JAVA Programming, Include 100 Questions & Answers
JAVA Programming, Include 100 Questions & Answers
Programming
AngularJS in 8 Hours
C# in 8 Hours
C++ in 8 Hours
Django in 8 Hours
Go in 8 Hours
JAVA in 8 Hours
JavaScript in 8 Hours
JQuery in 8 Hours
PHP in 8 Hours
Python in 8 Hours
R in 8 Hours
Ruby in 8 Hours
Rust in 8 Hours
What is Java?
Java Comments
Output Commands
Escaping Characters
Java Keywords
Data Types
Create a Variable
Arithmetical Operators
Logical Operators
Assignment Operators
Comparison Operators
Conditional Operator
Chapter 2 Statements
If Statement
If-else Statement
Switch Statement
For Loop
While Loop
Do-While Loop
Break Statement
Continue Statement
Boolean-Expression
Array Length
Element Value
Math Methods
String Connection
String Comparing
Extract a Character
Locate a Character
Extract a Substring
Case Change
Character Replace
StringBuffer
Return Value
Class Definition
Object Declaration
Constructor
Constructor Example
Overloading
“super” keyword
Overriding
Static variable
Static Method
final Variable
final Method( )
final class
Polymorphism
Abstract Example
Permission
Default Member
Public Member
Private Member
Private Example
Protected Member
Interface
Interface Example
Initializes Variables
Another Class
Finally Command
Throw Exception
Throws Exception
File Class
FileOutputStream
FileInputStream
Create Thread
Extends Thread
Implements Runnable
Multi-Thread
Thread’s Methods
Thread’s Example
100 Answers
Recommended Books
Chapter 1
Start JAVA
Install Java
In order to create any Java program, the Java development environment needs to be available on the
local computer system.
http://oracle.com/download
or
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Please click the link to download the newest version JDK at Oracle website. (Figure 1)
(Figure 2)
Please install the newest version of JDK to your computer.
Congratulation! Once JDK has been installed successfully, the system is ready to start running Java
programs!
IDE (Integrated Development Environment)
IDE (Integrated Development Environment) is used to write, edit and run Java. IDE contains many
Java development tools, compiler and debugger. There are many excellent free IDEs for download on
the internet, please download one IDE by the following links:
Eclipse http://www.eclipse.org
NetBeans https://netbeans.org/
DrJava http://www.drjava.org/
Jedit http://www.jedit.org/
BlueJ http://www.bluej.org/
JCreator http://www.jcreator.com/
Congratulation! Once an IDE has been installed successfully, you can write, edit and run Java
programs from now on.
What is Java?
Java is a class-based, object-oriented programming language, which is a secure, fast, and reliable
program for general-purpose such as internet, database, cell phone, countless variety of equipment.
Example 1.1
public class Hi
{
public static void main (String [ ] args)
{
System.out.print(“Hello World”);
}
}
( Output: Hello World )
Explanation:
“Public class” is two keywords; they are used to declare a Java program. “Hi” is a program name.
“public static void main (String [ ] args) {…}” is used to declare a main method.
“main” method contains main program codes to execute.
“String [ ] args” is used to accept the input manually.
“System.out.print( )” is used to display or print.
Each Java command should be ended with a semicolon (;).
Run First Program
Eclipse is one of the most popular Java IDE (Integrated Development Environment). It is used to
write, edit, debug and run Java programs.
Download Eclipse Installer
http://www.eclipse.org/downloads/
Please click the link to download the newest version Eclipse Installer at Eclipse website. (Figure 1)
(Figure 2)
(Figure 3)
Write & Run First Java Program
Step 1: Create a Java Project
Start up Eclipse > File > New > Java Project > Project Name > “FirstProject” > Finish. (Figure 4)
(Figure 4)
package newPackage;
System.out.print("Hello World!");
}
}
(Figure 8)
/* …… */
Java comments are used to explain the current code, describe what this code is doing. The Java
compiler will ignore comments.
// is used to single line comment.
/*…*/ is used in multi line comments
Example 1.3
System.out.println (“Hello World”); // show “Hello World”
/* System.out.println( ) is a Java output command, meaning display or print.
*/
Explanation:
// show “Hello World” is a single line comment.
/* System.out.println( ) is a Java output command, meaning display or print. */ is a multi line
comment.
Output Commands
System.out.print ( ); // print the result at the same line.
(Figure 1)
Select project “Test” > new > package > name > “myPackage” > Finish. (Figure 2)
(Figure 2)
package myPackage;
public class Calculation{
public static void main (String args[ ]){
int a = 100, b = 5; // define two variables
int c = a/b*10; // calculation
System.out.print("C = " + c); // output the value of “c”
}
}
Statements
If Statement
if ( test-expression ) { // if true do this; }
“if statement” executes codes inside { … } only if a specified condition is true, does not execute any
codes inside {…} if the condition is false.
Example 2.1
public class TryClass{
public static void main (String [ ] args){
int a=200;
int b=100;
if (a>b) { // if true, run the next command
System.out.print ( "a is greater than b.");
}}}
(Output: a is greater than b.)
Explanation:
( a>b ) is a test expression, namely (200>100), if returns true, it will execute the codes inside the { },
if returns false, it will not execute the codes inside the { }.
If-else Statement
if ( test-expression) { // if true do this; }
else { // if false do this; }
“if...else statement” runs some code if a condition is true and another code if the condition is false
Example 2.2
public class TryClass{
public static void main (String [ ] args){
int a=100; int b=200;
if (a>b){ // if true do this
System.out.print ( "a is greater than b.");
}
else { // if false do this
System.out.print ( "a is less than b");
}}}
(Output: a is less than b.)
Explanation:
( a>b ) is a test expression, namely (100>200), if returns true, it will output ”a is greater than b.” if
returns false, it will output “a is less than b”.
Switch Statement
switch ( variable )
{ case 1: if equals this case, do this; break;
case 2: if equals this case, do this; break;
case 3: if equals this case, do this; break;
default : if not equals any case, run default code;
break;
}
The value of the variable will compare each case first, if equals one of the “case” value; it will
execute that “case” code. “break;” terminates the code running.
Example 2.3
public class TryClass{
public static void main (String [ ] args){
int number=20;
switch ( number ) { // “number” value compares each case
case 10 : System.out.print ("Running case 10"); break;
case 20 : System.out.print ("Running case 20"); break;
case 30 : System.out.print ("Running case 30"); break;
default : System.out.print ("Running default code"); break;
}}} (Output: Running case 20)
Explanation:
The “number” value is 20; it will match case 20, so it will run the code in case 20.
For Loop
for( init, test-expression, increment) { // some code; }
“while loop” loops through a block of code if the specified condition is true.
Example 2.5
public class TryClass{
public static void main (String [ ] args){
int counter=0;
while (counter < 8){ // run 8 tmes
System.out.print ("&");
counter++;
}}}
( Output: &&&&&&&& )
Explanation:
“counter< 8” is a test expression, if the condition is true, the code will loop less than 8 times, until the
counter is 8, then the condition is false, the code will stop running.
Do-While Loop
do{ // some java code in here } while ( test-
expression);
“do...while” loops through a block of code once, and then repeats the loop if the specified condition
is true.
Example 2.6
public class TryClass{
public static void main (String [ ] args){
int counter=0;
do {
System.out.print ( "@");
counter++;
} while (counter<8); // run 8 times
}}
( Output: @@@@@@@@ )
Explanation:
“counter< 8” is a test expression, if the condition is true, the code will loop less than 8 times, until the
counter is 8, then the condition is false, the code will stop running.
Break Statement
Break;
“break” keyword is used to stop the running of a loop according to the condition.
Example 2.7
public class TryClass{
public static void main (String [ ] args){
int num=0;
while (num<10){
if (num==5) break; // leave the while loop
num++;
}
System.out.print( num );
}}
( Output: 5)
Explanation:
“if (num==5) break;” is a break statement. If num is 5, the program will run the “break” command,
the break statement will leave the while loop, then run “System.out.print(num)”.
Continue Statement
continue;
“continue” keyword is used to stop the current iteration, ignoring the following code, and then
continue the next loop.
Example 2.8
public class TryClass{
public static void main (String [ ] args){
int num=0;
while (num<10){
num++;
if (num==5) continue; // go to next while loop
System.out.print( num );
}}}
( Output: 1234678910)
Explanation:
Note that the output has no 5.
“if (num==5) continue;” includes “continue” command. When the num is 5, the program will run
“continue”, skipping the next command “System.out.print( num )”, and then continue the next while
loop.
Boolean-Expression
If ( bool-expression ) { statements }
while ( boolean-expression ) { statement }
The boolean-expression should be a test expression. For example: a>b; x<=y; m!=n; It cannot be a
variable only.
Example 2.9
public class TryClass{
public static void main (String [ ] args){
int num=10;
if( num ){ //error! because “num” is not a bool-expression
System.out.print ("No good");
}
while ( num ){ //error! for “num” is not a bool-expression
System.out.print ("No good");
}}}
Explanation:
if( num ) and while ( num ) is not correct codes, because it should be a boolean-expression inside the
( ), for example, if (num ==10) and while(num<10) are correct!
Hands-On Project: Run 100 Times
While Statement Program
Start up Eclipse > Select “myPackage” > new > class > name > WhileStatement > Finish.
Write following codes in Eclipse.
package myPackage;
public class WhileStatement {
public static void main(String[ ] args) {
int n = 1;
int sum = 0;
while(n <= 100){ // run 100 times
sum += n; // sum = sum + n
n++;
}
System.out.println("Sum = " + sum);
}
}
Click White Triangle Green Button in the tool bar to run the program and see the output:
Output:
Sum = 5050
Explanation:
“n<=100” is a test expression, if the condition is true, the code will loop less than 100 times, until the
counter is 100, then the condition is false, the code will stop running.
“sum += n;” is the same as “sum = sum + n”.
“n++;” means “n” increases 1in each loops.
Chapter 3
“Math.pow ( );” returns the first argument raised to the power of the second argument.
“Math.sqrt ( );” returns the square root of the argument.
Example 3.10
public class TryClass{
public static void main (String [ ] args){
int num = 4;
System.out.println("Square number is "+Math.pow(num,2) );
System.out.println("Square root is "+Math.sqrt(num) );
}}
( Output: Squared number is 16.0
Square root is 2.0)
Explanation:
“Maht.pow(num,2)” returns the first argument “4” raised to the power of the second argument “2”, the
result is 16.0
“Math.sqrt(num)” returns the square root of the argument “4”, the result is 2.0
Math.PI & random( )
Math.PI
Math.random( )
package myPackage;
public class TestArray {
public static void main(String[] args) {
int[]myArray;
myArray = new int[10]; //create an array “myArray”
for (int n = 0; n < myArray.length; n++){ // run 10 times
myArray[n] = n; // set the value of “n” to each array element
System.out.print(myArray[n] + ""); //output each element
}
}
}
Click White Triangle Green Button in the tool bar to run the program and see the output:
Output:
0123456789
Explanation:
“myArray = new int[10];” creates an array “myArray” with 10 elements.
“for (int n = 0; n < myArray.length; n++)” is a loop statement.
“int n = 0” initializes the variable “n” as 0.
“n < myArray.length” sets the loop’s number of times.
The loop’s number of times depends on the length of myArray.
“n++” means the variable “n” increases 1 in each loop.
“myArray[n] = n;” assigns value of “n” to myArray.
Chapter 4
String Processing
String Length
The String is consisted of one or more characters within double quotes. String.length( ) can get the
length of a string.
String.toUpperCase( );
String.toLowerCase( );
Example 4.7
public class TryClass{
public static void main(String args[ ]){
String Str = "Very Good"; System.out.println(Str.toUpperCase( ) );
System.out.println(Str.toLowerCase( ) );
}}
( Output: VERY GOOD )
( Output: very good )
Explanation:
“Str.toUpperCase( )” changes “Very Good” to “VERY GOOD”.
“Str.toLowerCase( )” changes “Very Good” to “very good”.
Character Replace
“str.replace( )” can change old characters to new characters in a string, and returns a new string
str.replace(oldCharacter, newCharacter);
Example 4.8
public class TryClass{
public static void main(String args[ ]){
String Str = "Very Good";
System.out.println( Str.replace("Good", "Well") );
}} // replace “Good” with “Well”
( Output: Very Well )
Explanation:
“Str.replace(“Good”, “Well”)” change the characters “Good” to character “Well” in string “Very
Good”, and return new string “Very Well”.
String Type Change
“Integer.toString(number)” can change a number to a string.
“String.trim( )” can remove spaces at the beginning or the end of a string.
Integer.toString( number);
String.trim( );
Example 4.9
public class TryClass{
public static void main(String args[ ]){
int num = 169;
String str = " Good "; // note that spaces.
String str1 = Integer.toString( num ); // convert to string
String str2 = str.trim( ); // remove spaces
System.out.println( str1+" is a String" );
System.out.println( str2+"is trimmed" );
}}
( Output: 169 is a String
Good is trimmed)
Explanation:
“Integer.toString( num )” converts an int number 169 to a string 169.
“str.trim( )” trims “ Good ” to a string “Good”.
StringBuffer
StringBuffer represents a string that can be dynamically changed. If a string value may change in
program running, please use StringBuffer, instead of String.
package myPackage;
public class TwoStrings {
public static void main(String[] args) {
String s1, s2, s3, s4;
s1 = "C++ in 8 Hours";
s2 = "C++ in 8 Hours";
s3 = "Python in 8 Hours";
s4 = s2; // assign the string value
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s3.equals(s4));
}
}
Click White Triangle Green Button in the tool bar to run the program and see the output:
Output:
true
false
false
Explanation:
“String s1, s2, s3, s4;” declares four string variables.
“s1.equals(s2)” compares two string’s value, if the two string’s value is the same, it returns true.
Chapter 5
Method, Class
& Object
Method
The Method is a code block that can be repeated to use.
class Class-name {
type variable;
type function-name( ) { }…
}
“obj = new Class-name( );” creates a new object named “obj” for the class.
“obj.variable;” means that “obj” references a variable.
“obj. function-name ( );” means that “obj” references a method.
Example 5.5
Color obj = new Color( ); // create an object “obj”
obj.c1= “yellow"; // an object references a variable
obj.c2=”purple”; // an object references a variable
obj.brightness ( ); // an object references a method
Explanation:
“Color obj = new Color;” creates an object named” obj”, then references variable “c1” and “c2”.
“obj.brightness ( );” calls the function “brightness ( );”(in previous page), and returns “blue”.
Class & Object
Example:
public class Color { // define a class
String c1, c2;
void brightness ( ) {
System.out.println("This flower is " + c1);
System.out.println("That flower is " + c2);
}
public static void main(String[] args) {
Color obj = new Color( ); // create an object
obj.c1= "yellow."; obj.c2="purple."; // references
obj.brightness ( ); // an object references a method
}}
Output:
This flower is yellow.
That flower is purple.
Explanation:
“public class Color { }” defines a class.
“Color obj = new Color( );” creates an object.
Constructor
The constructor is used to initialize variable. Constructor name is the same as class name.
class Class-name{
Class-name( ) { …} // constructor for initialization
}
package myPackage;
public class Message { // declare a class
String name, email, phone;
public Message(String theName, String theEmail, String thePhone){ // declare a constructor for
initialization
name = theName;
email = theEmail;
phone = thePhone;
}
void displayEmail(){ // declare a function
System.out.println("Email:" + email);
}
void displayPhone(){ // declare a function
System.out.println("Phone:" + phone);
}
public static void main(String[] args) { // main function
Message JACK = new Message ("JACK", "JACK@xxx.xxx", "678-xxx-9999"); //create an object
JACK, call the constructor
System.out.println(JACK.name);
JACK.displayEmail( ); // call a function
Click White Triangle Green Button in the tool bar to run the program and see the output:
Output:
JACK
Email:JACK@xxx.xxx
ANDY
Phone:567-xxx-0000
Explanation:
“public class Message” defines a class “Message”.
“public Message(……)” defines a constructor, initializes three string variables.
“ Message JACK = new Message (……)” creates an object “JACK”, and automatically calls the
constructor to initialize three string variables.
“JACK.name” references the variable “name”.
“JACK.displayEmail();” calls the function “displayEmail( )”.
“Message ANDY = new Message (……)”creates an object “ANDY”, and automatically calls the
constructor to initialize three string variables.
“ANDY.name” references the variable “name”.
“ANDY.displayPhone();” calls the function “displayPhone( )”.
Chapter 6
super ( argument );
“super ( argument );” is placed the first line in the constructor of sub class, to call the constructor of
the parent class.
Example 6.2
class super_class{
super_class (int x, int y){ // constructor
this.x=x; this .y=y;
}}
class sub_class extends super_class{
sub_class(int x, int y){ // constructor
super ( x,y ); // call the constructor of the parent class
}}
Explanation:
“super ( x,y );” calls the constructor in the super class.
Overriding
The method of sub class can override the method of the super class, if the method name and argument
are the same.
Example 6.3
class Super_class{
int test( int num ) { return num; } // overriding
}
class Sub_class extends Super_class{
int test( int num ) { return 100 + num; } // overriding
}
public class OverridingClass {
public static void main (String args[ ]){
Sub_class obj=new Sub_class( );
System.out.print( obj.test( 200 ));
}}
( Output: 300 )
Explanation:
When “obj.test( 200 )” calls the “int test( ){ }”, the “int test( ){ }” in sub class overrides the “int test(
){ }” in the super class, because they have the same name and same argument.
Overloading & Overriding
same method name, different argument,
overloading
in the same class.
same method name, same argument, in
overriding
between super class and sub class.
Example 6.4 (overloading)
class Color{ String x,y;
Color ( String a, String b) { x=a; y=b; } // overloading
Color ( ) { x=”yellow”; y=”purple”;} // overloading
}
Example 6.5 (overriding)
class super_class{
int test( int num ) { return num; } // overriding
}
class sub_class extends super_class{
int test( int num ) { return 100 + num; } // overriding
}
Explanation:
Example 1 is overloading. Example 2 is overriding.
Static variable
“static variable” is known as a class variable, it can be referenced by the class or object.
“Non static variable” cannot be referenced by class.
“Non static variable” can be referenced by object only.
Example 6.6
class MyClass {
static int count=100; // declare a static variable
public static void main (String args[ ]){
System.out.print( MyClass.count ); /* MyClass references a static variable “count” directly */
}} ( Output: 100 )
Explanation:
“static int count=100” defines a static variable.
“MyClass.count” means a class “MyClass” references a static variable “count” directly.
Note that an object can also reference static variable.
Static Method
“static method” is known as a class method, it can be called by the class or object.
“Non static method” cannot be referenced by class.
“Non static method” can be referenced by object only.
Example 6.7
class MyClass {
static int count( ) { return 100 ;} // declare a static method
public static void main (String args[ ]){
System.out.print( MyClass.count( ) ); /* MyClass calls a static method “count()” directly */
}}
( Output: 100 )
Explanation:
“static int count( ) { return 100 }” defines a static method.
“MyClass.count( )” means a class “MyClass” calls a static method “count()” directly.
Note that an object can also call static method.
final Variable
“final” is a keyword.
“final+ variable” means that variable value cannot be modified.
Example 6.8
class MyClass{
final int x =100; // declare a final variable
static void test( ){ x = 200;} // error! for “x” is a final variable
public static void main (String args[ ]){
System.out.print( MyClass.test( ) );
}
}
Explanation:
“final int x =100” defines a final variable “x”, its value is 100 and cannot be changed.
“static void test( ) { x = 200;}” tries to modify the value of “x”, but an error occurs.
final Method( )
“final” is a keyword.
“final method( )” means that method cannot be overridden.
Example 6.9
class animal{
final void test ( ){ // declare a final method
System.out.print(“animal”);
}}
class dog extends animal {
void test ( ){ // error! for test() want to override…
System.out.print(“dog”);
}
}
Explanation:
“final void test( ){…}” defines a final method.
“void test ( ){…}” tries to override “final void test( ){…}”, but error occurs.
final class
“final” is a keyword.
“final class” means that class cannot be extended.
Example 6.10
final class animal { // declare a final class
// define some variables;
// define some method;
}
class elephant extends animal { // error! cannot extends
// define some variables;
// define some method;
}
Explanation:
“final class animal {… }” defines a final class “animal”, which means “animal” class cannot be
extended.
“class elephant extends animal { …}” tries to extend super class “animal”, but an error occurs.
Polymorphism
Polymorphism describes the ability to perform different method for different objects.
Example 6.11
class Animal{ // parent class
void cry( ){
System.out.println("crying......");;
}
}
class Dog extends Animal{ // sub class
void cry( ){ // overriding
System.out.println("Wow, Wow......");
}
}
class Cat extends Animal{ // sub class
void cry( ){ // overriding
System.out.println("Meow, Meow......");
}
}
class PolymorphismDemo{
public static void main(String args[ ]){ // main function
Animal animalVar;
animalVar = new Dog( ); // create a dog object
animalVar.cry( ); // dog object calls cry()
animalVar = new Cat( ); // create a cat object
animalVar.cry( ); // cat object calls cry()
}
}
Output:
Wow, Wow……
Meow, Meow……
Explanation:
“animalVar = new dog( )” creates a dog object, therefore, “animalVar.cry( )” calls a method cry( ) in
sub class Dog.
“animalVar = new cat( )” creates a cat object, therefore, “animalVar.cry( )” calls a method cry( ) in
sub class Cat.
Package & Import
package package-name;
import package.class;
(In TestDrive.java)
package myPackage; // use “myPackage”
import myPackage.Drive; // import class “Drive” in myPackage
public class TestDrive{
public static void main (String args[ ]) {
Drive myDrive = new Drive( );
myDrive.getDistance(120, 5);
}
}
Output:
SPEED: 120 MILES/HOUR
TIME: 5 HOURS
DISTANCE: 600 MILES
Explanation:
“package myPackage;” creates a package “myPackage” in Drive.java file.
“import myPackage.Drive;” imports a class “Drive” of “myPackage”.
“Drive myDrive = new Drive( )” can create an object “myDrive” in file TestDrive, because Drive
class has been imported from Drive.java file.
“myDrive.getDistance(120, 5);” calls a method in Drive.java file.
Note: “package” command must be in above of the “import” command.
Hands-On Project: Inheritance
Inheritance Example
Start up Eclipse > Select “myPackage” > new > class > name > InheritanceDemo > Finish.
Write following codes in Eclipse.
package myPackage;
class code1{ // parent class
int x, y;
code1(int a, int b){ // constructor
x = a; y = b;
}
}
class code2 extends code1{ // sub class
code2 (int a, int b){ // constructor
super (a,b); // call the constructor in the parent class
}
}
public class InheritanceDemo {
Click White Triangle Green Button in the tool bar to run the program and see the output:
Output:
Sum = 300
Explanation:
“class code1” creates a super class “code1”.
“code1(int a, int b){ }” defines a constructor.
“class code2 extends code1” creates sub class “code2” that extends super class “code1”.
“code2 (int a, int b){ }” defines a constructor.
“super (a,b)” calls the constructor in super class so as to initialize the variable x and y.
same class V V V V
same
package V V X V
parent class
same
package V V X V
sub class
different
package X V X X
parent class
different
package X V X V
sub class
default member cannot be accessed by different package.
public member can be accessed by any package & class.
private member cannot be accessed by a different class.
protected member can be accessed by any sub class.
Default Member
default member cannot be accessed by different package, Note that package name must be the same
as directory name where the package locates.
package myPackage;
package myPackage;
}
Output:
100
Explanation:
Public member can be accessed by any package or any class, specially in different packages.
Example 7.3
package myPackage;
package newPackage;
import myPackage.ParentClass;
}
Output:
100
Explanation:
package myPackage;
package newPackage;
import myPackage.ParentClass;
}
Output:
100
Explanation:
“s.num” can access a protected member from sub class in different packages.
Interface Explanation:
interface books { //define an interface
int booknumber( ); //define an empty method
}
class eBooks implement books { //implement
interface
public int booknumber ( ) { //implement the
empty method
return …;
}
}
Initializes Variables
When creating an object, it needs a constructor to initialize the variables.
Example 7.7
class Book { // create a class
public String title;
public int number;
public Book ( ) { // define a constructor
title = “Learning Java ”; // initialization
number = 100; // initialization
}}
public class Publisher { // create main class
public static void main ( String args [ ]) { //main method
Book eBook = new Book ( ); // create an object
System.out.print( eBook.title + eBook.number);
}}
( Output: Learning Java 100 )
Explanation:
public Book ( ) { } is a constructor to initialize variables.
Another Class
Main class can use another-class to call another-method.
Example 7.8
class AnotherClass{ // define another class
public static void AnotherMethod( ){ // another method
System.out.print ( “Very Good” ); }
}
public class MainClass{ //define main class
public static void main (String args [ ]){ // main method
AnotherClass.AnotherMethod( ); //call another method
}
}
( Output: Very Good )
Explanation:
“AnotherClass.AnotherMethod( )” use another class to call another method.
Hands-On Project: Max & Min
Abstract Example
Start up Eclipse > Select “myPackage” > new > class > name > AbstractDemo > Finish.
Write following codes in Eclipse.
package myPackage;
abstract class A{ // define an abstract class
abstract int max(int x, int y); // define an abstract method
int min(int x, int y){
return x<y?x:y;
}}
class B extends A{ // extend the parent class
int max(int x, int y){ // override the abstract method
return x>y?x:y;
}}
package myPackage;
interface myInterface{ // define an interface
public void compareNumbers(int num1, int num2); /* define an empty method */
}
class MaxNum implements myInterface{ //implement interface
public void compareNumbers(int num1, int num2){ /* implement the empty method */
System.out.println("Two numbers are: "+num1+" & "+num2);
if (num1>=num2)
System.out.println("Maxmum is:"+num1);
else
System.out.println("Maxmum is:"+num2);
}
}
class MinNum implements myInterface{
public void compareNumbers(int num1, int num2){
System.out.println("Two numbers are: "+num1+" & "+num2);
if (num1<=num2)
System.out.println("Minmum is:"+num1);
else
System.out.println("Minmum is:"+num2);
}
}
public class InterfaceDemo {
public static void main(String[] args) {
MaxNum maxObject = new MaxNum();
maxObject.compareNumbers(100, 120);
MinNum minObject = new MinNum();
minObject.compareNumbers(60, 80);
}
}
Click White Triangle Green Button in the tool bar to run the program and see the output:
Output:
Two numbers are: 100 & 120
Maxmum is:120
Two numbers are: 60 & 80
Minmum is:60
Explanation:
“interface myInterface” defines an interface named “myInterface”.
“void compareNumbers ( )” defines an empty method “void compareNumbers( )”.
“class MaxNum implements myInterface { }” means class “MaxNum” implements “myInterface”
interface.
“class MinNum implements myInterface { }” means class “MinNum” implements “myInterface”
interface.
“public void compareNumbers( ){ }” implements the empty method compareNumbers( ) in the
interface.
Chapter 8
An exception is an error that occurs during the running of a program that breaks the normal flow of
commands.
Example 8.1
System.out.print ( c );
}}
“throw” is used to throw an exception and error message manually. “e.getMessage( )” can display
error messages.
Example 8.6
public class ExceptionSample {
public static void main (String args [ ]) {
try {
int a[ ] = new int[10]; // the last element is a[9], without a[10].
if ( a[10] >0 ) throw new ArrayIndexOutOfBoundsException("Error"); // throw
}
catch ( ArrayIndexOutOfBoundsException e) {
System.out.print ("Error index:"+e.getMessage( )); // alert
}}} ( Output: Error index: 10 )
Explanation:
“throw new exception(“…”)” can throw an exception.
Throws Exception
Any method can be ready to throw its own exceptions manually. “e.getMessage( )” displays the error
message.
Explanation:
“int calculate( int num) throws ArithmeticException” throws an exception.
“e.getMessage( )” displays the error message.
File Class
File class is used to display the property of the file, to check the file existence, writable, readable, to
rename the file……
package myPackage;
import java.io.*;
public class InputFile {
public static void main(String[] args) {
char ch;
int number;
try{
FileInputStream fin = new FileInputStream("MyFile.txt");
while((number=fin.read())!= -1) // read the file
System.out.print((char)number); // change to characters
fin.close();
}
catch(FileNotFoundException e){
System.err.println(e);
}
catch(IOException e){
System.err.println(e);
}}}
Output:
C++ is very good!
Explanation:
“fin” is an input stream object.
“fin.read()” reads the content of MyFile.txt
“-1” indicates the end of file.
Create Thread
Threads can be used to perform multiple tasks simultaneously. Each thread represents a subtask.
There are two methods to create a thread.
Method One:
Click White Triangle Green Button in the tool bar to run the program and see the output:
Output:
Red
Yellow
Green
Exception Occurs!
Array Index is Out of Range!
Explanation:
In array “String color[ ]={"Red", "Yellow", "Green"};”, if the index equals 3, an exception occurs.
Hands-On Project: Mult Tasks
Multi-Thread Program
Step 1: Create a Java Project
Start up Eclipse > File > New > Java Project > Project Name > “ThreadProject” > Finish. (Figure 1)
(Figure 1)
package threadPackage;
public class ThreadClass {
public static void main(String[] args) { // main function
myThread thread1=new myThread("Thread One");
myThread thread2=new myThread("Thread Two");
thread1.start(); // start thread
thread2.start(); // start thread
}
}
1. Which following Java statement will generate the output of “Hello World!”?
1. System.output.println("Hello World!”);
2. cout<<“Hello World!”<<endl;
3. echo (“Hello World!”);
4. System.out.println(“Hello World!”);
4. What will be the output of the following code if it is started from the command line using “java
test app boy cat dog”?
public class test {
public static void main (String[ ] args){
System.out.println(args[3]);
}
}
What is the output?
1. app
2. boy
3. cat
4. dog
6. \n will force a new line break in the output, \t will make a tab spacing in the output, \’’ will_____?
1. allow quotation marks to be used inside strings.
2. allow backspace to be used inside strings.
3. allow return to be used inside strings.
4. allow back slash to be used inside strings.
15. Which following code can count the total number of elements in an array?
1. arrayName.size
2. arrayName.length
3. arrayName.count
4. arrayName.length( )
1. 7 8
2. 7 7
3. 8 8
4. 8 7
18. What is the result of math.ceil(-7.5) & math.floor ( -7.5)?
1. -7 -8
2. -7 -7
3. -8 -8
4. -8 -7
1. 8 -8
2. 8 -7
3. 7 -8
4. 7 -7
int index=1;
int b=arr[index];
1. a value is 0
2. a value is 1
3. a value is 2
4. compile failure
21. Which following can create an array?
int a=3;
int b=10;
b=a++-1;
1. 2
2. 3
3. 4
4. 5
int a=3;
int b=10;
b=++a-1;
1. 2
2. 3
3. 4
4. 5
1. >>
2. <<
3. >>>
4. <<<
int val=-10;
System.out.println((val>”Negative”)?10:”Negative”);
1. 10
2. Negative
3. Positive
4. compile failure
26. What is the output of the following code?
boolean a = true;
boolean b = false;
if( (!b) || (a));
boolean c=(false?a:b);
System.out.print(c);
1. true
2. false
3. 0
4. compile failure
int i=1;
while (i){
if (i==3){
break;
++i;
System.out.print(i);
1. 1
2. 2
3. 3
4. compile failure
int x=5;
int y=6;
if (x=y){
System.out.println("5");}
else
System.out.println("6");
1. 5
2. 6
3. 0
4. compile failure
boolean test=true;
if (test=false) {System.out.println(“One”);}
else {System.out.println(“Three”);}
1. One
2. Two
3. Three
4. Compile failure
char num='b';
switch (num) {
1. B
2. BD
3. BCD
4. Compile failure
int num=10;
if(num>0)
if(num>100)
if(num>1000)
System.out.println("1000");
else
System.out.println("100");
else
System.out.println("10");
1. compile failure
2. 1000
3. 100
4. 10
1. if(integer-expression) …
2. if(char-expression) …
3. if(float-expression)…
4. if(boolean-expression)…
System.out.print(a[n]);
int num=2;
if (++num==num++)
System.out.print(“A”);
else
System.out.print(“B”);
1. A
2. B
3. 2
4. compile failure
String x=”A”;
if (y[1]) { x=”B”;}
else { System.out.print(x); }
1. A
2. B
3. ““
4. null
int num=100;
switch(num){
default: System.out.println(“default”);
1. A
2. default
3. default A
4. compile failure
if(n%9==0)
break;
if(n%3==1)
continue;
System.out.print(n);
1. 24689
2. 21678
3. 26137
4. 23568
45. What is the output of the following code?
int n=0;
while(true){
if(n++>10) break;
System.out.println(n);
1. 11
2. 12
3. 13
4. compile failure
class test{
private int x;
private int y;
test(int x, int y ){
this.x=x; // line1
this.y=y; // line2
}
}
class subtest extends test{
subtest(int x, int y) { //line3
int s = x + y;
super(x, y); // line4
}
}
……
1. line1
2. line2
3. line3
4. line4
80. If you want to restrict the access of member to current class from another class, which following
modifier should you choose?
1. default
2. private
3. public
4. protected
90. Which following statement is not correct when connect two strings?
1. operator”+” can connect two StringBuffer objects.
2. operator”+” can connect two String objects.
3. append( ) can connect two StringBuffer objects.
4. concat( ) can connect two String objects.
91. Which following code can create an array with 3 empty strings?
1. String arr [3];
2. String arr [ ]={null, null, null};
3. String arr [ ]={“ “, “ “, “ “};
4. String arr [ ]=new String [3];
for (int i=0; i<3; arr[i++]=null);
105. Which following object can use “throws” when exception occurred?
1. Event
2. Object
3. String
4. EOFException
106. java.io Package does not include_______.
1. InputStream Class
2. OutputStream Class
3. File Class
4. FileDescription Class
111. If the size of a file myFile.txt is 100 bytes, then after running
File f=new File("myFile.txt");
System.out.print(f);
112. When using read( ) in java.io.InputStream or write( ) in java.io.OutStream, you may handle an
exception which is ______.
1. java.io.InputException
2. java.io.OutputException
3. java.io.InputOutputException
4. java.io.IOException