JAVA100 Tests, Answers & Explanations
A Beginner’s GuideBy Ray Yao
Copyright © 2015 by Ray Yao
All Rights ReservedNeither part of this e-book nor whole of this e-book may be reproduced or transmitted in any form or by any means electronic,photographic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without prior writtenpermission from the author.
Ray Yao
About the Author
Ray Yao:Certified PHP engineer by Zend, USA
Certified JAVA programmer by Sun, USA
Certified SCWCD developer by Oracle, USA
Certified A+ professional by CompTIA, USA
Certified ASP. NET expert by Microsoft, USA
Certified MCP professional by Microsoft, USA
Certified TECHNOLOGY specialist by Microsoft, USA
Certified NETWORK+ professional by CompTIA, USA
Ray Yao's books:
Linux Command Line (eBook)
Linux Command Line (Paper Book)
JAVA 100 Tests, Answers & Explanations
PHP 100 Tests, Answers & ExplanationsJavaScript 100 Tests, Answers & Explanations
JAVA in 8 Hours
PHP in 8 Hours
JavaScript in 8 Hours
C++ in 8 Hours
AngularJS in 8 Hours
JQuery in 8 Hours
Preface“The Java 100 Tests; Answers & Explanations” is a useful book for beginners. From this book, youcan test:
Java Basic; Control Statement; Array; Function; If, Switch statement; For, While loop; Class, Object,Method & Interface; String & StringBuffer; Exception; Input & Output……This book can help beginners to understand the basic of JAVA. The straightforward answers, the plainand simple explanations can make beginners quickly learn the JAVA fundamental knowledge.
Test example 1:
11. Which following line is not correct?
import java.util.Date; // line1
package myPackage; // line2
class myClass1 extends Date{…} // line3class myClass2 extends Date{…} // line4
1. line12. line23. line34. line4
Answer : ……
Explanation: ……
Test example 2:5. What is the output in the following code?
FileInputStream in=new FileInputStream(“myfile.java”);byte b[ ]=new byte[10];
int d=in.read(b);
System.out.print(d);
1. 102. 203. not sure.4. compile failure.
Answer: ……
Explanation: ……
This book is completely suitable for beginner’s fast learning.
Table of Contents
PrefaceChapter 1 Java BasicChapter 2 Control Statement, Array, FunctionChapter 3 Class, Object, Interface & MethodChapter 4 Class, Object, Interface & MethodChapter 5 Class, Object, Interface & MethodChapter 6 String & StringBufferChapter 7 ExceptionChapter 8 Input & OutputConclusion
Chapter 1 Java Basic
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!”);
(The answer & explanation is in the next page.)
1. Answers: D
Explanation:
System.out.println( ) or System.out.print( ) is a standard output function used in java.
A is wrong, It should be “out” instead of “output”.
B is a C++ statement.C is a PHP statement.
2. For public class Hello { }, which following statement is correct?
1. The Java’s file name should be Hello.javac.2. The Java’s file name should be Hello.javadoc.3. The Java’s file name should be Hello.java.4. The Java’s file name should be Hello.class.
2. Answer: C
Explanation:
Java program files are saved with their exact class name and with the file extension ”.java”. Therefore, the program is saved as a file named “Hello.java”.
3. Which following statement is not correct?
1. The value range of byte is -128~1272. The value range of short is -32768~327673. The value range of int is -3276800~32767004. The value range of char is 0~65535
3. Answer: C
Explanation:
The value range of int is -2147483648 ~ 2147483647.
4. What will be the output of the following code if it is started from the command line using “java testapp boy cat dog”?
public class test {
public static void main (String[ ] args){
System.out.println(args[3]);
}
}
What is the output?
1. app2. boy3. cat4. dog
4. Answer: D
Explanation:
When using “java test app boy cat dog”, that will assign the value to string array. args[0]=app,args[1]=boy, args[2]=cat, args[3]=dog.
5. About Java comments, which following is correct?
1. // is used in multiple line comments2. /* */ are used in single line comments3. Both // and /* */ can be used in single line or multiple comments.4. // is used in single line comments and /* */ are used in multiple comments.
5. Answer: D
Explanation:
In Java, // is used in single line comments and /* */ are used in multiple comments.
6. \n will force a new line break in the output, \t will make a tab spacing to 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.
6. Answer: A
Explanation:
\” will allow quotation marks to be used inside strings.
7. To create a variable, and assign a value, use___?1. variableName=value;2. var variableName=value;3. dataType variableName=value;4. modifier variableName=value;
7. Answer: C
Explanation:
To create a variable, and assign a value, use the syntax like this:
dataType variableName = value;
8. Which following is not a valid variable name?
1. myVar2. 10Var3. _myVar4. $myVar
8. Answer: B
Explanation:
All variable names should start with letter, underscore character or a $ symbol. Numbers may be usedelsewhere in the name. Spaces are not allowed in variable names.
9. Which following can be use as variable name?
1. char2. float3. try4. nonVir
9. Answer: D
Explanation:
Java keywords cannot be used in variable names. char, float and try are java keywords.
10. Which following keyword description is not correct?
1. “char” is used to a single Unicode character.2. “float” is used to a floating-point number with a decimal point.3. “integer” is used to an integer number from-2.14 billion to 2.14 billion.4. “boolean” is used to a boolean value of true or false.
10. Answer: C
Explanation:
“int” is used to an integer number from-2.14 billion to 2.14 billion. “int” is a keyword, “integer” isnot a keyword.
11. Which following operator description is not correct?
1. + is used in addition2. – is used in subtraction3. * is used in multiplication4. % is used in division
11. Answer: D
Explanation:
% is used in modulus. / is used in division.
12. Which following express is not correct?
1. a += b means a = (a + b)2. a *= b means a = (a * b)3. a != b means a = (a ! b)4. a %= b means a = (a % b)
12. Answer: C
Explanation:
!= means “not equal to”.
About” !b”, if the variable “b” had a value of true, then “!b” would have a value of false.
13. Which following line is not correct?
String str=good;
if ((str!=good)&&(str.length<100)) // line1
{System.out.print(“compile succeed”)} // line2
else if ((str!=good)&(str.length<100)) // line3
{System.out.print(“compile failure”)} // line4
else {System.out.print(“end”);}
1. line12. line23. line34. line4
13. Answer: C
Explanation:
The && operator has "short-circuit" function, meaning it doesn't evaluate the right hand side if the lefthand side is false.
The || operator has "short-circuit" function, meaning it doesn't evaluate the right hand side if the lefthand side is true.
To know a string size, you should use string.length( ).To know an array size, you should use array.length.
Therefore, string.length is not correct.
14. Which following statement cannot create an array?
1. int[ ] myArray = [1,2,3];2. int[ ] myArray = new int[3];3. int[ ] myArray = {1,2,3};4. int[ ] myArray = new int[ ]{1,2,3};
14. Answer: A
Explanation:
Please use { } rather than [ ].
For example: int[ ] myArray = {1,2,3};
15. Which following code can count the total number of elements in an array?
1. arrayName.size2. arrayName.length3. arrayName.count4. arrayName.length( )
15. Answer: B
Explanation:
“arrayName.length” is used in array size.
“StringName.length( )” is used in string size.
16. Which following statement of Math method is not correct?
1. ceil( ) returns an integer that is greater than or equals to its argument.2. log( ) returns a natural logarithm of a number3. sqrt( ) returns a square root of a number4. floor( ) returns a closest value equal to an integer.
16. Answer: D
Explanation:
floor( ) returns an integer that is less than or equals to its argument.
17. What is the result of math.ceil (7.5 ) & math.floor (7.5)?
1. 7 82. 7 73. 8 84. 8 7
17. Answer: D
Explanation:
ceil( ) returns an integer that is greater than or equals to its argument.
floor( ) returns an integer that is less than or equals to its argument.
18. What is the result of math.ceil(-7.5) & math.floor ( -7.5)?
1. -7 -82. -7 -73. -8 -84. -8 -7
18. Answer: A
Explanation:
ceil( ) returns an integer that is greater than or equals to its argument.
floor( ) returns an integer that is less than or equals to its argument.
19. What is the result of math.round (7.5), math.round (-7.5)?
1. 8 -82. 8 -73. 7 -84. 7 -7
19. Answer: B
Explanation:
About round(-argument):
If the fractional part of a negative argument is less than or equal to 0.5, the result returned is the sameas Math.ceil( ).
If the fractional part of a negative argument is greater than 0.5, the result returned is the same asmath.floor( ).
20. What is the output?
int index=1;
int arr[ ]=new int[5];
int b=arr[index];
int a=b+ index;
1. a value is 02. a value is 13. a value is 24. compile failure
20. Answer: B
Explanation:
int b=arr[1] does not mean b=1, b still equals to 0.
21. Which following can create an array?
1. array a=new Array(3);2. int a[ ]=new int(3);3. int a[ ]=new int[3];4. int a[3]={1,2,3};
21. Answer: C
Explanation:
int a[ ]=new int[3] can create an array. Please use [ ] instead of ( ).
22. What is the value of b of the following code?
int a=3;
int b=10;
b=a++-1;
1. 22. 33. 44. 5
22. Answer: A
Explanation:
“b=a++-1” means:
“a” minus 1 first and assign the value to “b”, and then “a” increases 1.
23. What is the value of b of the following code?
int a=3;
int b=10;
b=++a-1;
1. 22. 33. 44. 5
23. Answer: B
Explanation:
“b=++a-1” means:
“a” increases 1first, and then it minus 1, assign the value to b.
24. Which of the following is not an operator in java?
1. >>2. <<3. >>>4. <<<
24. Answer: D
Explanation:
>> is the shift-right-with-sign-fill operator.
<< is the shift-left operator.
>>> is the shift-right-will-zero-fill operator.<<< is not the java operator.
25. What is the output in following code?
public static void main(String args[ ]){
int val=-10;
System.out.println((val>0)?10:”Negative”);
}
1. 102. Negative3. Positive4. compile failure
25. Answer: D
Explanation:
For (exp)?(exp1):(exp2), the data type in (exp1) and (exp2) should be the same.
In here, (exp1) is an integer; (exp2) is a string. They are different data type, so cannot pass thecompile. (This is quite different from C++.)
Chapter 2 Control Statement
1. What is the output in the following code?
boolean a = true;
boolean b = false;if( (!b) || (a));
boolean c=(false?a:b);
System.out.print(c);
1. true2. false3. 04. compile failure
1. Answer: B
Explanation:
(test-expression) ? (if-true-do-this) : (if-false-do-this). so when running “c=false?a:b)”, c=b, resultis false.
2. Which following is a correct statement?
1. if ( ) { } else { }2. if ( ) then { } else { }3. if ( ) then { } then else { }4. if ( ) then { } if else { }
2. Answer: A
Explanation:
In Java, if statement has no “then”. It is quite different from VB.
3. What is the output?
int result = 0;
for( int n=1; n<=100; n++)
result+=n;
System.out.println(result);
What is the output?
1. 1002. 10003. 50004. 5050
3. Answer: D
Explanation:
The sum of 1+2+3+……100 is 5050.
4. What is the output?
int i=0;
while(i< 10)
{
++i;
if(i==3) break;
System.out.println(“The number is”+i);
}What is the output?
1. The number is 12. The number is 1 The number is 23. The number is 1 The number is 2 The number is 34. The number is 1,2,3
4. Answer: B
Explanation:
When execute “if(i==3) break;”, the program will break through the current loop.
5. What is the output?
int i=0;
while (i<4)
{
++i;
if ( i ==2) continue;
System.out.println(“The number is”+i);
}What is the result?
1. The number is 12. The number is 1 The number is 23. The number is 1 The number is 34. The number is 1,2,3
5. Answer: C
Explanation:
When execute “if ( i ==2) continue;” the program will skip the following line of code, and continuethe next loop.
6. What will be the output?
char num = 1;
switch (num) {
case 1:
System.out.println (“one”);
case 2:
System.out.println (“two”);
case 3:System.out.println (“three”); break;
default:
System.out.println (“four”); break;
}
1. one2. one two3. one two three4. one two three four
6. Answer: CExplanation:
Because case1 and case 2 have no “break”, the program will keep running until meet the “break”.
7. What is the output?
public static void main (String[] args){
int i=1;
while (i){
if (i==3){
break;
}
++i;
}
}
1. 12. 23. 34. compile failure
7. Answer: D
Explanation:
while(i) is error. It should be while(i==1) or while(i!=1).
8. What is the output?
public static void main (String[ ] args){
int x=5;
int y=6;
if (x=y){
System.out.println(“5”);
else
System.out.println(“6”);
}
}
1. 52. 63. 04. compile failure
8. Answer: D
Explanation:
if (x=y) is error. It should be if(x==y) or if(x!=y).
9. What is the output in following code?
boolean test=true;
if (test=false) {System.out.println(“One”);}
else if (test) {System.out.println(“Two”);}
else {System.out.println(“Three”);}
1. One2. Two3. Three4. Compile failure
9. Answer: C
Explanation:
“test=false” means to assign the false to test.
“if (test=false)” equals to “if (false)”, then will not execute the codes inside its { }.
10. What is the output in following code?
char num=”b”;
switch (num) {
case “a” : System.out.print(“A”);
case “b” : System.out.print(“B”);
case “c” : System.out.print(“C”);
default: System.out.print(“D”); break;
}
1. B2. BD3. BCD4. Compile failure
10. Answer: C
Explanation:
Because case b and case c have no “break”, the program will keep running until meet the “break”.
11. Which following line is not correct?
import java.util.Date; // line1
package myPackage; // line2
class myClass1 extends Date{…} // line3
class myClass2 extends Date{…} // line4
1. line 12. line 23. line 34. line 4
11. Answer: A
“import” statement should be placed after package declaration, and before class definition.
12. Which following statement is not correct?
int a=1;
1. do{ break;} while ( a>0 ); 2. if(a>0) { break;} 3. switch (a) { default : break;} 4. for( ;a>0; ) break;
12. Answer: B
Explanation:
“break” is not used in if statement.
“break” is only used in break out of loops or switch statements.
13. What is the output in the following code?
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 failure2. 10003. 1004. 10
13. Answer: D
Explanation:
The second if belongs to the second else. The third if belongs to the first else.
14. For if (expression), which following type is correct?
1. if(integer-expression) …2. if(char-expression) …3. if(float-expression)…4. if(boolean-expression)…
14. Answer: D
Explanation:
About if(boolean-expression):
For example: if(100), if(x=100), if(char c) are not correct.
If(true), if(false), if(boolVir=false) are correct.
15. Given code:
System.out.print(a[n]);
Which following code can display all elements in array int a[ ]?
1. for(int n=0;n<a.length-1; n++)2. for(int n=0;n<a.length+1; n++)3. for(int n=0;n<a.length; n++)4. for(int n=0;n<a.length( ); n++)
15. Answer: C
Explanation:
for(int n=0;n<a.length; n++) use a correct syntax.
16. What is the output in the following code?
int num=2;
if (++num==num++)
System.out.print(“A”);
else
System.out.print(“B”);
1. A2. B3. 24. compile failure
16. Answer: B
Explanation:
About ++num:
“num” increases 1first, and then runs the expression.
About num++:
“num” runs the expression first, and then increases 1.
17. What is the output in the following code?
String x=”A”;
boolean[ ] y=new boolean[10];
if (y[1]) { x=”B”;}
else if { System.out.print(x); }
1. A2. B3. “ “4. null
17. Answer: A
Explanation:
array y[1] has not assigned any new value, it still has a default value as fault.
18. What is the output in the following code?
int num=100;
switch(num){
default: System.out.println(“default”);
case 0: System.out.println(“A”); break;
case 1: System.out.println(“B”); break;
case 2: System.out.println(“C”); break;
1. A2. default3. default A4. compile failure
18. Answer: C
Explanation:
Because “default: System.out.println(“default”)” has no “break”, the program will run the nextstatement.
19. What is the output in the following code?
for (int n=1; n<20; n++){
if(n%9==0)
break;
if(n%3==1)
continue;
System.out.print(n);
}
1. 246892. 216783. 261374. 23568
19. Answer: D
Explanation:
When i equals to 9, “break” will break through current loop, so the program outputs until 8.
If meet the condition i%3==1, “continue” will turn to the next loop and not to run the next statement.
20. What is the output in the following code?
int n=0;
while(true){
if(n++>10) break;
}
System.out.println(n);
1. 112. 123. 134. compile failure
20. Answer: B
Explanation:
When the value “n” is 11, n>10, and runs “break”. After running the expression, the ”n” will increase1, and become 12.
Chapter 3 Class, Object, Interface & Method
1. Which following statement can prevent creating sub class?
1. static class test{ }2. public class test{ }3. abstract class test{ }4. final class test{ }
1. Answer: D
Explanation:
Final variable cannot be modified.
Final method cannot be overridden.
Final class cannot be extended.
2. Which following line is not correct?
class test extend Object{
int x=1; int y=2; // line1
void fun( ){ // line2
int y=0; // line3
for (int y=10; y<100; y++){…} // line4}
}
1. line12. line23. line34. line4
2. Answer: D
Explanation:
In the for loop expression, the variable “int y” is the same name as another local variable name,which will cause error.
3. Which following line is not correct?
class test {
int x=1; // line1
int y=2; // line2
}
public class study{
public static void main(string args[ ]){
test t=new test(1,2); // line3System.out.println(t.x+t.y); } // line4
}
1. line12. line23. line34. line4
3. Answer: C
Explanation:
test class has no constructor method test(arguments){ },
so when using test t=new test(1,2), it will cause error.
4. Which following line is not correct?
class test {
int myMethod( ){ return 10; } // line1
void myMethod( ){ int num =10; } // line2
}
public class study{
public static void main(string args[]){test t=new test( ); // line3
t.myMethod( ); // line4
}
1. line12. line23. line34. line4
4. Answer: D
Explanation:
When using t.myMethod( ), t is not sure to call which myMethod( ).
5. Which following line is not correct?
class test{ // line1
private int x=1; y=2; // line2}
class subtest extends test{
int m=10; // line3
int n=m+x+y; // line4
}
1. line12. line23. line34. line4
5. Answer: D
Explanation:
In Java, the member in sub class cannot access the private member in super class.
6. Which following line is not correct?
class test{
test(int x, int y ){
this.x=x; // line1
this.y=y; // line2
}
}
class subtest extends test{subtest(int m, int n){
int sum=m+n; // line3
super(x,y); // line4
}
}
……1. line12. line23. line34. line4
6. Answer: D
Explanation:
“super” statement should be placed in the first line in constructor method.
7. Which following statement is correct?
1. Overriding occurs only in one class.2. Overloading occurs only in one class.3. Overriding occurs only between super class and sub class.4. Overloading occurs only between super class and sub class.
7. Answer: C
Overriding occurs only between super class and sub class.
8. Which following line is not correct?class test{
static int num=10; // line1
}static int myMethod( ){ // line2
return this.num; // line3
System.out.print(num); // line4
}
1. line12. line23. line34. line4
8. Answer: C
“this” cannot call a static method or static variable.
9. Which following line is not correct?public class test{
public void myMethod( ){
static int num=10; // line1
System.out.print(num); // line2
}
}
public static void main (String args[ ]){
test obj=new test( ); // line3obj.myMehtod( ); // line4
}
1. line12. line23. line34. line4
9. Answer: A
Static variable cannot be defined inside a method. Static variable belongs to a class.
10. Which following line is not correct?class test{
final int m=10; // line1
void myMethod(final int n=20){ // line2
n=100; // line3
System.out.print(m+n); // line4
}
}
1. line12. line23. line34. line4
10. Answer: C
Explanation:
final variable’s value cannot be changed.
11. Which following line is not correct?
class test{
final void myMethod(int num=10){ // line1
System.out.println(num); } // line2
}
class subtest extend test{
final void myMethod(int num=10){ // line3
System.out.println(num+1); // line4}
}
1. line12. line23. line34. line4
11. Answer: C
Explanation:
The method in sub class cannot override the final method in super class.
12. Which following line is not correct?
class test{ // line1
test(int x, int y ){ // line2 this.x=x;
this.y=y;
}
}
class subtest extends test{ // line3
final subtest(int m, int n){ // line4
int sum=m+n;
}}
1. line12. line23. line34. line4
12. Answer: D
Explanation:
Constructor method cannot be “final”.
13. Which following line is not correct?
abstract class car{
abstract void drive( ); // line1
}
class redCar extends car{ // line2
void driving( ){ // line3
System.out.println(“Driving red car.”) // line4
}}
1. line12. line23. line34. line4
13. Answer: C
Explanation:
The method name in sub class should be the same as the abstract method name in super class. Sodriving( ) should be changed to drive( ), so that the method in concrete class can implement theabstract method in abstract class.
14. Which following line is not correct?
abstract class car{
abstract void drive(){ }; // line1
}
class redCar extends car{ // line2
void drive(){ // line3
System.out.println(“Driving red car.”) // line4
}}
1. line12. line23. line34. line4
14. Answer: A
Explanation:
Abstract method should be an empty method. It should not have { }.
15. Which following statement is not correct?
1. abstract and final cannot be used at the same time to modify a class.2. abstract method can be placed inside or outside the abstract class.3. abstract class cannot contain private member.4. abstract and static cannot be used at the same time to modify a method.
15. Answer: B
Explanation:
Abstract method must be placed inside the abstract class.
16. Which following line is not correct?
interface test{
int num; // line1
int myMethod( ); // line2
}
class newTest implements test{
public int myMethod( ){ // line3
return 100; // line4}
}
1. line12. line23. line34. line4
16. Answer: A
Explanation:
Interface cannot include any declaration of variable or constructor method. However, Constant can bedefined inside the interface.
17. Which following line is not correct?interface test{
double PI=3.14159 // line1
int myMethod( ); // line2
}
class newTest implements test{
int myMethod( ){ // line3
return 100; // line4
}}
1. line12. line23. line34. line4
17. Answer: C
Explanation:
When a method implements the empty method in interface, this method should be declared as“public”. For instance: public int myMethod( ){…}.
18. Which following line is not correct?
class test{
private test( ){ } // line1
static test myMethod( ){return new test( ); } // line2
}
public class testPrivate{
public static void main (String args[ ])
test t=new test( ); // line3t.myMethod( ); // line4
}
1. line12. line23. line34. line4
18. Answer: C
Explanation:
constructor method cannot be defined as final.
test t=new test( ) cannot call the private constructor method private test( ){ …}.
19. Which following line is not correct?
public class test{
public int num=10; // line1
}
protected class newTest extends test{ // line2
public test t=new test( ); // line3
public void myMethod( ){ // line4 System.out.println(“OK1”);
}
}
1. line12. line23. line34. line4
19. Answer: B
Explanation:
“protected” or “private” cannot be a class modifier. Only “public” can be a class modifier.
20. Which following statement is not correct?
1. The protected member can be accessed by all members in the same class.2. The protected member can be accessed by all members in the same package.3. The protected member can be accessed by all members in the sub class.4. The protected member can be accessed by all members in the different package.
20. Answer: D
Explanation:
The protected member cannot be accessed by the members in non-sub class of the different package.
Chapter 4 Class, Object, Interface & Method
1. Which following line is not correct?
public class test{ static int num; // line1
num=10; // line2
public static void main (String args[ ]){ // line3
System.out.print(num); // line4
}
}
1. line12. line23. line34. line4
1. Answer: B
Explanation:
“num=10; “ should be placed in main( ) { }.
You can define a member variable and assign the value at the same time. The following codes arecorrect.
public class test{ static int num=10; // correct
}
You cannot modify the member variable in the class. The following codes are not correct.
public class test{
static int num;
num=10; // error
} If you move the “num=10;” inside the method, that will be correct.
2. What is the output in the following code?
public class test{
public static void main (String args[ ]){
String s=new String(“true”);
Boolean b=new Boolean(true);if(s.equals (b)){
System.out.print(“true”);
}
}
}
1. true2. false3. no output4. compile failure
2. Answer: C
Explanation:
The code if(s.equals (b)){ } is error. equals( ) only compares the same type object. “s” and “b are thedifferent type objects.
3. Which following declaration is not correct?
1. final class test2. public class test3. abstract class test4. private class test
3. Answer: D
Explanation:
“private” and “protected” cannot be a modifier of class.
However “public” can be a modifier of class.
4. Which following line is not correct?
class superClass {… }
class subClass extends superClass{… }
…
superClass a=new superClass( ); // line1
subClass b=new subclass( ); // line2
……a=b; // line3
b=a; // line4
1. line12. line23. line34. line4
4. Answer: D
Explanation:
The object of super class cannot assign the value to the object of sub class.
However, the object of sub class can assign the value to the object of super class.
5. Which following line is not correct?
interface A{ // line 1
double PI=3.14159; // line 2
void myMethod( ); // line 3
}
class B implements A{ } // line 4
1. line12. line23. line34. line4
5. Answer: D
Because class B has no any method to implement the empty method in the interface, the class B shouldbe declared as abstract class. The code should declare like this:
abstract class B implements A { }.
6. Which following line is not correct?
final class test{
void myMethod (){ // line1
int num=10; // line2
System.out.print(num); // line3
}
}
class subtest extends test{… } // line41. line12. line23. line34. line4
6. Answer: D
Explanation:
“class subtest extends test{… }” is error. A sub class cannot extend a final super class.
7. Which following statement is correct?
1. The name of the constructor method can be different from the name of class.2. Constructor method cannot have the return value, so it needs a void return type before its
name.3. To call a constructor method in super class, you can use “super” statement in sub class.4. Any class must define constructor method explicitly, so that it initializes all members in
class.
7. Answer: C
Explanation:
To call a constructor method in super class, you can use “super” statement in sub class.
“super” statement should be placed to the first line in the constructor method of sub class.
8. Which following statement is not correct?
1. The “super” statement must place in the first line in the sub class’s constructor method.2. The “super” statement can be used to the static method.3. Abstract method cannot have method body, and it must be placed inside the abstract class.4. Abstract class cannot use ”new” statement to create an object.
8. Answer: B
Explanation:
Static method cannot use “super” statement or “this” statement.
9. What is the output in the following code?
class superClass{
superClass( ){System.out.print(“A”);}
}
class subClass extends superClass{
subClass( ){System.out.print(“B”);}
}public static void main (String args[ ]){
superClass a=new superClass( );
subClass b=new subClass( );
}
1. A2. B3. AB4. AAB
9. Answer: D
Explanation:
According to Java’s rule, when creating sub-class object, it will call super-class constructor methodfirst, and then call sub-class constructor method.
10. Which line of code is not correct for overloading or overriding?
class superClass{
public int myMethod( ) {…}
}
public class subclass extends superClass{
/*The following codes will be inserted here for overloading or overriding. */
}
1. public int myMehtod( ){…}2. public double myMehtod(double d ){…}3. public void myMehtod( ){…}4. public float myMehtod(float f ){…}
10. Answer: C
Explanation:
public void myMehtod ( ){…} is error.
It cannot override the method in super class because their return type is different.
It cannot overload the method in super class because their argument feature is the same.
Chapter 5 Class, Object, Interface & Method
1. Which following code is correct?
1. abstract class test {abstract void myMethod();}2. class abstract test {abstract void myMethod();}3. abstract test {abstract void myMethod();}4. abstract class test {abstract void myMethod(){…};}
1. Answer: A
Explanation:
A is right, “abstract class test {abstract void myMethod();{ }” is correct.
B is wrong, because of a reverse order of “class abstract”.
C is wrong, because of a keyword “class” missing.D is wrong, because abstract method has method body { }.
2. Which following line is not correct?
class test{
int x=10; // line1
static int y=100; // line2
}public static void method1(static int c ){
x=c; // line3
}
public void method2( ){
y=200; // line4
}
1. line12. line23. line34. line4
2. Answer: C
Explanation:
A static variable in static method cannot modify a non-static variable.
“x=c” cannot modify a non-static variable “int x=100”.
But a non-static variable can modify a static variable.
3. Which following line is not correct?
public class test{ // line1
public int num=10; // line2
public static void main (String args[ ]){ // line3
System.out.print(“num=”+num); // line4
}}
1. line12. line23. line34. line4
3. Answer: D
Explanation:
“System.out.print(“num=”+num)” cannot directly output the value of the variable “num”.
You can create an object first, and use this object to call the variable “num”.
4. Given a code:
test obj=new test( );If you want to free the memory space of variable obj, which following code is suitable?
1. obj=” “; System.finalize( );2. obj=” ”; System.gc( );3. obj=null; System.finalize( );4. obj=null; System.gc( );
4. Answer: D
Explanation:
If you want to free the memory space of variable obj, please use the code like this:
obj=null; System.gc( );
5. If you want to restrict the access of member to current class from another class, which followingmodifier should you choose?
1. default2. private3. public4. protected
5. Answer: B
Explanation:
If you want to restrict the access of member to current class from another class, please use modifier“private” for a member.
6. Which following statement is not correct?
1. final variable cannot be modified.2. final method cannot be overridden.3. final object cannot be accessed.4. final class cannot be extended.
6. Answer: C
Explanation:
C is wrong.
A, B, D is correct.
final variable cannot be modified. final method cannot be overridden. final class cannot be extended
7. Which following line is not correct?
class A{
private int a=10;
protected int b=20;
int c=30;
void d ( ) {System.out.print(“ok”);
}
}
public class B{
public static void main (String args[ ]){
A obj=new A ( );
obj.a=100; // line1
obj.b=200; // line2obj.c=300; // line3
obj.d( ); // line4
}
}
1. line12. line23. line34. line4
7. Answer: A
Explanation:
obj.a=100; is error.
Variable “a” is defined as private variable, which cannot be accessed from another class.
8. What is the output in the following code?
public class test{
public test( ){
System.out.print(“A”);
}
public static void main (String args[ ]){
test t=new test( );t.test( );
System.out.print(“B”);
}
}
1. AB2. AAB3. AABB4. compile failure
8. Answer: D
Explanation:
t.test( ); is error. Object “t” cannot call the constructor method test( ).
9. What is the output in the following code?
class test{
int a=10;
String b=”str1”
test( ){
a=20;
b=”str2”;
}public static void main (String args[ ]){
test obj=new test( );
System.out.print(obj.a+obj.b);
}
}
1. 10str12. 10str23. 20str14. 20str2
9. Answer: D
Explanation:
When creating an object, initialization of a variable should use the variable in constructor method,instead of variables in class.
10. Which following line is not correct?
abstract class test{ // line1
abstract int myMethod( ); // line2
}
public class abstractTest extends test{ // line3
private int myMethod( ) {…} // line4
}
1. line12. line23. line34. line4
10. Answer: D
Explanation:
private int myMethod( ) {…} is error. private method cannot implement the abstract method.
You can use the method with public, protected or default modifier to implement the abstract method.
Chapter 6 String & StringBuffer
1. What is the output in the following code?
public class test{
public static void main (String args[ ]){Sting s1=new String(“ok”);
Sting s2=new String(“ok”);
if (s1==s2){
System.out.print(“equal”);
}
else{
System.out.print(“not equal”);
}}
}
1. no output2. equal3. not equal4. compile failure
1. Answer: C
Explanation:
“obj1==obj2” compares two objects to identify they are the same object.
“obj1.eqeal(obj2 )” compares two objects’ value to identify they have the same value.
For instance:Sting s1=new String(“ok”);
Sting s2=new String(“ok”);
if (s1.equals(s2)){ // using equals( )
System.out.print(“equal”);
}
The above code will output “equal”.
2. Which following line is not correct?
int a[ ]= {0,1,2,3}; // line1
System.out.print(a.length); // line2String.str=”Java”; // line3
System.out.print(str.length); // line4
1. line12. line23. line34. line4
2. Answer: D
Explanation:
String.length( ) gets the result of a string size.
Arrary.length gets the result of an array size.
3. Which following statement is correct?
public String substring (int m, int n)
1. return substring from m to n.2. return substring from m-1 to n-1.3. return substring from m-1 to n.4. return substring from m to n-1.
3. Answer: D
Explanation:
public String substring (int m, int n) will return substring from m to n-1.
4. Which following statement is not correct when comparing String object?
1. compareTo( ) is used to compare two objects’ value by dictionary order. Returning zeromeans equal.
2. compareObjects( ) is used to compare two String objects by its value.3. equals( ) is used to compare two String objects by its value.4. == is used to compare two String objects to identify if they are the same object.
4. Answer: B
Explanation:
Java has no compareObjects( ).
5. 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.
5. Answer: A
Explanation:
operator”+” cannot connect two StringBuffer objects.
6. 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);
6. Answer: C
Explanation:
String arr [ ] = {“ “, “ “, “ “} can create three empty.
“null” is not an empty string.
7. Which following statement is not correct?
1. String class is a final class. It cannot have sub class.2. String class is included in the package java.lang.3. “ok”.equals(“ok”) will return true.4. String a="ok", b="ok"; a.compareTo(b) will return true.
7. Answer: D
Explanation:
String a="ok", b="ok"; a.compareTo(b) will return zero.
str1.compareTo(str2) compares two string objects lexicographically.
Returning the value 0 if the str1 lexicographically equal to str2;Returning a value less than 0 if the str1 lexicographically less than str2;
Returning a value greater than 0 if the str1 lexicographically greater than str2;
8. What is the output in the following code?
public static void main (String args[ ]){
String str1=”AB”;
String str2=”CD”;str2.toLowerCase( );
str1.concat.(str2);
System.out.print(str1+str2);
}
1. ABcd2. ABCD3. abcd4. compile failure
8. Answer: B
Explanation:
str2.toLowerCase( ) cannot make str2 lowercased.
Just imagine:
String str3= str2.toLowerCase( ); then str3 will be lowercased, but str2 will be still unchanged.
9. Which following line is not correct?
StringBuffer str1; str3; // line1
String str2 =new StringBuffer( ); // line2
str3=str1.concat(str2); // line3
System.out.println(str3); // line4
1. line12. line23. line34. line4
9. Answer: C
Explanation:
str3=str1.concat(str2) is wrong.
concat( ) is used to String object instead of StringBuffer object.
append( ) can be used to StringBuffer object.
10. Which following line is not correct?
StringBuffer str1; str2; // line1
str1=”OK”; // line2
str2=new StringBuffer(“OK”); // line3
System.out.println(str2); // line4
1. line12. line23. line34. line4
10. Answer: B
Explanation:
str1=”OK” is wrong.
StringBuffer object cannot be assigned a value directly, which is different from String object.
If you want to assign a value to StringBuffer object, you can use the code like this:str1=new StringBuffer(“OK”);
Chapter 7 Exception
1. Which following line is no good practice in programming?
int a=100; b=0; // line1
c=a/b; // line2try{ // line3
a=200/b; // line4
}catch(arithmeticException e){
System.out.println(“Divided by zero.”);
}
1. line12. line23. line34. line4
1. Answer: B
Explanation:
c=a/b; will occur exception, which should be placed inside the try{ } block.
2. Which following line is not correct?
try{
int a, b, c; // line1
c=a/b; // line2
}
catch(RuntimeException e) // line3
{
System.out.println(“Divided by zero.”); // line4}
catch(ArithmeticException e)
{
System.out.println(“Divided by zero”);
}
1. line12. line23. line34. line4
2. Answer: C
Explanation:
catch(RuntimeException e) is wrong.
Sub class exception should be used first, and then super class exception can be used later.
ArithmeticException is a sub class of RuntimeException, so ArithmeticException should be usedbefore the RuntimeException. There are some sub class exceptions under Exception:
ArithmeticExceptionIndexOutOfBoundsExceptionInterruptedException
RuntimeException
Exception IOException FileNotFoundExceptionEOFException
AWTException
3. The common super class of Error and Exception is___?
1. Throwable2. AWTError3. AWTException4. ErrorException
3. Answer: A
Explanation:
The common super class of Error and Exception is Throwable.
LinkageError
VirtualmachineErrorAWTError
Error
Throwable
ArithmeticException
IndexOutOfBoundsExceptionInterruptedException
Exception
4. Which following statement is correct?
1. Error is an Exception.2. IOException is a sub class of EOFException.3. Any codes that maybe throw an error should be placed inside the try{ } block.4. Any codes that maybe throw an exception should be placed inside the try{ } block.
4. Answer: D
Explanation:
Any codes that maybe throw an exception should be placed inside the try{ } block.
A is wrong. Error is different from Exception.
B is wrong. EOFException is a sub class of IOException.C is wrong. Error cannot throw an exception.
5. Which following operation may not throw exception?
1. Want to open a file that does not exist.2. A float or integer divided by zero.3. When the index of an array is out of bounds4. Return -1 when use indexOf( ) to search a substring.
5. Answer: D
Explanation:
The indexOf( ) method returns the position of the first occurrence of a specified value in a string.
indexOf( ) returns -1 if the value to search for never occurs, but it never throw an exception.
6. Which following line will throw exception?
try{
int a=10, b=20, c=0;
if((a==b)&&(a=b/c)) // line 1
System.out.print(“A”); // line 2
else if ((a==b)&(a=b/c)) // line 3
System.out.print(“B”); // line 4}
1. line12. line23. line34. line4
6. Answer: C
Explanation:
else if ((a==b)&(a=b/c)) will throw an exception.
if((a==b)&&(a=b/c)) cannot throw an exception. Because && has a short-circuit function.
About short-circuit function:In (expression1)&&(expression2), if the expression 1 return false, than expression2 will be ignored.
In (expression1)||(expression2), if the expression 1 return true, than expression2 will be ignored.
7. Which following code is not correct?
1. public void myMethod( ) throws Exception2. public void myMethod( ) throw Exception1. public void myMethod( ) throws RuntimeException2. public void myMethod( ) throws ArithmeticException
7. Answer: B
Explanation:
(1) If you want to throw an exception inside a method, you should use “throws” statement whendeclaring a method.
For example:
public void myMethod( ) throws exception{…}(2) If you want to throw an exception manually, you can use “throw e;” somewhere necessary.
For example:
Exception e= new ExceptionType( );
throw e;
8. What exception should be thrown so as to pass compile?
public testException extends Exception{ }public void myMethod( ) throws testException{ }
public void myTest( ) throws _______?
{
myMethod( );
}
1. Exception2. RuntimeException3. AWTException4. IOException
8. Answer: A
Explanation:
Because myMethod( ) throws testException, and testException is a sub class of Exception. So whendeclaring myTest( ), it should declare to throw its super class Exception. Only super class exceptioncan include sub class exception.
B, C, D is wrong. RuntimeException, AWTException and IOException are sub class of Exception.They cannot include testException.
9. What is the output in the following code?
public static void main (String args[ ]){
try
{
System.out.print(“A”);
return;
}catch(RuntimeException e)
{
System.out.print(“B”);
}
finally
{
System.out.print(“Finally”);
}}
1. A2. B3. AB4. AFinally
9. Answer: D
Explanation:
When try{ } block has a “return” statement, “finally” statement should be executed first.
The statements after the “finally” block will not execute.
10. Which following object can use “throws” when exception occurred?
1. Event2. Object3. String4. EOFException
10. Answer: D
Explanation:
Event, Object and String do not belong to Exception class. They are not throwable exceptions.
Chapter 8 Input & Output
1. java.io Package does not include_______. 1. InputStream Class2. OutputStream Class3. File Class4. FileDescription Class
1. Answer: D
Explanation:
java.io package includes InputStream class, OutputStream class, File class, RandomAccessFile classand FileDescriptor class.
2. File class is not used to _________.
1. check if file exist.2. read file or write
file. 3. check if file is readable or is writable.4. return the length of a file.
2. Answer: B
Explanation:
File class can check if file exists, check if file is readable or is writable, return the length of a file,get the file name, rename the file, delete the file, set the file read only and create a new directory orremove a directory……etc.
File class cannot access the contents of a file, cannot read or write a file.
3. Which following statement is not correct?
1. FileInputStream Class is the sub class of InputStream Class.2. FileOutputStream Class is the sub class of OutputStream Class.3. FileInputStream and FileOutputStream can write or read byte data from a file.4. FileInputStream and FileOutputStream can write or read byte, character, integer, and one
line of data from a data stream.
3. Answer: D
Explanation:
FileInputStream and FileOutputStream cannot write or read character, integer and one line of datafrom a data stream.
4. Which following statement is not correct?
1. DataInputStream Class is the sub class of InputStream Class.2. DataOutputStream Class is the sub class of OutputStream Class.3. DataInputStream and DataOutputStream only can write or read byte data from a file, but
cannot write or read various types of data.4. DataInpuutStream and DataOutputStream can write or read byte, character, integer and one
line of data from a data stream.
4. Answer: C
Explanation:
DataInputStream and DataOutputStream not only can write or read byte data from a file, but also canwrite or read various types of data.
5. What is the output in the following code?
FileInputStream in=new FileInputStream(“myfile.java”);
byte b[ ]=new byte[10];
int d=in.read(b);
System.out.print(d);
5. 106. 207. not sure.8. compile failure.
5. Answer: C
Explanation:
byte[10] means the length of array is 10, does not mean the value of array is 10.
in.read(b) means to read the value of array, but value of “b” is not sure.
6. If the size of a file myFile.txt is 100 bytes, then after running
OutputStream f=new FileOutputStream(new File(“myFile.txt”));
The size of myFile.txt is_______ bytes.
1. 1002. 03. not sure4. Compile failure.
6. Answer: B
Explanation:
Although File class created an object, but it did not use length( ) to get the size of the myFile.txt.Therefore, the file size is zero.
7. When using read( ) in java.io.InputStream or write( ) in java.io.OutStream, you may handle anexception which is ______.
1. java.io.InputException2. java.io.OutputException3. java.io.InputOutputException4. java.io.IOException
7. Answer: D
Explanation:
java.io.IOException may be thrown by read( ) in InputStream or write( ) in OutputStream.
8. Which following statement is not correct?
1. There are two kinds of main streams: one is input stream, another is output stream.2. InputStream and OutputStream is a super class stream of all other class stream.3. In order to support input/output device, Java defines two stream objects. One is System.in
object. Another is System.out object.4. PushbackInputStream class has the function of rejecting data stream.
8. Answer: D
Explanation:
“PushbackInputStream class has the function of rejecting data stream.” is wrong.
PushbackInputStream class can return the read data back to stream.
9. Which following stream can output character?
1. java.io.OutputStreamWriter2. java.io.OutputStream3. java.io.BufferedOutputStream4. java.io.FileOutStream
9. Answer: A
Explanation:
OutputStreamWriter can output character.
B is wrong. OutputStream works for byte stream instead of character stream.
C is wrong. BufferedOutputStream works for byte stream instead of character stream.D is wrong. There is no FileOutStream in Java.
10. Which following stream can input character?
1. java.io.InputStreamReader2. java.io.InputStream3. java.io.BufferedInputStream4. java.io.FileInStream
10. Answer: A
Explanation:
InputStreamReader can input character.
B is wrong. InputStream works for byte stream instead of character stream.
C is wrong. BufferedInputStream works for byte stream instead of character stream.D is wrong. There is no FileInStream in Java.
11. What is the output in the following code?
String str1=”You”;
String str2=“like my book”;
String str3=new String(”You like my book”);
String str4=str1.concat(str2);If (str3.equals(str4))
{System.out.print(“Write a positive review for this book!”);}
else if(str3==str4)
{System.out.print(“Write a not-positive review for this book”);}
else
{System.out.print(“The End”);}
1. Write a positive review for this book!2. Write a not-positive review for this book!3. Compile Failure!4. The End!
11. Answer: A
Explanation:
A is correct answer!
equals( ) compares two string values, if two values are the same, it will return true.
Therefore, “Write a positive review for this book!” is right!
== compares two string objects, if two string objects are the same, it will return true. In here, str3 andstr4 are different string objects, so it return false.
Therefore, “Write a non-positive review for this book” is wrong.
“Write a positive review for this book!” is correct. Thank you!
How time flies! It is time to say good-bye.
Ray Yao's books:
Linux Command Line (eBook)
Linux Command Line (Paper Book)
JAVA 100 Tests, Answers & ExplanationsPHP 100 Tests, Answers & Explanations
JavaScript 100 Tests, Answers & Explanations
JAVA in 8 Hours
PHP in 8 Hours
JavaScript in 8 Hours
C++ in 8 Hours
AngularJS in 8 Hours
JQuery in 8 Hours
Conclusion
Dear My Friend,
If you are not satisfied with this eBook, could you please return the eBook for a refund within sevendays of the date of purchase?
If you found any errors in this book, could you please send an email to me?
I will appreciate for your email. Thank you very much!
Ray Yao
My friend, See you!