Core Java
Core Java
Core Java
1.Which is a valid method signature in an interface? d)Yes-the child classes inherit both.
a)private int getArea(); 10.Which one of the following statements is true ?
b)protected float getVol(float x); a) An abstract class can be instantiated.
c) public static void main(String [] args); b)An abstract class is implicitly final.
d)boolean setFlag(Boolean [] test []); c)An abstract class can declare non-abstract methods.
d)An abstract class can not extend a concrete class.
2.Which statement is true about interfaces?
a)Interfaces allow multiple implementation inheritance. 11.What is an abstract method?
b)Interfaces can extend any number of other interfaces. a)An abstract method is any method in an abstract class.
c) Members of an interface are never static. b)An abstract method is a method which cannot be inherited.
d)Members of an interface can always be declared static. c)An abstract method is one without a body that is declared
with the reserved word abstract.D)An abstract method is a
3.Which statement is true about interfaces? method in the child class that overrides a parent method.
a)The keyword extends is used to specify that an interface
inherits from another interface. 12.What is an abstract class?
b) The keyword extends is used to specify that a class a)An abstract class is one without any child classes.
inherits from an interface. b)An abstract class is any parent class with more than one
c) The keyword implements is used to specify that an child class.
interface inherits from another interface. c)An abstract class is a class which cannot be instantiated.
d)The keyword implements is used to specify that a class d)An abstract class is another name for "base class."
inherits from another class.
13.Which declaration in the below code represents a valid
4.Which of the field declaration is legal within the body of declaration within the interface ?
an interface? 1. public interface TestInterface {
a) protected static int answer = 42; 2. volatile long value=98L;
b)volatile static int answer = 42; 3. transient long amount=67L;
c)int answer = 42; 4. Long calculate(long input);
d)private final static int answer = 42; 5. static Integer getValue();
6. }
5.Which declaration prevents creating a subclass of a top a)Declaration at line 2.
level class? b)Declaration at line 3.
a) private class Javacg{} c)Declaration at line 4.
b)abstract public class Javacg{} d)Declaration at line 5.
c)final public class Javacg{}
d)final abstract class Javacg{} 14.Given:
1. public interface Constants {
6.Here is an abstract method defined in the parent: 2. static final int SEASON_SUMMER=1;
public abstract int sumUp ( int[] arr ); 3. final int SEASON_SPRING=2;
Which of the following is required in a non-abstract child? 4. static int SEASON_AUTUMN=3;
a)public abstract int sumUp ( int[] arr ) { . . . } 5. public static const int SEASON_WINTER=4;
b)public int sumUp ( int[] arr ) { . . . } 6. }
c)public double sumUp ( int[] arr ) { . . . } What is the expected behaviour on compiling the above code?
d)public int sumUp ( long[] arr ) { . . . } a)Compilation error occurs at line 2.
b)Compilation error occurs at line 3.
7.Which statement is true for any concrete class c)Compilation error occurs at line 4.
implementing the java.lang.Runnable interface? d)Compilation error occurs at line 5.
a)The class must contain an empty protected void method
named run(). 15.Given the following,
b)The class must contain a public void method named 1. abstract class A {
runnable(). 2. abstract short m1() ;
c)The class definition must include the words implements 3. short m2() { return (short) 420; }
Threads and contain a method called run(). 4. }
d)The mandatory method must be public, with a return type 5.
of void, must be called run(), and cannot take any arguments. 6. abstract class B extends A {
7. // missing code ?
8.Which is a valid declaration within an interface? 8. short m1() { return (short) 42; }
a)protected short stop = 23; 9. }
b)final void madness(short stop); Which of the following statements is true?
c)public Boolean madness(long bow); a) Class B must either make an abstract declaration of
d)static char madness(double duty); method m2() or implement method m2() to allow the code to
compile.
9.Can an abstract class define both abstract methods and b) It is legal, but not required, for class B to either make an
non-abstract methods ? abstract declaration of method m2() or implement method
a)No-it must have all one or the other. m2() for the code to compile.
b) No-it must have all abstract methods. c) As long as line 8 exists, class A must declare method m1()
c)Yes-but the child classes do not inherit the abstract in some way.
1
d) If class A was not abstract and method m1() on line 2 was 12. public static void main(String... args) {
implemented, the code would not compile. 13. EC ec = new EC();
14. ec.setup();
16.Given the following, 15. ec.execute();
1. interface Base { 16. }
2. boolean m1 (); 17.}
3. byte m2(short s); What is the expected behaviour?
4. } a)Compilation error at line 2.
Which of the following code fragment will compile? b)Compilation error at line 14.
a)interface Base2 implements Base {} c)Runtime error occurs.
b) abstract class Class2 extends Base { d)Prints "execute of EC invoked".
public boolean m1() { return true; } }
c) abstract class Class2 implements Base { 20.Given the code below:
public boolean m1() { return (7 > 4); } } interface MyInterface {
d) class Class2 implements Base { void doSomething ( ) ;
boolean m1() { return false; } }
byte m2(short s) { return 42; } } class MyClass implements MyInterface {
// xx
17.Given: }
1. interface I1 {
2. int process(); Choose the valid option that can be substituted in place of xx
3. } in the MyClass class .
4. class C implements I1 { a)public native void doSomething ( ) ;
5. int process() { b) void doSomething ( ) { /* valid code fragments */ }
6. System.out.println("process of C invoked"); c)private void doSomething ( ) { /* valid code fragments */ }
7. return 1; d)protected void doSomething ( ) { /* valid code fragments */
8. } }
9. void display() {
10. System.out.println("display of C invoked"); 21.interface I1 {
11. } void draw();
12.} }
13.public class TestC { class C implements I1 {
14. public static void main(String... args) { xxxxxx
15. C c = new C(); }
16. c.process(); Which of the following when inserted at xxxxxx is a legal
17. } definition and implementation ?
18.} a)void draw() { }
What is the expected behaviour? b)public void draw() { }
a)Compilation error at line 5. c)protected void draw() { }
b)Compilation error at line 9. d)abstract void draw() { }
c) Runtime error occurs.
d)Prints "process of C invoked". 22.Given the following,
1. interface Count {
18.Given: 2. short counter = 0;
1. public interface Alpha { 3. void countUp();
2. String MESSAGE = "Welcome"; 4. }
3. public void display(); 5. public class TestCount implements Count {
4. } 6.
To create an interface called Beta that has Alpha as its 7. public static void main(String [] args) {
parent, which interface declaration is correct? 8. TestCount t = new TestCount();
a)public interface Beta extends Alpha { } 9. t.countUp();
b)public interface Beta implements Alpha {} 10. }
c)public interface Beta instanceOf Alpha {} 11. public void countUp() {
d)public interface Beta parent Alpha { } 12. for (int x = 6; x>counter; x--, ++counter) {
13. System.out.print(" " + counter);
19.Given: 14. }
1. abstract class AbstractClass { 15. }
2. void setup() { } 16. }
3. abstract int execute(); What is the result?
4. } a)1 2 3
5. class EC extends AbstractClass { b)0 1 2 3
6. int execute() { c)1 2 3 4
7. System.out.println("execute of EC invoked"); d)Compilation fails
8. return 0;
9. } 23.Given the following,
10.} 1. interface DoMath {
11.public class TestEC { 2. double getArea(int rad); }
2
3. 17.}
4. interface MathPlus { What is the expected behaviour?
5. double getVol(int b, int h); } a) Prints "Invoking calculate...".
6.
3
34.Which statement is true? 43.Which of the following modifiers cannot be applied to
a) Constructors can be declared abstract. the declaration of a field?
b) A subclass of a class with an abstract method must a) final
provide an implementation for the abstract method. b) transient
c) Transient fields will be saved during serialization. c) volatile
d) Instance methods of a class can access its static members d) synchronized
implicitly.
44.How restrictive is the default accessibility compared to
35.Which statement is true? public, protected, and private accessibility?
a) Less restrictive than public.
a) A static method can call other non-static methods in the b) More restrictive than public, but less restrictive than
same class by using the this keyword. protected.
b) A class may contain both static and non-static variables c)More restrictive than protected, but less restrictive than
and both static and non-static methods. private.
c) Each object of a class has its own instance of each static d)More restrictive than private.
variable. 45.What is printed out following the execution of the code
d) Instance methods may access local variables of static below ?
methods. 1. class Test {
2. static String s;
36.Which of the following modifiers cannot be applied to a 3. public static void main(String []args) {
top level class? 4. int x = 4;
a) public 5. if (x < 4)
b) private 6. System.out.println("Val = " + x);
c) abstract 7. else
d) final 8. System.out.println(s);
9. }
37.Which of the following modifiers cannot be applied to a 10. }
method? a) Nothing. The code fails to compile because the String s
a) final isn’t declared correctly.
b) synchronized b) The text "Val = null" is displayed.
c) transient c) The text "null" is displayed.
d) native d) Runtime error due to NullPointer exception.
38.Which of the following modifiers can be applied to a 46.Analyse the following 2 classes and select the correct
constructor? statement.
a)private class A {
b) abstract final volatile private int x = 0;
static int y = 1;
39.Which statement is true about modifiers? protected int q = 2;
a) Fields can be declared native. }
b) Non-abstract methods can be declared in abstract classes. class B extends A {
c) Classes can be declared native. void method() {
d) Abstract classes can be declared final. System.out.println(x);
System.out.println(y);
40.Before which of the following can the keyword System.out.println(q);
"synchronized" be placed, without causing a compile error. }
a) class variables }
b) instance methods a) The code fails to compile because the variable x is not
c) instance variables available to class B.
d) a class b) The code compiles correctly, and the following is
displayed:012
41.A protected method can be overridden by c) The code fails to compile because you can’t subclass a
a) A private method class with protected variables.
b) A method without any access specifiers (i.e. default) d) The code fails to compile because you can’t subclass a
c) A protected method class with static variables.
d) All of the above
47.Given the following class, which of these is valid way of
42.Which statement is true about accessibility of members? referring to the class from outside of the package com.test?
a) Private members are always accessible from within the package com.test;
same package. public class MyClass {
b)Private members can only be accessed by code from within // ...
the class of the member. }
c) A member with default accessibility can be accessed by a) By simply referring to the class as MyClass.
any subclass of the class in which it is defined. b) By simply referring to the class as test.MyClass.
d) Package/default accessibility for a member can be c) By simply referring to the class as com.test.MyClass.
declared using the keyword default. d) By importing with com.* and referring to the class as
test.MyClass.
4
6. }
48.Given the following member declarations, which 7. void callStuff() {
statement is true? 8. System.out.print("this " + this.doStuff() );
int a; // (1) 9. ParentUtil p = new ParentUtil();
static int a; // (2) 10. System.out.print(" parent " + p.doStuff() );
int f() { return a; } // (3) 11. }
static int f() { return a; } // (4) 12. }
Declarations (1) and (3) cannot occur in the same class Which statement is true?
definition. a) The code compiles and runs, with output this 420 parent
Declarations (2) and (4) cannot occur in the same class 420.
definition. b) If line 8 is removed, the code will compile and run.
Declarations (1) and (4) cannot occur in the same class c) If line 10 is removed, the code will compile and run.
definition. d) Both lines 8 and 10 must be removed for the code to
compile.
Declarations (2) and (3) cannot occur in the same class
definition. 52.What would be the result of attempting to compile and
run the following program?
49.// Class A is declared in a file named A.java. class MyClass {
package com.test.work; static MyClass ref;
public class A { String[] arguments;
public void m1() {System.out.print("A.m1, ");} public static void main(String[] args) {
void m2() {System.out.print("A.m2, ");} ref = new MyClass();
} ref.func(args);
// Class D is declared in a file named D.java. }
package com.test.work.other; public void func(String[] args) {
import com.test.work.A; ref.arguments = args;
public class D { }
public static void main(String[] args) { }
A a = new A(); a) The program will fail to compile, since the static method
a.m1(); // 1 main() cannot have a call to the non-static method func().
a.m2(); // 2 b) The program will fail to compile, since the non-static
}} method func() cannot access the static variable ref.
What is the result of attempting to compile and run the c) The program will fail to compile, since the argument args
program? passed to the static method main() cannot be passed on to
a) Prints: A.m1, A.m2, the non-static method func().
b) Runtime error occurs. d) The program will compile and run successfully.
c) Compile-time error at 1.
d) Compile-time error at 2. 53.package com.test.work;
public class A {
50.public class MyClass { public void m1() {System.out.print("A.m1, ");}
int calculate(int i, int j) protected void m2() {System.out.print("A.m2, ");}
{ private void m3() {System.out.print("A.m3, ");}
return 2+i*j; void m4() {System.out.print("A.m4, ");}
} }
public static void main(String [] args) { class B {
public static void main(String[] args) {
int k = MyClass.calculate(5,10); A a = new A();
System.out.println(k); a.m1(); // 1
} a.m2(); // 2
} a.m3(); // 3
What is the result? a.m4(); // 4
a) 70 }}
b) 52 Assume that the code appears in a single file named A.java.
c) Compilation error What is the result of attempting to compile and run the
d) An exception is thrown at runtime program?
5
protected static int i; }
private int j; }
} What will be the result of compiling the above code ?
final class MyOtherClass extends MyClass { a) The code fails to compile, because you can’t override a
// MyOtherClass(int n) { m = n; } // (2) method to be more private than its parent.
public static void main(String[] args) { b) The code fails to compile, because @Override cannot be
MyClass mc = new MyOtherClass(); mentioned above a default method.
} c) The code fails to compile, because public methods cannot
void f() {} be overriden.
void h() {} d) The code compiles correctly without any errors.
// void k() { i++; } // (3)
// void l() { j++; } // (4) Topic: Arrays
int m;
} 58.What is the value of seasons.length for the following
array?
a) final void h() {} // (1) String[] seasons = {"winter", "spring", "summer", "fall", };
b) MyOtherClass(int n) { m = n; } // (2) undefined
c) void k() { i++; } // (3) a) 4
d) void l() { j++; } // (4) b) 5
c) 22
55.Given the following code, which statement can be placed
at the indicated position without causing compilation errors? 59.Which of the following will declare an array and initialize
public class ThisUsage { it ?
int planets; a) Array a = new Array(5);
static int suns; b) int array[] = new int [5];
public void gaze() { c) int a[] = new int(5);
int i; d)int [5] array;
// ... insert statements here ...
} 60.Which of the following is an illegal declaration of array ?
} a) int [] myscore[];
a) this = new ThisUsage(); b) char [] mychars;
b) this.i = 4; c) Dog mydogs[7];
c) this.planets = i; d) Dog mydogs[];
d) i = this.planets;
61.Which will legally declare, construct, and initialize an
56.Given the following: array?
class Gamma { a) int [] myList = {"5", "8", "2"};
public int display() { b) int [3] myList = (5, 8, 2);
return 3; c) int myList[] [] = {5,8,2,0};
} d) int [] myList = {5, 8, 2};
}
public class Delta extends Gamma { 62.Which of these array declaration statements is not legal?
@Override a) int[] i[] = { { 1, 2 }, { 1 }, {}, { 1, 2, 3 } };
protected int display() { b) int i[][] = new int[][] { {1, 2, 3}, {4, 5, 6} };
return 4; c) int i[4] = { 1, 2, 3, 4 };
} d) int i[][] = { { 1, 2 }, new int[ 2 ] };
}
What will be the result of compiling the above code ? 63.Which of the following is a legal declaration of a two-
a) The code compiles correctly without any errors. dimensional array of integers?
b) The code fails to compile, because you can’t override a a) int[5][5]a = new int[][];
method to be more private than its parent. b) int a = new int[5,5];
c) The code fails to compile, because @Override cannot be c) int[]a[] = new int[5][];
mentioned above a protected method. d) int[][]a = new int[][5];
d) The code fails to compile, because public methods cannot
be overriden. 64.How would you declare and initialize the array to declare
an array of fruits ?
57.Given the following: a) String[] arrayOfFruits = {"apple", "mango", "orange"};
class TestAccess { b) String[] arrayOfFruits= ("apple", "mango", "orange");
public int calculate() { c) String[] arrayOfFruits= ["apple", "mango", "orange"];
int a=5,b=6; d) String[] arrayOfFruits = new String{"apple, mango,
return a+b; orange"};
}
} 65.What type parameter must the following method be
public class MyChild extends TestAccess { called with?
@Override int myMethod ( double[] ar )
int calculate() { {
return 100; ....
6
} 74.Given the following code snippet:
a) An empty double array. double sum = 10.0, price=100;
b) A reference to an array that contains elements of type sum += price>=100 ? price*1.1 : price;
double. What value is placed in sum? Choose the most appropriate
c) A reference to an array that contains zero or more answer.
elements of type int. a) 90
d) An array of any length that contains double and must be b) 100
named ar c) 110
. d) 120
66.After the declaration:
char[] c = new char[100]; 75.If x, y, and z are all integers, which expression will
What is the value of c[50]? produce a runtime error?
a) 49 NOTE: The expressions are always evaluated with all the
b) 50 integers having a value of 1.
c) ‘\u0020’ a) z = x/y--;
d) ‘\u0000’ b) z = -x/x;
c) z = y/x--;
67.Which will legally declare, construct, and initialize an d) z = y%--x
array?
a) int [] myList = {"9", "6", "3"}; 76.Given a variable x of type int ( which contains a positive
b) int [3] myList = (9, 6, 3); value), which is the correct way of doubling the value of x,
c) int myList[] [] = {9,6,3,0}; barring any wrapping of out-of-range intermediate values ?
d) int [] myList = {9, 6, 3};
68.Given the following code snippet: a) x << 1;
float average[] = new float[6]; b) x >> 1;
Assuming the above declaration is a local variable in a c) x >>> 1;
method of a class, after the above statement is executed, d) x << -1;
which of the following statement is false ?
a) average.length is 6 77.Suppose you have four int variables: x, y, z, and result.
b) average[0] is 0.0 Which expression sets the value of z to x if result has a value
c) average[5] is undefined of 1, and the value of y to x otherwise?
d) average[6] is undefined a) x = (result == 1) ? z : y;
b) x = (result == 1) ? y : z;
Topic: Assignments, Expressions, Operators c) x = (result == 1) : y ? z;
d) x = (result == 1) : z ? y;
69.Which one of the below expression is equivalent to 16>>2
? 78.Given a variable x of type int ( which can contain a
a) 16/4 negative value), which of these expressions always gives a
b) 16/2 positive number irrespective of the value of x?
c) 16*2 a) x << 1;
d) 16/2^2 b) x >> 1;
c) x >>> 1;
70.Which of the following is correct? d) x << 2;
a) 8 >> 2 gives 2
b) 16 >>> 2 gives 2 79.Given:
c) 4 << 2 gives 2 int x = 7;
d) 2 << 1 gives 2 x <<= 2;
What best describes the second line of code?
71.Which of the following is correct? a) It assigns the value of 2 to x, and shifts it to left by one
128>>> 1 gives place.
a) 32 b) It assigns the value to x after shifting x to 2 places left.
b)64 c) It assigns the value to x after shifting 2 to x places left.
c) -64 d) It is invalid because there is no such operator as <<=.
d) -32
80.Given the variables defined below:
72.What is the value of -32 % 6 ? int one = 1;
a) 5 int two = 2;
b) -5 char initial = ‘2’;
c) 2 boolean flag = true;
d) -2 Which one of the following is invalid?
a) if( one == two ){}
73.Which one of the following is a short-circuit operator ? b) switch( one ){}
a)| c) switch( flag ){}
b) && d) switch( initial ){}
c) &
d) ^ 81.Identify the shift operator that returns -1 as the value of
the variable in the following statement:
7
int a= -4 MISSING OPERATOR 2; 7. }
a) >>> 8. }
b) >> What is the output ?
c) <<< a) 8.0
d) << b) Compilation error at Line 3
c) Compilation error at Line 4
82.public class TestOperator { d) Compilation error at Line 5
public static void main(String[] args) {
byte x = 0x0F; 86.public class Test {
byte y = 0x08; public static void main(String[] args)
byte z = x & y;logical operations returns int {
System.out.println(z); System.out.println( 6 ^ 4);
} }
} }What is the output?
What is the result? a) 1296
a) 8 b) 24
b) 15 c) 2
c) 23 d) Compilation error
d) Compilation error
87.What will happen if you try to compile and run the
83.public class TestExpression { following code?
private static int value=0; int a = 200;
private static boolean method2(int k) { byte b = a;
value+=k; System.out.println ("The value of b is " + b );
return true; a) It will compile and print The value of b is 200
} b) It will compile but cause an error at runtime
public static void method1(int index) { c) Compile-time error
boolean b; d) It will compile and print The value of b is -56
b = index >= 15 && method2(30);
b = index >= 15 & method2(15); 88..Given:
} public class TestOperator {
public static void main ( String args[]) { int x=15;
method1(0); public void method(int x) {
System.out.println(value); x+=x;
} System.out.println(x);
} }
What is the output? public static void main(String... args) {
a) 0 TestOperator t = new TestOperator();
b) 15 t.method(10);
c) 30 }
d) 45 }
What is the output of the above code?
84.public class TestCondition { a) 10
public static void main (String... args) { b)20
int i=1; c) 25
int j=2; d) 30
int k=2;
if ((i ^ j) && (j ^ k)) { 89.1. public class TestLiterals {
System.out.println("true"); 2. public static void main(String[] args) {
} 3. float f1 = 2.0;
else { 4. float f2 = 4.0f;
System.out.println("false"); 5. float result = f1 * f2;
} 6. System.out.println(result);
} 7. }
} 8. }
What is the expected output ? What is the output?
a) Prints true a) A value which is exactly 8.0
b) Prints false b)Compilation error at Line 3
c)Compilation error occurs c)Compilation error at Line 4
d) Runtime error occurs d) Compilation error at Line 5
8
} What is the result?
What is the output? a) 0
a) true b) 24
b) false c) 36
c) Compile-time error d) Compilation error
d) Run-time error
95.public class TestOperation {
91.public class TestOperator { public static void main (String... args) {
public static void main (String[] args) { int a = 4;
int x = 2, y = 4; int b = 3;
System.out.printf("%d,%d", (x ^ y), (y ^ x)); a += (--b + a * 3);
} System.out.printf("a=%d,b=%d",a,b);
} }
What is the expected output ? }
a) 8,8 What is the value of a after this code is run?
b) 6,8 a) a=19,b=3
c) 6,6 b) a=18,b=2
d) 8,6 c) a=19,b=1
d) a=18,b=3
92.public class Test {
private static int value =0; 96.public class TestIncrement {
private static boolean method2(int k) { public static void main(String[] args)
value+=k; {
return true; int index=10;
}
public static void method1(int index) { int result=0;
boolean b; if (index++ > 10)
b = index < 10 | method2(10); {
b = index < 10 || method2(20); result = index;
} }
public static void main ( String args[]) { System.out.println("index=" + index);
method1(0); System.out.println("result=" + result);
System.out.println(value); }
} What is the output?
} a) index=10
What is the output? result=0
a) 0 b) index=11
b)10 result=0
c) 20 c) index=10
d) 30 result=10
d) index=11
93.Given: result=11
1. public class B {
2. Integer x;not initialized 97.below:
3. int sum; if( val > 4 )
4. public B(int y) { { System.out.println( "Test A" );
5. sum=x+y; }
6. System.out.println(sum); else if( val > 9 )
7. } { System.out.println( "Test B" );
8. public static void main(String[] args) { }
9. new B(new Integer(23)); else System.out.println( "Test C" );
10. } Which values of val will result in "Test C" NOT being printed?
11. } a) val < 0
What is the expected output ? b) val = 0
a) The value "23" is printed at the command line. c) 0 < val < 4
b) Compilation fails because of an error in line 9. d) 4 < val < 9
c) A NullPointerException occurs at runtime.
d) A NumberFormatException occurs at runtime. 98.public class TestIncrement {
public static void main(String[] args)
94.public class TestOperator { {
public static void main(String[] args) { int index=10;
int x = 0x04; int result=0;
int y = 0x20; if (++index > 10)
int z = x && y; {
System.out.println(z); result = index;
} }
} System.out.println("index=" + index);
9
System.out.println("result=" + result); b) The last statement in the constructor
} c) You can’t call super in a constructor
} d) Any where
What is the output?
a) index=10 106.Which one of the below statements is true?
result=0 a) When a class has defined constructors with parameters,
b) index=11 the compiler does not create a default no-args constructor.
result=0 b) When a constructor is provided in a class, a corresponding
c) index=11 destructor should also be provided.
result=10 c)The compiler always creates the default no-args
d) index=11 constructor for every class.
result=11 d) The no-args constructor can invoke only the no-args
constructor of the superclass. It cannot invoke any other
99.public class Test{ constructor of the superclass.
public static void main(String[] args) {
System.out.print((-1 & 0x1f) + "," + (8 << -1)); 107.Which of the following techniques can be used to
} prevent the instantiation of a class by any code outside of the
} class?
What is the result of attempting to compile and run the a) Do not declare any constructors.
program? b) Do not use a return statement in the constructor.
a) 0,0 c) Declare all constructors using the keyword void to indicate
b) 0x1f,8 that nothing is returned.
c) 31,16 d) Declare all constructors using the private access modifier.
d) 31,0
108.Which one of the following is legal declaration for
100.What is the value of x after this code is run? nonnested classes and interfaces?
int x = 3 ; a) final abstract class Test {}
int y = 2 ;
x += (y + x * 2); b) public static interface Test {}
a) 9 c) final public class Test {}
b) 10 d) protected interface Test {}
c) 11
Topic: Class / Method Concepts 109.What is a method’s signature?
a)The signature of a method is the name of the method and
101.Which of the following is illegal for a method declaration? the type of its return value.
a) protected abstract void m1(); b) The signature of a method is the name of the method and
b) static final void m2(){} the names of its parameters.
c) transient private native void m3() {} c) The signature of a method is the name of the method and
d) synchronized public final void m4() {} the data types of its parameters.
d) The signature of a method is the name of the method, its
102.Which one of these statements is true about parameter list, and its return type.
constructors?
a) Constructors must not have arguments if the superclass 110.public class MethodTest {
b)constructor does not have arguments. public void methodSam( int a, float b, byte c) {}
c) Constructors are inherited. }
d)Constructors cannot be overloaded. Which of the following is considered as overloaded
e)The first statement of every constructor is a legal call to methodSam ?
the super() or this()method. a) private int methodSam( int a, float b, byte c) {}
b) private int methodSam( float a, int b, byte c) {return b;}
103.Here is a method definition: c) private float methodSam( int a, float b, byte c) {return b;}
int compute( int a, double y ){ . . . .} d) public void methodSam( int x, float y, byte z) {}
Which of the following has a different signature?
a) int compute( int sum, double value ){ . . . .} 111.Which one of the following is not a legal declaration for
b) double compute( int a, double y ){ . . . .} top level classes or interfaces ?
c) double compute( int sum, double y ){ . . . .} a) public abstract interface Test {}
d) int compute( int a, int y ){ . . . .} b) final abstract class Test {}
c) abstract interface Test {}
104.Which one of the following is not a legal method d) public abstract class Test {}
declaration?
a) static final void m2(){} 112.A constructor is used to
b) transient private native void m3() {} a) Free memory
c) synchronized public final void m4() {} b) Initialize a newly created object.
d) private native void m5(); c) Import packages
d) Clean up the object
105.In a constructor, where can you place a call to the super
class constructor? 113.public class Constructor {
a) The first statement in the constructor public Constructor (int x, int y, int z)
10
{} 9. }
} Which is true about the classes described above?
Which of the following is considered as overloaded a)Class A is tightly encapsulated.
constructor? b) Class B is tightly encapsulated.
a) Constructor() {} c) Classes A and B are both tightly encapsulated.
b) protected int Constructor(){} d) Neither class A nor class B is tightly encapsulated.
c) private Object Constructor() {}
d) public void Constructor(int x, int y, byte z){} 119.Given the following,
1. public class Barbell {
114.If MyProg.java were compiled as an application and then 2. public int getWeight() {
run from the command line as 3. return weight;
java MyProg I like myprogram 4. }
What would be the value of args[1] inside the main( ) method? 5. public void setWeight(int w) {
a) MyProg 6. weight = w;
b) I 7. }
c) like 8. public int weight;
d) 4 9. }
Which is true about the class described above?
115.Given the following, a) Class Barbell is tightly encapsulated.
1. long test( int x, float y) { b) Line 2 is in conflict with encapsulation.
2. c) Line 5 is in conflict with encapsulation.
3. } d) Line 8 is in conflict with encapsulation.
Which one of the following line inserted at line 2 would not
compile? 120.Examine the following code:
a) return (long) y; String str = "Hot Java";
b) return (int) 3.14d; boolean bValue = str instanceof String;
c)return ( y / x ); What value is placed in bValue?
d)return x / 7; a) true
11
6. } System.out.println("i=" + i + " j=" + j);
7. } }
8. protected class NewTreeSet { public static void main(String[] args)
9. void count() { {
10. for (int x = 0; x < 7; x++,x++ ) { TestConstructor tc = new TestConstructor();
11. System.out.print(" " + x); }
12. } }
13. } What will be the output?
14. } a) No output
What is the result? b) i=10 j=11
a) 0 2 4 c)Compilation error
b) 0 2 4 6 d) Runtime error
c) Compilation fails at line 4
d) Compilation fails at line 8 126.Given the following,
1. import java.util.*;
123.Given: 2. class Ro {
1. class Fruit { 3. Object[] testObject() {
2. private String name; 4.
3. public Fruit(String name) { this.name = name; } 5.
4. public String getName() { return name; } 6. }
5. } 7. }
6. public class MyFruit extends Fruit { Which one of the following code fragments inserted at lines
7. public void displayFruit() { } 4, 5 will not compile?
9. } a) return null;
Which of the following statement is true? b) Object t = new Object();
a) The code will compile if public MyFruit() { Fruit(); } is added return t;
to the MyFruit class. c) Object[] t = new Object[10];
b) The code will compile if public Fruit() { MyFruit(); } is added return t;
to the Fruit class. d) Object[] t = new Integer[10];
c) The code will compile if public Fruit() { this("apple"); } is return t;
added to the Fruit class.
d) The code will compile if public Fruit() { Fruit("apple"); } is 127.Given the following,
added to the Fruit class. 1. public class ThreeConst {
2. public static void main(String [] args) {
124.Given the following, 3. new ThreeConst();
1. 4. }
2. public class NewTreeSet extends java.util.TreeSet{ 5. public void ThreeConst(int x) {
3. public static void main(String [] args) { 6. System.out.print(" " + (x * 2));
4. java.util.TreeSet t = new java.util.TreeSet(); 7. }
8. public void ThreeConst(long x) {
5. t.clear(); 9. System.out.print(" " + x);
6. } 10. }
7. public void clear() { 11.
8. TreeMap m = new TreeMap(); 12. public void ThreeConst() {
9. m.clear(); 13. System.out.print("no-arg ");
10. } 14. }
11. } 15. }
Which statement added at line 1, allow the code to compile? What is the result?
a) No statement is required a) 8 4 no-arg
b) import java.util.*; b) no-arg 8 4
c) import.java.util.Tree*; c) Compilation fails.
d) import java.util.*Map; d) No output is produced.
12
1. public class CheckType { c) The code fails to compile because there is no default no-
2. int check() { args constructor for class A.
3. d) The code fails to compile because there is no default no-
4. return y; args constructor for class B.
5. }
6. public static void main(String [] args) { 132.Given the following,
7. CheckType c = new CheckType(); 1. class Base {
8. int x = c.check(); 2. Base() {
9. } 3. System.out.println("Base constructor invoked...");
10.} 4. }
Which line of code, inserted independently at line 3, will not 5. }
compile? 6.
a) short y = 7; 7. public class Derived extends Base {
b) int y = (int) 7.2d; 8. Derived() {
c) Long y = 7; 9. System.out.println("Derived constructor invoked...");
d) int y = 0xface; 10. }
11.
130.Given the following, 12. public static void main (String[] args) {
class TestFooBar { 13. Base b = new Derived();
public static Foo f = new Foo(); 14. }
public static Foo f2; 15.}
public static Bar b = new Bar(); What is the output ?
5. a)Base constructor invoked...
public static void main(String [] args) { Derived constructor invoked...
for (int x=0; x<4; x++) { b) Base constructor invoked...
f2 = getFoo(x); c) Derived constructor invoked...
f2.react(); d) Derived constructor invoked...
} Base constructor invoked...
}
static Foo getFoo(int y) { 133.Given the following,
if ( 0 == y % 2 ) {
return f; 1. public class ThreeConst {
} else { 2. public static void main(String [] args) {
return b; 3. new ThreeConst(4L);
} 4. }
} 5. public ThreeConst(int x) {
} 6. this();
20. 7. System.out.print(" " + (x * 2));
21. class Bar extends Foo { 8. }
22. void react() { System.out.print("Bar "); } 9. public ThreeConst(long x) {
23. } 10. this((int) x);
24. 11. System.out.print(" " + x);
25. class Foo { 12. }
26. void react() { System.out.print("Foo "); } 13.
27. } 14. public ThreeConst() {
What is the result? 15. System.out.print("no-arg ");
a) Bar Bar Bar Bar 16. }
b)Foo Bar Foo Bar 17. }
c) Foo Foo Foo Foo What is the result?
d) Compilation fails. a) 4 8
b) 8 4 no-arg
131.Consider the following piece of code: c) no-arg 8 4
class A { d) Compilation fails.
int x = 0;
A(int w) { 134.Given the following,
x = w; 1.
} 2. public class MyHashSet extends java.util.HashSet{
} 3. public static void main(String [] args) {
class B extends A { 4. java.util.HashSet hs = new java.util.HashSet();
int x = 0; 5. hs.clear();
B(int w) { 6. }
x = w + 1; 7. public void hmClear() {
} 8. HashMap hm = new HashMap();
} 9. hm.clear();
a) The code compiles correctly. 10. }
b) The code fails to compile, because both class A and B do 11. }
not have valid constructors. Which statement added at line 1, allow the code to compile?
13
a) import java.util.*; class B extends A {B() throws Exception {}} // 2
b) import java.util.*Map; class C extends A {C() {}} // 3
c) import java.util.Hash*; Which one of the following statements is true?
d) No statement is required a) Compile-time error at 1.
b) Compile-time error at 2.
Topic: Exceptions c) Compile-time error at 3.
d) No compile-time errors.
135.Which statement is TRUE about catch{} blocks?
a) There can only be one catch{} block in a try/catch 143.When is a finally{} block executed?
structure. a) Only when an unhandled exception is thrown in a try{}
b) The catch{} block for a child exception class must block.
PRECEDE that of a parent exception class. b) Only when any exception is thrown in a try{} block.
c) The catch{} block for a child exception class must FOLLOW c) Always after execution has left a try catch{} block, no
that of a parent exception class. matter for what reason
d) A catch{} block need not be present even if there is no d) Always just as a method is about to finish.
finally{} block.
144.Which statement is TRUE about the try{} block?
136.Both class Error and class Exception are children of this a) It is mandatory for statements in a try{} block to throw at
parent: least one exception type.
a)Throwable b) The statements in a try{} block can only throw one
b) Catchable exception type and not several types.
c) Runnable c) The try{} block can contain loops or branches.
d) Problem d) The try{} block can appear after the catch{} blocks.
14
a) Nothing. The program will not compile because no }
exceptions are specified. }
b) Nothing. The program will not compile because no catch }
clauses are specified. a) If run with one argument, the program will produce no
c) Hello world. output.
d) Hello world Finally executing b) If run with one argument, the program will simply print
the given argument.
148.What is the result of compiling and executing the below c) If run with one argument, the program will print the given
code ? argument followed by "The end".
public class TryTest { d) The program will throw an
public static void main(String[] args) ArrayIndexOutOfBoundsException.
{
try 152.Given the following:
{ public class TestDivide {
return; public static void main(String[] args) {
} int value=0;
finally try {
{ int result = 10/value;
System.out.println("Finally"); } finally {
} System.out.println("f");
} }
} }
a) Outputs nothing }
b) Finally What is the result ?
c) Compilation Error a) Compilation fails since a catch block is not present.
d) Runtime Error b) Prints only "f" in the output.
c) Only a runtime error is displayed.
149.class A { d)Prints an "f" in the output and a runtime error is also
public static void main (String[] args) { displayed.
Error error = new Error();
Exception exception = new Exception(); 153.Given the following code in the 3 java files:
System.out.print((exception instanceof Throwable) + ","); NewException.java
System.out.print(error instanceof Throwable); class NewException extends Exception {
}} }
What is the result of attempting to compile and run the Welcome.java
program? class Welcome {
a) Prints: false,false public String displayWelcome(String name) throws
b) Prints: false,true NewException {
c) Prints: true,false if(name == null) {
d) Prints: true,true throw new NewException();
150.public class MyClass { }
public static void main(String[] args) { return "Welcome "+ name;
RuntimeException re = null; }
throw re; 10.}
} TestNewException.java
} 11.class TestNewException {
What will be the result of attempting to compile and run the public static void main(String... args) {
above program? Welcome w = new Welcome();
a) The code will fail to compile, since the main() method does System.out.println(w.displayWelcome("Ram"));
not declare that it throws RuntimeException in its }
declaration. 16.}
b) The program will compile without error and will throw What is the result on compiling and executing it ?
java.lang.RuntimeException when run. a) Compiles successfully and displays Ram when
c) The program will compile without error and will throw TestNewException is executed.
java.lang.NullpointerException when run. b) Runtime exception occurs on executing the class
d) The program will compile without error and will run and TestNewException.
terminate without any output. c) Compilation of Welcome.java fails.
d)Compilation of TestNewException.java fails
151.Given the following program, which one of the
statements is true? 154.Given the following code:
public class Exceptions { public class ArithmeticTest {
public static void main(String[] args) { public static void main(String[] args){
try { try
if (args.length == 0) return; {
System.out.println(args[0]); int x=0;
} finally { int y=5/x;
System.out.println("The end"); System.out.println(y);
15
} 8. System.out.print("hello ");
catch (Exception e) 9. throwit();
{ 10. }
System.out.println("Exception"); 11. catch (Exception re ) {
} 12. System.out.print("caught ");
catch (ArithmeticException ae) 13. }
{ 14. finally {
System.out.println("ArithmeticException"); 15. System.out.print("finally ");
} 16. }
} 17. System.out.println("after ");
} 18. }
What is the output? 19. }
a) Exception What is the output ?
b) ArithmeticException a) hello throwit caught
c) NaN b) hello throwit RuntimeException caught after
d) Compilation Error c) hello throwit caught finally after
d) hello throwit caught finally after RuntimeException
155.Given the following,
1. import java.io.*; 158.public class ExceptionTest {
2. public class MyProgram { public static void main(String[] args)
3. public static void main(String args[]){ {
4. FileOutputStream out = null; try
5. try { {
6. out = new FileOutputStream("test.txt"); ExceptionTest a = new ExceptionTest();
7. out.write(122); a.badMethod();
8. } System.out.println("A");
9. catch(IOException io) { }
10. System.out.println("IO Error."); catch (Exception e)
11. } {
12. finally { System.out.println("B");
13. out.close();unhandled exception }
14. } finally
15. } {
16. } System.out.println("C");
and given that all methods of class FileOutputStream, }
including close(), throw an IOException, which one of these is }
true?
a) This program will compile successfully. void badMethod()
b) This program fails to compile due to an error at line 13. {
c) This program fails to compile due to an error at line 9. throw new Error();
d) This program fails to compile due to an error at line 6. }
}
156.Given the following: What is the output?
1. class Base { a) BC followed by Error exception
2. void display() throws Exception { throw new b) Error exception followed by BC
Exception(); } c) C followed by Error exception
3. } d) Error exception followed by C
4. public class Derived extends Base {
5. void display() { System.out.println("Derived"); } 159.Given the following,
6. public static void main(String[] args) { public class MyProgram {
7. new Derived().display(); public static void throwit() {
8. } throw new RuntimeException();
9. } }
What is the result ? public static void main(String args[]){
a) Derived try {
b) The code runs with no output. System.out.println("Hello world ");
c) Compilation fails because of an error in line 2. throwit();
d) Compilation fails because of an error in line 7. System.out.println("Done with try block ");
}
157.Given the following, finally {
1. public class RTExcept { System.out.println("Finally executing ");
2. public static void throwit () { }
3. System.out.print("throwit "); }
4. throw new RuntimeException(); }
5. } Which answer most closely indicates the behavior of the
6. public static void main(String [] args) { program?
7. try { a) The program will not compile.
16
b) The program will print Hello world, then will print that a } catch (NullPointerException e1) {
RuntimeException has occurred, then will print Done with try System.out.print("n");
block, and then will print Finally executing. } catch (RuntimeException e2) {
c) The program will print Hello world, then will print that a System.out.print("r");
RuntimeException has occurred, and then will print Finally } finally {
executing. System.out.print("f");
d) The program will print Hello world, then will print Finally }
executing, then will print that a RuntimeException has }
occurred. }
What is the output if NullPointerException occurs when
160.Given the following, executing the code in the try block ?
1. System.out.print("Start "); a) f
2. try { b)nf
3. System.out.print("Hello world"); c) rf
4. throw new FileNotFoundException(); d) nrf
5. }
6. System.out.print(" Catch Here "); 163.Given the following:
7. catch(EOFException e) { 1. class ShapeException extends Exception {}
8. System.out.print("End of file exception"); 2.
9. } 3. class CircleException extends ShapeException {}
10. catch(FileNotFoundException e) { 4.
11. System.out.print("File not found"); 5. public class Circle2 {
12. } 6. void m1() throws ShapeException {throw new
and given that EOFException and FileNotFoundException are CircleException();}
both subclasses of IOException, and further assuming this 7.
block of code is placed into a class, which statement is most 8. public static void main (String[] args) {
true concerning this code? 9. Circle2 circle2 = new Circle2();
a) The code will not compile. 10. int a=0, b=0;
b) Code output: Start Hello world File Not Found. 11.
c) Code output: Start Hello world End of file exception. 12. try {circle2.m1(); a++;} catch (ShapeException e) {b++;}
d) Code output: Start Hello world Catch Here File not found. 13.
14. System.out.printf("a=%d, b=%d", a, b);
161.Given the following code: 15. }
1. import java.io.IOException; 16.}
1. 2. public class ExceptionTest What is the expected output ?
2. { a) a=0, b=0
3. public static void main(String[] args) b) a=1, b=0
4. { c)a=0, b=1
5. try d) Compile time error at line 6.
6. {
7. methodA(); 164.Given the following:
8. } 1. class ShapeException extends Exception {}
9. catch(IOException e) 2.
10. { 3. class CircleException extends ShapeException {}
11. System.out.println("Caught IO Exception");
12. } 4.
13. catch(Exception e) 5. public class Circle1 {
14. { 6. void m1() throws CircleException {throw new
15. System.out.println("Caught Exception"); ShapeException();}
16. } 7.
17. } 8. public static void main (String[] args) {
18. static public void methodA() 9. Circle1 circle1 = new Circle1();
19. { 10. int a=1, b=1;
20. throw new IOException(); 11.
21. } 12. try {circle1.m1(); a--;} catch (CircleException e) {b--;}
22. } 13.
What is the output ? 14. System.out.printf("a=%d, b=%d", a, b);
a) The output is "Caught Exception". 15. }
b) The output is "Caught IO Exception". 16.}
c) Code will not compile. What is the expected output ?
d) Program executes normally without printing a message.
a) a=1, b=1
162.Given: b) a=0, b=1
public class TestException { c) a=1, b=0
public static void main(String... args) { d)Compile time error at line 6.
try {
// some piece of code Topic: Flow Control
17
172.Given the following code:
165.Suppose your code needs to traverse through an array public class TestBreak {
named array1. Which code would you use to do this ? public static void main(String [] args) {
a) for(int i = 0; i <= array1.length; i++) int i = 2;
b)for(int i = 0; i < array1.length; i++) if (i < 2) {
c) for(int i = 0; i <= array1.length(); i++) i++;
d) for(int i = 0; i < array1.length(); i++) break printAndExit;
}
166.Which of the following is legal? i++;
a)for (int i=0, j=1; i<10; i++, j++) { } printAndExit:
b) for (int i=0, j=1; i<10; i++; j++) { } System.out.print(i);
c) for (int i=0, j=1; i<10,j<10; i++, j++) { } }
d) for (int i=0, float j=1.0; ; i++, j++) { } }
What will be the result of the above code?
167.Which option completes the code to print the message a) 2
as long as number is greater than 20? b) 3
int number = 100 ; c) 4
MISSING CODE { d) Compilation error
System.out.println("The number = " + number);
number --; 173.Given the following:
} public class DoWhileTest {
a) do while (number > 20) public static void main(String [] args) {
b) for (number > 20) int i=2, j=5;
c)while (number > 20) do
d) if (number >20) {
if(i++ > --j) continue;
168.Suppose you are writing code for a for loop that must }while(i < 3);
execute three times.Which is the correct declaration for the System.out.printf("i=%d, j=%d",i,j);
loop? }
a) for (int i < 4; i = 1; i++) }
b) for (int i = 0; i < 4; i++) After execution, what are the values of i and j?
c) for (int i = 1; i++; i < 4) a) i=4, j=4
d) for (int i = 3; i >=1; i--) b) i=3, j=4
c) i=2, j=4
169.Which flow control mechanism determines when a block d) i=2, j=5
of code should run more than once?
a) iteration 174.Which statement is true about the following code
b) sequence fragment?
c) selection 1. int j = 2;
d) exceptions 2. switch (j) {
3. case 2:
170.Which of the following is a legal loop definition? 4. System.out.println("value is two");
a) while (int a == 0) { /* whatever */ } 5. case 2 + 1:
b) do { /* whatever */ } while (int a = 0); 6. System.out.println("value is three");
c) do { /* whatever */ } while (int a == 0); 7. break;
d) for (int a=0; a<100; a++) { /* whatever */ } 8. default:
9. System.out.println("value is " + j);
171.Given the following code: 10. break;
public class SwitchTest { 11. }
public static void main(String [] args) { The code is illegal because of the expression at line 5.
int i=5, j=0; a) The output would be
switch(i){ value is two
case 2: j+=3; b) The output would be
case 4: j+=5; value is two
default : j+=1; value is three
case 0: j+=7; c) The output would be
} value is two
System.out.println("j value " + j); value is three
} d) value is 2
}
What is the result? 175.Given the following:
a) j value 16 public class TestLoop
b) j value 8 {
c) j value 7 public static void main(String... args)
d) Compilation error ( "default" should be at the last of the {
switch statement) int index = 2;
while( --index > 0 )
18
System.out.println( index ); }
} What is the acceptable type for the variable i?
}
What is printed to standard output? a) byte
a)1 b) float
0 c) double
b) 1 d) Object
2
c) 1 180.Given the following code:
d) Nothing is printed public class TestSwitch {
public static void main(String args[]) {
176.Given the following, byte b = -1;
1. int i = 0; switch(b) {
2. label: case -1: System.out.print("-1"); break;
3. if (i < 2) { case 127: System.out.print("127"); break;
4. System.out.print(" i is " + i); case 128: System.out.print("128"); break;
5. i++; default: System.out.print("Default ");
6. continue label; }}}
7. } What is the result of attempting to compile and run the
What is the result? program?
a) Compilation fails. a) Prints: -1
b) Produces no output b) Prints: 128
c) i is 0 c) Prints: Default
d) i is 0 i is 1 d) Compile-time error
19
continue;
184.Given the following code: } while ((flag) ? true : false);
class SwitchTest { }
public static void main(String args[]) { }
int x = 3; int success = 0; What will be the output of above code?
do { a) 3210
switch(x) { b)321
case 0: System.out.print("0"); x += 5; break; c) Will go into an infinite loop
case 1: System.out.print("1"); success++; break; d)Compilation error
case 2: System.out.print("2"); x += 1; break;
case 3: System.out.print("3"); x -= 2; break; 188.Given the following code:
default: break; 1. public class Test1
} 2. {
} while ((x != 1) || (success < 2)); 3. public static void main(String[] args)
}} 4. {
What is the result of attempting to compile and run the 5. int i=0;
program? 6. while(i)
a) Prints: 3631 7. {
b) Prints: 3621 8. if(i==4) break;
c) Prints: 311 9. i++;
d) Compile-time error 10. }
11. }
185.Given the following, 12. }
1. public class Test { What will be the value of i at line 11?
2. public static void main(String [] args) { a) 0
3. int i = 1; b)4
4. do while ( i < 1 ) c)5
5. System.out.print(" i is " + i); d)The code will not compile.
6. while ( i > 1 ) ;
7. } 189.Given the following code what is the effect of the
8. } parameter "num" passed a value of 1.
What is the result? public class LoopTest {
a) i is 1 public static void process(int num) {
b) i is 1 i is 1 loop: for (int i = 1; i < 2; i++){
c)No output is produced. for (int j = 1; j < 2; j++) {
d) i is 1 i is 1 ... in an infinite loop. if (num > j) {
break loop;
186.Given the following code: }
public class JavaRunTest { System.out.println(i * j);
public static void main (String[] args) { }
int i = 0, j = 8; }
do { }
if (j < 4) {break;} else if (j-- < 7) {continue;} public static void main (String[] args) {
i++; process(1);
} while (i++ < 5); }
System.out.print(i + "," + j); }
} a) Generates a runtime error
} b) 3
What is the result of attempting to compile and run the c) 2
program? d) 1
a) Prints: 5,4
b) Prints: 6,5 190.Given the following code:
c) Prints: 6,4 public class TestIf {
d) Prints: 5,7
20
c) Compilation fails
192.Given the following: d) Produces no output
public class TestLoop2
{
public static void main(String... args) Topic: Inheritance Concepts
{
int count = 10; 195.Which statement is true?
while( count++ < 11 ) a) A super() or this() call must always be provided explicitly
System.out.println( count ); as the first statement in the body of a constructor.
} b) If both a subclass and its superclass do not have any
} declared constructors, the implicit default constructor of the
What is the output ? subclass will call super() when run.
a) 10 c) If neither super() nor this() is declared as the first
11 statement in the body of a constructor, then this() will
b) 10 implicitly be inserted as the first statement.
c) 11 d) If super() is the first statement in the body of a constructor,
d) Nothing is printed then this() can be declared as the second statement.
193.Given the following: 197.A class Car and its subclass Yugo both have a method
public class TestDoWhile run() which was written by the programmer as part of the
{ class definition. If junker refers to an object of type Yugo,
public static void main(String... args) what will the following code do?
{ junker.run();
int count = 20; a) The run() method defined in Yugo will be called.
do { b) The run() method defined in Car will be called.
System.out.println( count ); c) The compiler will complain that run() has been defined
} while ( count++ < 21 ); twice.
} d) Overloading will be used to pick which run() is called.
}
What is the output ? 198.Here is a situation:
a) 20 Birthday happy;
21 happy = new AdultBirthday( "Joe", 39);
b) 20 happy.greeting();
c) 21 Which greeting() method is run ?
d) Nothing is printed a) The one defined for Birthday because that is the type of
the variable happy.
194.Given the following: b) The one defined for AdultBirthday because that is the type
public class TestIfBoolean { of the object referred to by happy.
public static void main(String[] args) { c) The one closest in the source code to the happy.greeting()
Boolean bFlag=null; statement.
if (bFlag) { d) The assignment statement where the AdultBirthday object
System.out.print("A"); is assigned to happy variable is an error.
} else if (bFlag == false) {
System.out.print("B"); 199.Can an object of a child type be assigned to a variable of
} else { the parent type? For example,
System.out.print("C"); Card crd;
} BirthDay bd = new BirthDay("Lucinda", 42);
} crd = bd; // is this correct?
} a) No-there must always be an exact match between the
What is the expected output ? variable and the object types.
a) A b) No-but a object of parent type can be assigned to a
b) B variable of child type.
c) C c)Yes-an object can be assigned to a reference variable of the
parent type.
d) java.lang.NullPointerException is thrown at runtime d) Yes-any object can be assigned to any reference variable.
21
members of a superclass. Which is the most restrictive
access modifier that will accomplish this objective? 209.Which one of the following statement is false?
a) public a) The subclass of a non-abstract class can be declared
b) private abstract.
c)protected b) All members of the superclass are inherited by the
d)transient subclass.
c) A final class cannnot be abstract.
202.What determines what method is run in the following: d) A top level class in which all the members are declared
Card crd = new BirthDay("Lucinda", 42); private, can be declared public.
crd.greeting();
a) The type of the object or the type of the reference variable? 210.Which statement is true?
b) The type of the object. a) Public methods of a superclass cannot be overridden in
c) The type of the reference variable. subclasses.
d) Both (type of object as well as the reference variable). b) Protected methods of a superclass cannot be overridden in
subclasses.
203.Which one of the following statement is false? c) Methods with default access in a superclass cannot be
a) A subclass must override all the methods of the superclass. overridden in subclasses.
b)It is possible for a subclass to define a method with the d) Private methods of a superclass cannot be overridden in
same name and parameters as a method defined by the subclasses.
superclass.
c) Aggregation defines a has-a relationship between a 211.Which statement is true?
superclass and its subclasses. a) A subclass must define all the methods from the
d) Inheritance defines a is-a relationship between a superclass.
superclass and its subclasses. b) It is possible for a subclass to define a method with the
same name and parameters as a method defined by the
204.Which statement is true? superclass.
a) Inheritance defines a has-a relationship between a c) Aggregation defines a is-a relationship between a
superclass and its subclasses. superclass and its subclasses.
b) Every Java object has a public method named equals. d) It is possible for two classes to be the superclass of each
c) Every Java object has a public method named length. other.
d) A final class can be extended by any number of classes
212.Given the following:
205.Which statement is true? class Vehicle { }
a) Private methods of a superclass cannot be overridden in class FourWheeler extends Vehicle { }
subclasses. class Car extends FourWheeler { }
b) A subclass can override any method present in a public class TestVehicle
superclass. {
c) An overriding method can declare that it throws more public static void main(String[] args)
exceptions than the method it is overriding. {
d) The parameter list of an overriding method must be a Vehicle v = new Vehicle();
subset of the parameter list of the method that it is FourWheeler f = new FourWheeler();
overriding. Car c = new Car();
xxxxxxx
206.Which statement is true? }
a) The subclass of a non-abstract class can be declared }
abstract. Which of the following statement is legal, which can be
b) All the members of the superclass are inherited by the substituted for xxxxxxx ?
subclass. a) v = c;
c) A final class can be abstract. b) c = v;
d) A class in which all the members are declared private, c) f = v;
cannot be declared public. d) c = f;
207.What restriction is there on using the super reference in 213.Given the following,
a constructor? 1. class ParentClass {
a) It can only be used in the parent’s constructor. 2. public int doStuff(int x) {
b) Only one child class can use it. 3. return x * 2;
c) It must be used in the last statement of the constructor. 4. }
d) It must be used in the first statement of the constructor. 5. }
6.
208.Given classes A, B, and C, where B extends A, and C 7. public class ChildClass extends ParentClass {
extends B, and where all classes implement the instance 8. public static void main(String [] args ) {
method void doIt(). How can the doIt() method in A be called 9. ChildClass cc = new ChildClass();
from an instance method in C? 10. long x = cc.doStuff(7);
a) super.doIt(); 11. System.out.println("x = " + x);
b) super.super.doIt(); 12. }
c) A.this.doIt(); 13.
d) It is not possible. 14. public long doStuff(int x) {
22
15. return x * 3; d) B b2 = (B)(A)b;
16. }
17. } 217.What will be the result of attempting to compile and run
What is the result? the following program?
a) x = 14 public class Polymorphism {
b) x = 21 public static void main(String[] args) {
c) Compilation fails at line 2. A ref1 = new C();
d) Compilation fails at line 14. B ref2 = (B) ref1;
System.out.println(ref2.f());
214.1. public class TestPoly { }
2. public static void main(String [] args ){ }
3. Parent p = new Child(); class A { int f() { return 0; } }
4. } class B extends A { int f() { return 1; } }
5. } class C extends B { int f() { return 2; } }
6. a) The program will fail to compile.
7. class Parent { b) The program will compile without error, but will throw a
8. public Parent() { ClassCastException when run.
9. super(); c) The program will compile without error and print 1 when
10. System.out.println("instantiate a parent"); run.
11. } d) The program will compile without error and print 2 when
12. } run.
13.
14. class Child extends Parent { 218.Say that class Rodent has a child class Rat and another
15. public Child() { child class Mouse. Class Mouse has a child class PocketMouse.
16. System.out.println("instantiate a child"); Examine the following
17. } Rodent rod;
18. } Rat rat = new Rat();
What is the result? Mouse mos = new Mouse();
a) instantiate a child PocketMouse pkt = new PocketMouse();
b) instantiate a parent Which one of the following will cause a compiler error?
ic) nstantiate a child a) rod = rat;
instantiate a parent b) rod = mos;
d) instantiate a parent c) pkt = null;
instantiate a child d) pkt = rat;
215.1 abstract class AbstractIt 219.What would be the result of attempting to compile and
2{ executing the following code?
3 abstract float getFloat(); // Filename: MyClass.java
4} public class MyClass {
5 public class Test1 extends AbstractIt public static void main(String[] args) {
6{ C c = new C();
7 private float f1 = 1.0f; System.out.println(c.max(13, 29));
8 private float getFloat(){ return f1;} }
9 }
10 public static void main(String[] args) class A {
11 { int max(int x, int y) { if (x>y) return x; else return y; }
12 } }
13 } class B extends A{
a) Compilation error at line no 5 int max(int x, int y) { return super.max(y, x) - 10; }
b) Runtime error at line 8 }
c)Compilation error at line no 8 class C extends B {
d) Compilation succeeds int max(int x, int y) { return super.max(x+10, y+10); }
}
216.Given: a) The code will fail to compile because the max() method in
interface I1 {} B passes the arguments in the call super.max(y, x) in the
class A implements I1 { } wrong order.
class B extends A {} b) The code will fail to compile because a call to a max()
class C extends B { method is ambiguous.
public static void main( String[] args) { c) code will compile without errors and will print 29 when
B b = new B(); run.
xxxxxxx // insert statement here d) code will compile without errors and will print 39 when
} run.
}
Which code, inserted at xxxxxxx, will cause a cte? 220.Consider the following class heirarchies
a) A a = b; class A { }
b) I1 i= (C)b; class B extends A { }
c) I1 i= (A)b; class C extends B { }
23
And the following method declaration A a = new B();
public B doSomething ( ) { a.baz();
// some valid code fragments }
return xx; public void baz() {
} System.out.println("B");
Objects of which class ( from the heirarchy shown above ) can }
be safely substituted in place of xx in the method }
doSomething ( ) ? What is the result?
a) Object of class A a) A
b) An array object of class B b)B
c) Object of class C c)Compilation fails.
d) An array object of class C d) An exception is thrown at runtime.
221.Given the following code, which is the simplest print 224.Given the following:
statement that can be inserted into the print() method? 1. public class MyClass {
// Filename: MyClass.java 2. public static void main(String[] args) {
public class MyClass extends MySuperclass { 3. Derived d = new Derived("hello");
public static void main(String[] args) { 4. }
MyClass object = new MyClass(); 5. }
object.print(); 6.
} 7. class Base {
public void print() { 8. Base() { this("a", "b"); }
// INSERT CODE HERE THAT WILL PRINT 9.
// THE "Hello, world!" STRING FROM THE Message 10. Base(String x, String y) { System.out.println(x + y); }
// CLASS. 11. }
} 12.
} 13. class Derived extends Base {
class MySuperclass { 14. Derived(String s) { System.out.println(s); }
Message msg = new Message(); 15. }
} What is the output?
class Message { a) It will print hello followed by ab.
// The message that should be printed: b) It will print ab followed by hello.
String text = "Hello, world!"; c) It will print hello.
} d) It will print ab
a) System.out.println(Message.text);
b) System.out.println(msg.text); 225.Given the code below:
c) System.out.println(object.msg.text); 1. class Fruit {
d) System.out.println(super.msg.text); 2. Fruit getInstance() {
3. return this;
222.Given the following code, which of these constructors 4. }
can be added to MySub class without causing a compile-time 5. void print()
error? 6. {
class MySuper { 7. System.out.println("Fruit");
int number; 8. }
MySuper(int i) { number = i; } 9. }
} 10. 10.
class MySub extends MySuper { 11. public class Apple extends Fruit {
int count; 12. Apple getInstance() {
MySub(int cnt, int num) { 13. return this;
super(num); 14. }
count=cnt; 15. void print()
} 16. {
// INSERT ADDITIONAL CONSTRUCTOR HERE 17. System.out.println("Apple");
} 18. }
a) MySub() {} 19. public static void main(String... args)
b) MySub(int cnt) { count = cnt; super(cnt); } 20. {
c)MySub(int cnt) { this(cnt, cnt); } 21. Fruit fr = new Apple().getInstance();
d) MySub(int cnt) { super(cnt); this(cnt, 0); } 22. fr.print();
23. }
223.Given the following, 24. }
class A { What will be the output?
public void baz() { a) Fruit
System.out.println("A"); b)Apple
} c) Compilation error at Line 12; Return type of the overriding
} method getInstance() cannot be different from the return
public class B extends A { type of the overridden method of the super class.
public static void main(String [] args) { d) java.lang.ClassCast Exception at Line 21 since Apple
24
instance cannot be assigned to Fruit. }
a) The code will fail to compile.
226.Given the following, b)The use of aggregation is justified, since Planet has-a Star.
1. class B extends A { c) The code will fail to compile if the name starName is
2. int getID() { replaced with the name bodyName throughout the
3. return id; declaration of the Star class.
4. } d) An instance of Planet is a valid instance of a HeavenlyBody.
5. }
6. class C { 230.Given the following,
7. public int name; class Foo {
8. } String doStuff(int x) { return "hello"; }
9. class A { }
10. C c = new C(); Which method would not be legal in a subclass of Foo?
11. public int id; a) String doStuff(int x) { return "hello"; }
12. } b) int doStuff(int x) { return 42; }
Which one is correct about instances of the classes listed c) public String doStuff(int x) { return "Hello"; }
above? d) protected String doStuff(int x) { return "Hello"; }
a) A is-a B
b) C is-a A 231.Given:
c) B has-a A 1. public class TestOverload {
d) B has-a C 2.
3. public void process() {
227.Given the following, 4. }
1. class Over { 5.
2. int doStuff(int a, float b) { 6. public String process() {
3. return 7; 7. return "hello";
4. } 8. }
5. } 9.
6. 10. public float process(int x) {
7. class Over2 extends Over { 11. return 67.5f;
8. // insert code here 12. }
9. } 13.}
Which method, if inserted at line 8, will not compile? What is the result?
a) public int doStuff(int x, float y) { return 4; } a) An exception is thrown at runtime.
b) protected int doStuff(int x, float y) {return 4; } b) Compilation fails because of an error in line 10.
c)private int doStuff(int x, float y) {return 4; } c) Compilation fails because of an error in line 6.
d)private int doStuff(int x, double y) { return 4; } d) Compilation succeeds and no runtime errors with class
TestOverload occur.
228.Given:
abstract class Shape { 232.Given the following code:
public abstract void draw(); class MySuper {
} final int calculate(int i, int j)
public class Circle extends Shape { {
public void draw() { } return i*j;
} }
Which one of the following statement is correct? }
a) Shape s = new Shape(); public class MySub extends MySuper {
s.draw(); int calculate(int i, int j)
b) Circle c = new Shape(); {
c.draw(); return 2*i*j;
c) Shape s = new Circle(); }
s.draw();
d) Shape s = new Circle(); public static void main(String [] args) {
s->draw(); MySuper sup = new MySub();
int k = sup.calculate(2,5);
229.Given the following code, which statement is true? System.out.println(k);
public interface HeavenlyBody { String describe(); } }
class Star implements HeavenlyBody { }
String starName; What is the result?
public String describe() { return "star " + starName; } a) 10
} b) 20
class Planet { c) Compilation error
String name; d) An exception is thrown at runtime
Star orbiting;
public String describe() { 233.Given the following classes and declarations, which
return "planet " + name + " orbiting " + orbiting.describe(); statement is true?
} // Classes
25
class Foo { this.empID = empID;
private int i; this.empName = empName;
private void f() { /* ... */ } this.age = age;
public void g() { /* ... */ } }
} }
class Bar extends Foo { Which is true?
public int j; a) The class is fully encapsulated.
public void g() { /* ... */ } b)The empName variable breaks encapsulation.
} c) The empID and age variables break polymorphism.
// Declarations: d) The setEmployeeInfo method breaks encapsulation.
// ...
Foo a = new Foo(); 237.Assuming Card is the base class of Valentine, Holiday
Bar b = new Bar(); and Birthday, in order for the following code to be correct,
// ... what must be the type of the reference variable card?
a) The statement b.f(); is legal. _________ card;
b) The statement a.j = 5; is legal. card = new Valentine( "Joe", 14 ) ;
c) The statement a.g(); is legal. card.greeting();
d) The statement b.i = 3; is legal card = new Holiday( "Bob" ) ;
card.greeting();
234.Say that class Rodent has a child class Rat and another card = new Birthday( "Emily", 12 ) ;
child class Mouse. Class Mouse has a child class card.greeting();
PocketMouse. Examine the following a) Valentine
Rodent rod; b) Holiday
Rat rat = new Rat(); c) Birthday
Mouse mos = new Mouse(); d)Card
PocketMouse pkt = new PocketMouse();
Which of the following array declarations is correct for an 238.Given the following:
array that is expected to hold up to 10 objects of types Rat, 1. class Animal {
Mouse, and PocketMouse? 2. String name = "No name";
a) Rat[] array = new Rat[10]; 3. public Animal(String nm) { name = nm; }
b) Rodent[] array = new Rat[10]; 4. }
c) Rodent[] array = new Rodent[10]; 5.
d) Rodent[10] array; 6. class DomesticAnimal extends Animal {
7. String animalFamily = "nofamily";
235.Given the following, 8. public DomesticAnimal(String family) { animalFamily =
1. class MySuper { family; }
2. public MySuper(int i) { 9. }
3. System.out.println("super " + i); 10.
4. } 11. public class AnimalTest {
5. } 12. public static void main(String[] args) {
6. 13. DomesticAnimal da = new DomesticAnimal("cat");
7. public class MySub extends MySuper { 14. System.out.println(da.animalFamily);
8. public MySub() { 15. }
9. super(2); 16. }
10. System.out.println("sub"); What is the result ?
11. } a) cat
12. b) nofamily
13. public static void main(String [] args) { c) An exception is thrown at runtime.
14. MySuper sup = new MySub(); d) Compilation fails due to an error in line 8.
15. }
16. } 239.What will be the result of attempting to compile and run
What is the result? the following program?
a) sub public class Polymorphism2 {
super 2 public static void main(String[] args) {
b) super 2 A ref1 = new C();
sub B ref2 = (B) ref1;
c) Compilation fails at line 9. System.out.println(ref2.g());
d) Compilation fails at line 14. }
}
236.Given: class A {
public class Employee { private int f() { return 0; }
public int g() { return 3; }
private String empID; }
public String empName; class B extends A {
private Integer age; private int f() { return 1; }
public void setEmployeeInfo(String empID, String public int g() { return f(); }
empName, Integer age) { }
26
class C extends B { value can be shared and which does not create new object
public int f() { return 2; } for each similar declaration ?
} a) StringBuffer hello = new StringBuffer(14);
a) The program will compile without error and print 0 when b) String hello = new String("Welcome to Java");
run. c) String hello = "Welcome to Java";
b) The program will compile without error and print 1 when d) String hello[] = "Welcome to Java";
run.
c) The program will compile without error and print 2 when 246.What is the default data type of the literal represented
run. as 48.0 ?
d) The program will compile without error and print 3 when a) float
run. b)double
c) int
240.Given the following code: d) byte
class B { int m = 7; }
class D extends B { int m = 9; } 247.Which of the following is a valid declaration of char ?
public class TestBaseDerived { a) char ch="a";
public static void main(String[] args) { b) char ch = ‘cafe’;
B b = new B(); c) char ch = ‘\ucafe’;
D d = new D(); d) char ch = ‘\u10100’;
B bd = new D();
System.out.printf("%d %d %d", b.m, d.m, bd.m); 248.Which of the following is a non-primitive data type in
} Java?
} a) int
What will be the output on executing the above code ? b) float
a) 7 9 7 c) String
b) 7 9 9 d) double
c) 9 7 9
d) 9 9 7 249.Which of the following is a reserved word in the Java
programming language ?
241.Given the following, a) reference
1. class MyInherit { b) method
2. int calculate(int m, float n) { c)native
3. return 9; d) array
4. }
5. } 250.Which of the following describes an incorrect default
6. value for the types indicated?
7. class MyInheritChild extends MyInherit { a) float -> 0.0f
8. // insert code here b) boolean -> false
9. } c) Dog -> null
Which method, if inserted at line 8, will NOT compile? d) String -> "null"
a) private int calculate(int a, float b) {return 25; }
b) private int calculate(int a, double b) { return 25; } 251.Which statement is true?
c) public int calculate(int a, float b) { return 25; } a) return, goto, and default are keywords in the Java
d) protected int calculate(int a, float b) {return 25; } language.
b) new and delete are keywords in the Java language.
Topic: Keywords, Literals, Identifiers c) exit, class, and while are keywords in the Java language
d) static, unsigned, and long are keywords in the Java
242.Which of the following keywords is reserved but not language
used in Java?
a) delete 252.Which of the following variable initialization is invalid?
b) const a) byte myByte=254;
c) constant b) double myDouble=12341.509D;
d) unsigned c) int myInt = 0xFACE;
d)long myLong=45678L;
243.Which of the following is a valid initialization ?
a) boolean b = TRUE; 253.Which of the following is a valid Java identifier?
b) float f = 27.893; a) _underscore
c) int i = 0xDeadCafe; b) %percent
d) long l = 79,653; c) @attherate
d) 3numbers
244.Which of the following is a valid declaration of String ?
a) String S1=‘null’; 254.To create a class level constant, which of the following
b) String S2=null; two keywords should be used:
c) String S3 = (String) ‘face’; a) public and constant
d) String S4=(String)\ufeed; b) const and final
c) final and constant
245.What is the correct way to create a String object whose d) final and static
27
3. public static void main(String[] args)
255.Which of the following is an invalid initialization ? 4. {
a) byte y=0x7a; 5. byte b1=198;
b) short s=679; 6. byte b2=1;
c)boolean b=FALSE; 7. System.out.println(b1+b2);
d) double d=14.67f; 8. }
9. }
256.Which of the following is an invalid intialization ? a) Compilation error at Line 5.
a) float f = 85.3f; b) Compilation error at Line 7.
b) byte t = 0x5e; c) Prints 199
c) long l = 9876L; d) Prints a number different from 199.
d)boolean n = TRUE;
261.What results would print from the following code
257.Given: snippet:System.out.println("12345 ".valueOf(54321));
1. public class Test { a) 12345 54321
2. public static void main(String[] args) { b)54321
3. unsigned byte b=0; c) The application won’t compile.
4. b--; d) Runtime error
5.
6. } 262.Given:
7. } 1. public class ValueCheck {
What is the value of b at line 5? 2. public static void main(String[] args) {
a) -1 3. unsigned byte y = -1;
b) 255 4. y++;
c)Compilation error at line 3 as there is nothing like unsigned 5.
byte in Java. 6. }
d) Compilation succeeds and throws runtime exception at 7. }
line 4. What is the value of y at line 5?
a) 0
258.What is the result of compiling and executing the below b) 2
code ? c)Compilation error at line 3 as there is nothing like unsigned
1. public class Test byte in Java.
2. { d) Compilation succeeds and throws runtime exception at
3. public static void main(String[] args) line 4.
4. {
5. byte b=127; 263.What is the result of compiling and executing the below
6. byte c=15; code ?
7. byte a = b + c; 1. public class ByteTest
8. } 2. {
9. } 3. public static void main(String[] args)
a) Throws runtime exception at line no 7 saying "out of 4. {
range". 5. byte x=100;
b) Compilation succeeds and a takes the value of 142. 6. byte y=127;
c) Compilation error at line 5. Byte cant take value of 127. 7. byte z = x + y;
d) Compilation error at line 7. 8. }
9. }
259.What will be the output after compiling the following a) Throws runtime exception at line no 7 saying "out of
statements? range".
public class TestIdentifier b) Compilation succeeds and a takes the value of 227.
{ c) Compilation error at line 6. Byte cant take value of 127.
public static void main(String[] args) d)Compilation error at line 7.
{
double volatile = 21+3.775; 264.What will be the output after compiling the following
System.out.println(volatile); statements?
} public class TestIdentifier
} {
public static void main(String[] args)
a) 25 {
b) 24.775 float volatile = 53+4.289;
c) 24 System.out.println(volatile);
d) Compilation error as volatile is a keyword and cannot be }
used as identifier. }
a) 58
260.What is the result of compiling and executing the below b) 57.289
code ? c) 57
1. public class Test d) Compilation error as volatile is a keyword and cannot be
2. { used as identifier.
28
c) 24 bits
265.What is the result of compiling and executing the below d) 32 bits
code ?
1. public class Test 272.In which of these variable declarations will the variable
2. { remain uninitialized unless explicitly initialized?
3. public static void main(String[] args) a) Declaration of an instance variable of type boolean
4. { b) Declaration of a static variable of type double
5. byte y1=3; c)Declaration of a local variable of type short
6. byte y2=225; d) Declaration of a static variable of type String
7. System.out.println(y1+y2);
8. } 273.Examine the following section of code:
9. } int area;
a) Compilation error at Line 6. int perimeter;
b) Compilation error at Line 7. String name;
c) Prints 228 How many objects have been created?
d) Prints a number different from 228. a)None, there is one object reference variable, but no objects
yet.
266.What results would print from the following code b) One, there is one object reference variable so there must
snippet:System.out.println("ABCDE ".valueOf(98765)); be one object.
a) ABCDE 98765 c) Three, one for each variable.
b)98765 d) Two, one for each data type.
c) The application won’t compile.
d) Runtime error 274.What is the numerical range of char?
a) -128 to 127
267.Given: b) -( 2 ^ 15) to (2 ^ 15) -1
1. public class TestByte { c) 0 to 32767
2. d) 0 to 65535
3. public static void main(String[] args) {
4. unsigned byte t=255; 275.If i is an int and s is a short, how do you assign i to s?
5. t++; a) i = s;
6. b) i = (int) s;
7. } c) s = (short) i;
8. } d) s = i;
What is the value of t at line 6?
a) Compilation succeeds and throws runtime exception at 276.Which one of the following primitive type conversion is
line 5. permitted implicitly without using casting?
b)Compilation error at line 4 as there is nothing like unsigned a) long to int
byte in Java. b) double to long
c) 256 c) float to double
d) 0 d) double to float
Topic: Primitive Types, Objects, References 277.In which of the following answers does the number of
bits increase from fewest (on the left) to most (on the right)?
268.Which range of values is valid for all integral types, a) byte long short int
where n is the number of bits? b) int byte short long
a) 2^(n-1) to 2^(n+1)+1 c)byte short int long
b) -2^(n-1) to 2^(n-1)-1 d) short byte long int
c) -2^(n-1) to 2^(n-1)+1
d) -2^(n)-1 to 2^(n-1)-1 278.Which of the following is a valid declaration of boolean?
a) boolean b2 = no;
269.Given char c = ‘A’; b) boolean b3 = yes;
What is the simplest way to convert the character value in c c)boolean b4 = false;
into an int? d) boolean b5 = Boolean.false();
a) int i = Character.getNumericValue(c);
b) int i = (int) c; 279.Which primitive type ranges from -2^15 to (2^15)-1?
c) int i = int (c); a) char
d) int i = c; b) int
c)short
270.Which primitive type ranges from -2^31 to (2^31)-1? d) byte
a) long
b) int 280.Given :
c) short int a = 4;
d) byte byte b = 0;
Which line assigns the value of a to b?
271.The primitive type char in Java consists of a) b = a;
a) 8 bits b)b = (byte) a;
b)16 bits c) b = byte a;
29
d)b = byte(a); {
x.append(y);
281.Which of the following primitive data type is an integer y = x;
type? }
a) boolean public static void main(String[] args)
b) byte {
c) float StringBuffer x = new StringBuffer("Sun");
d) double StringBuffer y = new StringBuffer("Java");
operate(x,y);
282.Given the following code within a method, which System.out.println(x + "," + y);
statement is true? }
int a,b; }
b=5; What is the result?
a) Local variable a is not declared. a)The code compiles and prints "Sun,Java".
b) Local variable b is not declared. b) The code compiles and prints "Sun,Sun".
c) Local variable a is declared but not initialized. The code compiles and prints "Java,Java".
d) Local variable b is declared but not initialized. b) The code compiles and prints "SunJava,java".
c)The code compiles and prints "SunJava,SunJava".
283.Given: d)None of the above
int index = 2;
boolean[] test = new boolean[3]; 287.public class Test1
boolean foo = test [index]; {
What is the result? private float f1 = 1.0f;
a) foo has the value of 0. float getFloat(){ return f1;}
b) foo has the value of null. public static void main(String[] args)
c) foo has the value of true. {
d) foo has the value of false. String foo = "ABCDE";
foo.substring(3);
foo.concat("XYZ");
284.Given the following: System.out.println(foo);
1 public class Test { }
2 public static void add( Integer i) }
3 { What will be the output?
4 int val = i.intValue(); a) Compilation error in the line where "substring" is invoked
5 val +=3; b) ABXYZ
6 i = new Integer(val); c) ABCXYZ
7 } d)ABCDE
8
9 public static void main (String[] args) 288.What will be the result of attempting to compile and run
10 { the following class?
11 Integer i = new Integer(0); public class Assignment {
12 add(i); public static void main(String[] args) {
13 System.out.println(i.intValue()); int a, b, c;
14 } b = 10;
15 } a = b = c = 20;
What will be the output? System.out.println(a);
a) Compilation error }
b) Run time error at Line no. 4 }
c) 3 a) The code will fail to compile, since the compiler will
d) 0 recognize that the variable c in the assignment statement a =
b = c = 20; has not been initialized.
285.What will be the result of attempting to compile and run b) The code will fail to compile because the assignment
the following program? statement a = b = c = 20; is illegal.
public class Integers { c) The code will compile correctly and will display 10 when
public static void main(String[] args) { run.
System.out.println(0x10 + 10 + 010); d) The code will compile correctly and will display 20 when
} run.
}
a) The program will not compile. The compiler will complain 289.
about the expression 0x10 + 10 + 010 Given:
b) When run, the program will print 30 int index = 2;
c) When run, the program will print 34 Boolean[] test = new Boolean[3];
d) When run, the program will print 101010 Boolean foo = test [index];
What is the result?
286.public class Test a) foo has the value of true.
{ b) foo has the value of false.
static void operate( StringBuffer x, StringBuffer y) c)foo has the value of null.
30
d) foo has the value of 0. a) (str1 == "Unread")
b) (str1 == str2)
Topic: String Concepts c) str1.equals(str2)
d) str1.equals(str4)
290.What function does the trim() method of the String class
perform? 298.Which expression will extract the substring "kap" from a
a) It returns a string where the leading white space of the string defined by String str = "kakapo"?
original string has been removed. a) str.substring(2, 2)
b) It returns a string where the trailing white space of the b) str.substring(2, 3)
original string has been removed. c) str.substring(2, 4)
c) It returns a string where both the leading and trailing d) str.substring(2, 5)
white space of the original string has been removed.
d) It returns a string where all the white space of the original
string has been removed. 299.Which one of the following statements is true?
a) String class cannot be subclassed.
291.Which one of the following operators cannot be used in b) Subclasses of the String class can be mutable.
conjunction with a String object? c) All objects have a public method named clone().
a) + d) The expression ((new StringBuffer()) instanceof String) is
b) - always true.
c) +=
d) . 300.Given the code snippet:
String str = new String("Hello");
292.Which method is not defined in the StringBuffer class? Which of the below mentioned is an invalid call ?
a) trim() a) str.replace('H','h');
b) length() b) str.substring(2);
c) append(String) c) str.append("World");
d) reverse() d) str.trim();
293.Which method is not defined in the String class? 301.Given the following,
a) reverse()
b) length() 1. public class StringRef {
c) concat(String) 2. public static void main(String [] args) {
d)hashCode() 3. String s1 = "abc";
4. String s2 = "def";
294.Which statement concerning the charAt() method of the 5. String s3 = s2;
String class is true? 6. s2 = "ghi";
a) The index of the first character is 1. 7. System.out.println(s1 + s2 + s3);
b) The charAt() method returns a Character object. 8. }
c) The expression "abcdef".charAt(3) is illegal. 9. }
d) expression "abcdef".charAt(3) evaluates to the character What is the result?
‘d’. a) abcdefghi
b) abcdefdef
295.Which one of the statements is true? c) abcghidef
a) StringBuffer is thread safe whereas StringBuilder is not d) abcghighi
thread safe
b) StringBuffer is not thread safe whereas StringBuilder is 302.Given the following code snippet,
thread safe 13. String x = new String("xyz");
c) Both String and StringBuilder are immutable 14. y = "abc";
d) Both StringBuffer and StringBuilder are immutable 15. x = x + y;
How many String objects have been created? Assume the
296.Which one of the expressions will evaluate to true if code given above is a portion of the code present in a method.
preceded by the following code? a) 2
String a = "hello"; b) 3
String b = new String(a); c) 4
String c = a; d) 5
char[] d = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ };
a) (a == "Hello") 303.Given the following:
b) (a == b) public class TestSubstring {
c) a.equals(b) public static void main(String[] args) {
d) a.equals(d) String str = "international";
str = str.substring(6,9);
297.Which one of the expressions will evaluate to true if char b = str.charAt(2);
preceded by the following code? str = str + b;
String str1 = "unread"; System.out.println(str);
String str2 = new String(str1); }
String str3 = str1; }
char[] str4 = { ’u’, ’n’, ’r’, ’e’, ’a’, ’d’ }; What is the result? Assume the code given above is a portion
31
of the code present in a method. public class MyClass {
a) atia public static void main(String[] args) {
b)atii String s = "hello";
c) atioa StringBuffer sb = new StringBuffer(s);
d) atiot sb.reverse();
if (s == sb) System.out.println("a");
304.What will be the result of attempting to compile and run if (s.equals(sb)) System.out.println("b");
the following code? if (sb.equals(s)) System.out.println("c");
public class StringMethods { }
public static void main(String[] args) { }
String str = new String("eenny"); a) The program will throw a ClassCastException when run.
str.concat(" meeny"); b) The code will fail to compile since the expression (s == sb)
StringBuffer strBuf = new StringBuffer(" miny"); is illegal.
strBuf.append(" mo"); c) The code will fail to compile since the expression
System.out.println(str + strBuf); (s.equals(sb)) is illegal.
} d) The program will print c when run.
}
a) The program will print "eenny meeny miny" when run. 309.What will be the result of attempting to compile and run
b) The program will print "eenny meeny miny mo" when run. the following program?
c) The program will print "meeny miny mo" when run. public class MyClass {
d) The program will print "eenny miny mo" when run. public static void main(String[] args) {
StringBuffer sb = new StringBuffer("have a nice day");
305.What will be the result of attempting to compile and run sb.setLength(6);
the following code? System.out.println(sb);
public class RefEq { }
public static void main(String[] args) { }
String s = "ab" + "12"; a) The code will fail to compile since there is no method
String t = "ab" + 12; named setLength in the StringBuffer class.
String u = new String("ab12"); b) The program will throw a
System.out.println((s==t) + " " + (s==u)); StringIndexOutOfBoundsException when run.
} c) The program will print "have a" when run.
d) The program will print "ce day" when run.
}
a) The program will print true true when run. 310.What will the following program print when run?
b) The program will print false false when run. public class Search {
c) The program will print false true when run. public static void main(String[] args) {
d) The program will print true false when run. String s = "Contentment!";
int middle = s.length()/2;
306.Given the following code snippet, String nt = s.substring(middle-1, middle+1);
String x = "xyz"; System.out.println(s.lastIndexOf(nt, middle));
x.toUpperCase(); }
String y = x.replace(‘Y’, ‘y’); }
y = y + "abc"; a) 2
System.out.println(y); b) 4
What is the result? Assume the code given above is a portion c) 5
of the code present in a method. d) 7
a) abcXyZ
b) abcxyz 311.What will be the result of attempting to compile and run
c)xyzabc the following code?
d) XyZabc class MyClass {
public static void main(String[] args) {
307.Given the following: String str1 = "str1";
public class TestStringBuffer { String str2 = "str2";
public static void main(String[] args) { String str3 = "str3";
StringBuffer strBuff = new StringBuffer("java platform"); str1.concat(str2);
strBuff.deleteCharAt(4); System.out.println(str3.concat(str1));
System.out.println(strBuff); }
} }
} a) The program will print str3str1 when run.
What is the output ? b) The program will print str3str1str2 when run.
a) jav c) The program will print str3 when run.
b)java d) The program will print str3str2 when run.
c) platform
d) javaplatform 312.Which one of the following is not legal?
a) System.out.println("st".concat("ep"));
308.What will be the result of attempting to compile and run b) System.out.println("st" + "ep");
the following program? c) System.out.println(’s’ + ’t’ + ’e’ + ’p’);
32
d) System.out.println("st" + new String(’e’ + ’p’)); 318.The JAR files are packaged using the following format
a) TAR
313.What will be written to the standard output when the b) ZIP
following program is run? c) ARJ
import static java.lang.System.out; d) CAB
public class TestOutput {
public static void main(String[] args) { 319.In order to run a jar file, say "app.jar" using the command
String space = " "; "java -jar app.jar", what condition should be satisfied?
String composite = space + "windows" + space + space; a) app.jar should be given executable permission
composite.concat("server"); b) The manifest file of the jar should specify the class whose
String trimmed = composite.trim(); main method should be executed.
out.println(trimmed.length()); c) "-jar" is an invalid option for java command and an error
} will be displayed.
} d) There should be a class "app.class" with the same name as
a) 7 the jar file for the command to work.
b) 9
c) 13 320.Which one of the following is not a valid header in the
d) 15 manifest of jar file?
a) Specification-Title
314.Which expression will evaluate to true? b)Application-Version
a) "Hello there".toLowerCase().equals("hello there") c) Implementation-Vendor
b) "HELLO THERE".equals("hello there") d) Name
c) ("hello".concat("there")).equals("hello there")
d) "Hello There".compareTo("hello there") == 0 321.A special file which is present inside the JAR that contain
information about the files packaged in a JAR file is known as
315.Given the following code snippet, a) Metafest
4. String d = "bookkeeper"; b) Metadata
5. d.substring(1,7); c) Manifest
6. d = "w" + d; d) Manidata
7. d.append("woo");
8. System.out.println(d); 322.You decide that you wish to add your application’s class
What is the result? Assume, the code given above is a portion to a group of classes that are stored in the location
of the code present in a method. /examples/basics.
a) wookkeewoo Complete the code to do this
b) wbookkeewoo a) package examples.basics;
c) Compilation fails. b) import examples.basics;
d) An exception is thrown at runtime. c) import package examples.basics;
d) package examples/basics;
316.What will be the result of attempting to compile and run
the following code? 323.We want the code in Test.java to access the
public class TestStringOperation { example.basics.Utilities class which is stored within the
public static void main(String[] args) { example.jar file in the directory /jars. How would you
String str1 = new String("java"); compile your code?
str1.concat(" world"); a) javac -classpath /jars/example.jar Test.java
StringBuffer strBuf1 = new StringBuffer(" magazine"); b) javac -classpath /jars/example Test.java
strBuf1.append(" article"); c) javac -classpath /jars/ Test.java
System.out.println(str1 + strBuf1); d) javac -classpath /jars Test.java
}
} 324.Suppose you are creating a class named Button that you
a) The program will print "java magazine article" when run. want to include in a group of related classes called controls.
b) The program will print "world magazine article" when run. Identify the correct code that includes the class in that group.
c) The program will print "java world magazine" when run. a) package controls;
d) The program will print "java world magazine article" when b) public class Button
run. c) package Button;
d) import controls;
Topic: Package, Import, Jar Concepts
325.Which is true about the package statement in Java?
317.Which is true about the import statement in Java? a) It can appear anywhere in the file as long as the syntax is
a) When .* is used in an import statement, all the classes in correct.
that package and the sub-packages will be imported. b) It should appear after all the import statements but before
b) The import statements must appear before any package the class declaration.
statement is declared. c) There can be more than one package statement.
c) The import statement must be the first statement after d)It should be the first non-comment line in the Java source
any package declaration in a file. file.
d) The import statement is mandatory when using classes of
other packages since there is no other way to use a class. 326.Following is a file format which enables to bundle
multiple files into a single file
33
a) JPG and the command-line invocation as,
b) PNG java CommandArgsTwo 1 2 3
c) TIF 1. public class CommandArgsTwo {
d) JAR 2. public static void main(String [] argh) {
3. String [] args;
327.Which is the manifest header that is used to specify the 4. int x;
application’s entry point in a JAR file? 5. x = argh.length;
a) Class-Path 6. for (int y = 1; y <= x; y++) {
b) Entry-Class 7. System.out.print(" " + argh[y]);
c) Start-Class 8. }
d)Main-Class 9. }
10. }
328.Suppose a class named App1 is located in the What is the result?
samples.messages package. You have compiled the class. a) 0 1 2
How do you execute the class? b) 1 2 3
a) java App1 c) 0 0 0
b) java samples.messages.App1 d) An exception is thrown at runtime
c) javac samples.messages.App1
d) java samples.messages.App1.class 333.Given the following code:
public class Test {
329.Why is the main() method special in a Java program? public static void main(String[] args)
a) It is where the Java interpreter starts whole program {
running. System.out.println(args.length);
b) Only the main() method may create objects. }
c) Every class must have a main() method. }
d) main() method must be the only static method in a If the above code is compiled and run as follows
program. java Test Hello 1 2 3
What would be the output ?
330.Given the following code: a) 6
public class Test { b) 5
public static void main(String[] args) c) 4
{ 334.Given A.java contains
System.out.println(args[0]); class A {public static void main(String... args) {}} // 1
} and B.java contains
} class B {protected static void main(String[] args) {}} // 2
If the above code is compiled and run as follows What is the result of attempting to compile each of the two
java Test Hello 1 2 3 class declarations and invoke each main method from the
What would be the output ? command line?
a) java a) Compile-time error at line 1.
b) Test b) Compile-time error at line 2.
c) Hello c) An attempt to run A from the command line fails.
d) Hello 1 2 3 d) An attempt to run B from the command line fails.
34
} a) Junit
} b) Jprofiler
If the above code is compiled and run as follows c)WiproStyle
java Foo Apples 9 8 7 d) None of the above
What would be the output ?
a) java 342.Which of the following is correct with respect to severity
b) Foo level information in Static Analyzers?
c) Apples a) Severity levels information helps to fix only the violations
d) 9 with critical severity
b) Severity levels information helps to ignore the violations
337.Given the below mentioned code with minor severity
and the command-line invocation as, c) Severity levels information helps in better prioritization of
java CommandArgsFour 9 6 3 violations
d) All of the above
public class CommandArgsFour {
public static void main(String [] argh) { 343.What is WiproStyle?
String [] args; a) WiproStyle is a unit testing tool
int a; b)WiproStyle is a static analysis tool
a = argh.length; c) WiproStyle is a structural analysis tool
for (int b= 1; b < a; b++) { d) WiproStyle is a testing tool
System.out.print(" " + argh[b]);
} 344.Which of the following refers to the analysis of computer
} software that is performed without actually executing
} programs?
What is the result? a) runtime analysis
a) null null b) static analysis
b) 9 6 c) profiling
c) 6 3 d) none of the above
d) An exception is thrown at runtime
345.What are coding standards?
338.Given the below mentioned code
and the command-line invocation as, a) Standards to avoid code construct having high probability
java CommandArgsFive 9 8 7 6 of resulting in an error.
public class CommandArgsFive { b) Standards to be followed during System testing.
public static void main(String [] args) { c) Stdards used for defining designing guidelines for the
Integer i1 = new Integer(args[1]); system.
Integer i2 = new Integer(args[2]); d) Standards that cannot be followed during the CUT phase
Integer i3 = new Integer(args[3]);
Integer i4 = new Integer(args[4]); 346.Which of the WiproStyle rule is violated in below snippet
System.out.print(" args[3] = " + i3); of code,
} public class Sample{
} public int method1() {
What is the result? int a =10; int b=20;
a) args[3] = 8 int c = a*b;
b) args[3] = 7 return c;
c) args[3] = null }
d) An exception is thrown at runtime }
a) Minimize the number of lines by joining multiple shorter
Topic: WiproStyle lines
b) Avoid return statements
339.When does 'Avoid magic numbers' rule in WiproStyle c) Declare all variables in a single line
throw a violation? d) Avoid multiple variable declaration in single line
a) Integer variable is declared
b) A numeric literal that is not defined as a constant is 347.Which of the following is a benefit of using static
detected analyzer?
c) When the integer variable is made global a) Non-Compliance to coding guidelines can be detected
d) No such rule in WiproStyle automatically.
b) Unit testing can be performed
340.Which of the following are advantages of using c) Code coverage can be measured
WiproStyle for code review? d) can reverse engineer the code
a) Reduces code review effort
b) Code is generated automatically 348.Which is the earliest phase in which Wiprostyle can be
c) Code can be reverse engineered used?
d) All the above a) System testing
b) Design
341.Which of the following can be used to automate code c) Requirements
review in Java? d) Coding
35
String firstName, LastName;
349.Which of the WiproStyle error category is violated in int myAge, mySize, numShoes = 28;
below snippet of code, int a = 4, b = 5, c = 6;
class Foo{ }
public void testA () { a) Avoid Nested Blocks
System.out.println("Entering test");//VIOLATION b) Multiple variable declaration on the same line
} c) Empty Block
} d) Missing Switch Default
a) Maintainability
b) Security 356.Which of the following violations is thrown by
c) Reliability WiproStyle in below code section?
d) Efficiency public class SampleViolation{
351.Which of the following rules does WiproStyle handle? 357.Which of the following options should be used to correct
a) Rules to detect code coverage the violation on line 9?
b) Formatting ,naming conventions, java doc 1.class Foo {
c) Rules to detect failed test cases 2. void bar() {
d) None of the above 3.try
4.{
352.Which of the software code quality attribute can be 5. compressThumbnailToDisk(metadata, image);
improved by following consistent formatting standard? 6.}
a) Security 7.catch (IOException e)
b)Maintainability 8.{
c) Efficiency 9. e.printStackTrace(); //Violation
d) Formatting related standards do not improve any code 10. throw new ResourceError(e.getMessage());
quality attributes 11.}
353.Which of the following violations is thrown by a) System.out.println()
WiproStyle in below code section? b) java doc
public class SrrayListExample { c) System.print.err
int method(int a, int b) { d) logger
int i = a + b;
return i; 358.Which of the following violations is thrown by
} WiproStyle in below code section?
} public class SampleViolation {
a) Use arraylist instead of vector public int publicVariable; // VIOLATION
b) Class should define a constructor protected int protectedVariable; // VIOLATION
c) Avoid instantiating string objects int packageVariable; // VIOLATION
d) Unused import }
a) Trailing Array Comma
354.Which of the following violations is thrown by b) Visibility Modifier
WiproStyle in below code section? c) SuperFinalize
public class Foo { d) Missing Switch Default
public void bar() {
int x = 2; 359.Which of the following violations is thrown by
switch (x) { WiproStyle for below code section?
case 2: import java.*;
int j = 8; import java.util.*;
} import java.io.IOException;
} public void Helllo{
} }
a) Avoid Nested Blocks a) Use only Star (Demand) Imports
b) Use arraylist instead of vector b) Trailing Array Comma
c) Missing Switch Default c) Avoid Star (Demand) Imports
d) Multiple variable declaration on the same line d) Avoid multiple import statements
355.Which of the following violations is thrown by 360.Which of the following violations is thrown by
WiproStyle in below code section? WiproStyle in below code section?
class A{ public interface Foo {
int x, y, z; public void method (); // VIOLATION
36
abstract int getSize (); // VIOLATION public void method () throws InterruptedException {
static int SIZE = 100; // VIOLATION wait (); // VIOLATION
} } What is the cause of the above violation.
a) Redundant Modifier a) Avoid using exceptions as flow control
b) Trailing Array Comma b) Avoid throwing raw exception types
c) Avoid Star (Demand) Imports c) Do not implement 'SingleThreadModel' interface
d) SuperFinalize d) Call wait() inside while or do-while
361."Explicitly invalidate Session when user logs off" . This 367.public class Test {
rule address public static void main() { // VIOLATION
a) Java secure coding }
b) Concurrency and Timing problems public void test() {
c) Data handling problems }
d) Logical problems public void test1() {
websession }
}
362.Which of the following violations will be thrown on the What may be the possible coding standard violation in the
given code snippet. above snippet
class Foo { boolean bar(String a, String b) { return a == b; }} a) Placement of Constants
a) Do not instantiate a StringBuffer with a char b) Avoid Multple overloaded methods
b) Use equals() to compare object references c) Place Main method as last method
c) Avoid chaining assignment operators d) Use Chain Constructors
d) Always initialize static fields
368.public class Test {
363.What violation is expected to be thrown by wiprostyle on int AGE; // Violation
the below code ? public void method1() {
public class Test { int AGE;
int method (int a, int b) { }
int i = a + b; return i; // Violation String NA__ME11; // Violation
} } What is the java coding standard violation expected in the
a) Simple Statements - line with more than a single code snippet above?
statement a) Reduntant Modifiers
b) Avoid chaining assignment operators b) Declare fields with uppercase character names as 'final'
c) Trailing Array Comma c) Avoid unused private fields
d) Avoid assignments in operands d) Always initialize static fields
369.public class MI {
364.public int convert(String s) { public String[] getNames() {
int i, i2; String[] names = {"ashik","hema"};
i = Integer.valueOf(s).intValue(); // Violation if(names.length != 0) {
i2 = Integer.valueOf(i).intValue(); // Violation return names;
return i2; } else {
} return null;//Violation
What is the cause of the violation in the above code , that }
wiprostyle may throw. }
a) Do not add empty strings }
b) Consider replacing this Vector with the newer java.util.List How can the above highlighted coding standard violation be
c) Unneccessary Wrapper Object creation fixed?
d) Avoid instantiating String objects; this is usually a) Return Zero length array instead of null
unnecessary b) Avoid return statements
c) Do not add empty strings
365.public class Foo { d) Avoid instantiating String objects; this is usually
public void bar() { unnecessary
try {
// do something 370.public abstract class Sample { //VIOLATION
} catch (Throwable th) { //violation public abstract StringBuffer getText();
th.printStackTrace(); public abstract int getStartPosition();
} public abstract int getEndPosition();
} public abstract int getStartLine();
} public abstract int getEndLine();
a) Avoid using exceptions as flow control }
b) Avoid catching NullPointerException; consider removing What may be the violation thrown by a static analyzer at
the cause of the NPE the highlighted line.
c)Avoid throwing raw exception types a) If a class Extends / Implements other class then it should
d) A catch statement should never catch throwable since it have a Naming Convention as defined by the user
includes errors b) anonymous classes used as interface implementors
c) Redeclare non-functional class as interface
366.public class InvokeWait { d) Avoid multiple Class or Interface
37
public void bar() {
371."The ability of a software product to keep operating over int x = 2;
time without failures that renders the system unusable" is x = x; //Violation
called ( as per ISO 9126) }
a) Portability }
b) Maintainability What is the java coding standard violation that may be
c) Reliability thrown on the above code at the highlighted line?
d) Efficiency a) Possible unsafe assignment to a non-final static field in a
constructor
372."The aptitude of the source code to undergo repair and b) Unused Local Variable
evolution". Is called ( as per ISO 9126) c) Consider simply returning the value vs storing it in local
a) Efficiency variable ''{0}''
b) Reliability d) Avoid idempotent operations (like assigning a variable to
c) portability itself)
d) Maintainability
379.public class Foo {
373.Examination of code intended to find and fix mistakes void bad() {
overlooked in the initial development phase. List foo = getList();
a) Profiling if (foo.size() == 0) {//Violation
b) unit testing // blah
c) defect tracking }
d) code review }
How the above violation be fixed regarding collection?
374.What is the ideal time for starting the usage of static a) Perhaps ''{0}'' could be replaced by a local variable
analyzers b)Position literals first in String comparisons
a) as soon as the coding starts. c) Substitute calls to size() == 0 (or size() != 0) with calls to
b) once all the coding is over isEmpty()
c) along with system testing d) Avoid instantiating String objects; this is usually
d) after unit testing unnecessary
375.What is the recommended procedure for usage of static 380.The capability of the software product to protect
analyzers if you have legacy code ? (existing code base) information and data so that unauthorized persons or
a) Static analyzer should be run on the legacy code as well systems cannot read or modify them and authorized persons
b) No need to run static analyzer on Legacy code base. or systems are not denied access to them is termed as
c) static analyzer usage is not reccomended in this scenario a) Security
d) Static analyzers are supposed to be run on the newly b) Efficiency
developed LOCs by you. c) Stability
d) Usability Compliance
376.The capability of the software product to avoid
unexpected effects from modifications of the software. (ISO
9126) is termed as 381.class Foo {
a) adaptability boolean bar(String x) {
b) portability return x.equals("2"); // Violation
c) testability }
d) stability }
What is the cause of above violation?
377.public class Foo { a) Unneccessary Wrapper Object creation
void bar(int a) { b) Position literals first in String comparisons
switch (a) { c) Avoid instantiating String objects; this is usually
case 1: unnecessary
// do something d) Do not instantiate a StringBuffer with a char
break;
mylabel: // Violation 382.public class Foo {
break; Object bar;
default: // bar is data or an action or both?
break; void bar() { //Violation
} }
} }
} Reason for the violation at the highlighted line in the code
What may be the cause of the above violation? snippet may be due to
a) The default label should be the last label in a switch a) The field name indicates a constant but its modifiers do
statement not
b)A non-case label was present in a switch statement b) It is somewhat confusing to have a field name matching
c) Case with no break the declaring class name
d) Non-static initializers are confusing c) It is somewhat confusing to have a field name with the
same name as a method
378.public class Foo { d) Non-static initializers are confusing
38
383.public class Foo extends Bar { 389.Select the correct statement related to unit testing
int foo; //Violation a) Systematically done unit testing can replace system
} testing
Reason for the violation at the highlighted line in the code d) If code reviews & code inspections are done thoroughly
snippet may be due to unit testing is NOT required
a) It is somewhat confusing to have a field name matching b) Both Unit testing and System testing are required as they
the declaring class name compliment each other
b) It is somewhat confusing to have a field name with the c) In any case either system testing or unit testing is required;
same name as a method but NOT the both
c) The field name indicates a constant but its modifiers do
not 390.Unit testing is required even if code reviews & code
d)Non-static initializers are confusing inspections are done thoroughly. Check the correctness
a) Above statement is correct only in case of large
384.The Phase in which code review tools / static analyzers applications
are supposed to be used for best results b) Above statement is correct only in case of small
a) CUT phase applications
b) System Testing c) Above statement is correct in case of all applications
c) Design d) Above statement is NOT correct in case of all applications
d) Integration Testing
391.What is unit testing?
385.public class SampleViolation { a) Testing each unit of code in an isolation
public copyArray (int[] array) { b) Testing code linewise
int k =0; c) Testing individual class of code in an isolation
int length = array.length; d) None of the above
int[] copy = new int [length];
for(int i = 1; i < length;i++) { 392.What is the purpose of Data Driven Test (DDT) testing
copy[i] = array[i]; // VIOLATION feature?
} a)editing of tests to change values in tool generated test
while(k < length){ cases
copy[k] = array[k++]; // VIOLATION b) generation of more number of test so that method can be
} tested with all possible values
} c) Customization of test classes. It allows users to add any
} number of test classes
What is the reccomended procedure to fix the above d) Parameterization of tests with user defined test data
violations thrown on coping two arrays
a) Instead of copying data between two arrays, use 393.What is the basic intention of performing unit testing?
System.arraycopy method which is efficient. a) to avoid system testing
b) Do not add empty arrays b) to avoid system functionality testing
c) Trailing Array Comma c) to detect problems early in the development stage
d) Avoid arraylength in loops d) to avoid regression testing
386.A form of static analysis based on the definition and 394.Which of the following is given highest priority while
usage of variables fixing unit testing problems ?
a) Profiling a) Assertion failures
b) Data Flow Analysis b) Exceptions
c) peer review c) Timeout errors
d) coverage analysis d) No prioritization is required
387.class Foo { void bar(Object x) { if (x != null && x 395.What is Code coverage analysis?
instanceof Bar)// Violation. a) Process of finding areas of a program NOT exercised by a
What may be the cause of the violation? set of test cases
a) Reduntant Modifiers b) Process of finding failed test cases
b) Avoid chaining assignment operators c) Process of finding areas of programs throwing errors
c) No need to check for null before an instanceof d) Process of finding areas of program NOT exercised
d) Avoid assignments in operands because of exceptions
39
a) Type coverage will Catch all the Bugs Anyway.
b) Block coverage b) Cost of fixing a defect identified during the early stages is
c) Package coverage less compared to that during later stage.
d) Test coverage c) We can test parts of a project with out waiting for the
other parts to be available
398.How does calculating and tracking of metrics help? d) Designers can identify and fix problem immediately, as the
a) Helps in reducing static analysis effort modules are best known to them. This helps in fixing
b) Helps to identify some of the symptoms of poor design multiple problems simultaneously
c) Helps to avoid unit testing
d) None of the above 404.What is meant by Code Coverage in Unit Testing ?
a) A code coverage tool simply keeps track of which parts of
399.Examine the code coverage for below code. your code get executed and which parts do not.
public void testAdd1() throws Throwable { b) A code coverage tool simply keeps track of pass and
int actual1 = Arithmetic.add(338,18); failure scenario of test cases.
assertEquals(356, actual1); c) A code coverage tool simply keeps track of which parts of
int actual2 = Arithmetic.add(36, 39); your code has private and protected method.
assertEquals(75, actual2); d) None of the above
int actual3 = Arithmetic.add(100, 8);
assertEquals(108, actual3); 405.How a Unit testing framework will be helpful for Unit
} Testing
a) Full Coverage a) It helps to skip unit testing and do functional testing
b) Partial coverage directly so as to reduce effort
c) Not Covered b)It helps to simplify the process of unit testing by reusable
d) None of the above set of libraries or classes that have been developed for a
wide variety of languages
400.Which of the following statement is correct with respect c) which helps to test values with boundary conditions
to private method in Unit Testing ? d) None of the above
a) Private methods can't be tested during unit testing
b) When a method is declared as "private", it can only be 406.What is Data Driven Testing in Unit Testing ?
accessed within the same class. So there is no way to test a a) It is a test approach to test private method in the class
"private" method of a target class from any test class. So we b) It is single test to verify many different test cases by
can write a test case inside target class driving the test with input and expected values from an
c) When a method is declared as "private", it can only be external data source
accessed within the same class. So there is no way to test a c) It is a test approach to test protected method in the class
"private" method of a target class from any test class. You d) It is a test approach to test values with boundary
have to perform unit testing manually. Or you have to conditions
change your method from "private" to "protected".
d) None of the above 407.Which of the below statements are true about Data
Driven Testing in Unit Test?
401.Which of the following statement is correct with respect 1) all input data and expected results for your automated
to protected method ? tests are kept in one place, which makes it easier to maintain
a) Protected methods can not be tested during unit testing test cases
b) When a method is declared as "protected", it can only be 2)you can also execute expressions specified in cells of the
accessed within the same package where the class is processed storage (for example, your storage can contain the
defined.In order to test a "protected" method of a target value of 5+5)
class, you need to define your test class in the same package 3)After first failure test case remaining test cases will not be
as the target class. executed
a) Both 1 & 2
b) Both 1 & 3
c) When a method is declared as "protected", it can only be c) Both 2 & 3
accessed within the same package where the class is defined d) All three statements
we can write a test case inside target class.
d) None of the above 408.How to write a test case for the method add in the below
class Sample.
402.What are the benefits of Unit Testing?
a) The modular approach during Unit testing eliminates the a) public class Sample { private int addInteger(int i, int
dependency on other modules during testing. j){ int sum; sum=i+j; return sum; } }
b) We can test parts of a project with out waiting for the b) Private methods can't be tested during unit testing
other parts to be available. Test case can be written inside target class itself
c) Designers can identify and fix problem immediately, as the c) Unit testing needs to be done either manually or test case
modules are best known to them. This helps in fixing can be written by changing access modifier "private" to
multiple problems simultaneously "protected"
d) All of the above d) None of the above
403.Which of the following statement is wrong about unit 409.protected int addInteger(int i, int j){ int sum; sum=i+j;
testing return sum; }
a) Integration Test is a replacement of Unit testing which How a test case can be written for this method?
40
a) Protected methods can not be tested during unit testing }
b) Test case can be written by defining the test class in the How test case can be written for the above method?
same package as the target class. a) Test case can't be written since it has Connection object as
c) Since protected methods can't be accessed outside the a parameter
package unit testing needs to be done either manually or b) Object mocking can be used to write test cases
test case can be written by changing access modifier c) Data Driven Testing can be used to write test cases
"protected" to "public" d) None of the above
d) None of the above
414.public class ConstructorExample {
410.public static int Divide (int i1, int i2) { return i1/i2; } public static long getFileLength (String path) throws
How a test case can be written for this method ? IOException {
a) public void testDivide1() throws Throwable { int actual1 = RandomAccessFile file = new RandomAccessFile (path,
Arithmetic.Divide(1, -2147483648); assertEquals(1, actual1); "rw");
int actual2 = Arithmetic.Divide(-2147483648, 1); return file.length ();
assertEquals(1, actual2); } }
b) Test case can't be written since it is static method }
c) Test case can't be written since it is public method How a test case can be written for this method ?
d) None of the above a) Test case can't be written for this method
b) Stubs can be used to write test cases
411.How a test case can be written for this method ? c) Data Driven Testing can be used to write test cases
public static boolean startsWith(String str,String match){ d) None of the above
for (int i= 0; i < match.length(); ++i) {
if(str.charAt(i)!= match.charAt(i)) 415.public static List getScores(String team_name) throws
return false; SQLException {
} _loggedCalls.add("getScores: " + team_name);
return true; prepare();
} List list_scores = new ArrayList();
a) public void testStartsWith1() throws Throwable { boolean Statement stmt = _connection.createStatement();
actual1 = Arithmetic.startsWith("853956.85395645", "d R0"); ResultSet rs = stmt
assertEquals(false, actual1); boolean actual2 = .executeQuery("SELECT * FROM SCORES WHERE
Arithmetic.startsWith("853956.85395645", (String) null); TEAM_NAME='"
assertEquals(true, actual2); } + team_name + "'");
while (rs.next()) {
b) public void testStartsWith1() throws Throwable { boolean int score = rs.getInt("SCORE");
actual1 = Arithmetic.startsWith("853956.85395645", "d R0"); list_scores.add(new Integer(score));
assertNotNull(false, actual1); boolean actual2 = }
Arithmetic.startsWith("853956.85395645", (String) null); return list_scores;
assertNotNull(true, actual2); } }
How a test case can be written for this method ?
c)Test case can't be written since it is static method a) Test case can't be written for this method
d) Test case can't be written since it is public method b) Stubs can be used to write test cases
c) Data Driven Testing can be used to write test cases
412.public class Student { public void setAge(int age) { d) None of the above
this.Age = age;
}} 416.public static void addsample()
How the case can be written for the above bean class method? { int i,j,k; k=i+j;}
a) No need to write a test case for bean class methods How test case can be written for the above method?
b) public void testSetAge1() throws Throwable { Student a) Test case is not required as there is no functionality in this
student = new Student(); student.setAge(0); method affected by external calls
student.setAge(1); student.setAge(-1); b) Stubs can be used to write test cases
student.setAge(2147483647); student.setAge(-2147483648); c) Data Driven Testing can be used to write test cases
} d) None of the above
c) Bean class methods can not be tested during unit testing
d) None of the above 417.Which of the following is a framework for Java Unit
testing ?
413.public class TestDb { 1 JUnit 2 GUnit 3 NUnit 4 Unit++
public String readABC(Connection c,String table_name)
throws SQLException{ 418.Please identify Java Unit testing tools
Statement stm=c.createStatement(); 1) JDeveloper 2) JTest 3) WiproUT 4)JUnit
ResultSet rs=stm.executeQuery("select a
from"+table_name); 2,3,4
int a=0; 1,2,4
a=rs.getInt("a"); All 1,2,3 &4
String result; Only 4
result =" result "+ a ;
return result; 419.
} public static int Divide (int i1, int i2) { return i1/i2; }
41
Please examine the below test case for the above method. Java Eclipse IDE ?
public void testDivide1() throws Throwable { 1NUnit 2 C++Unit 3 JUnit 4 Cactus
int actual1 = Arithmetic.Divide(16,8);
assertEquals(2, actual1); 428.public static int add (int i1, int i2) {
int actual2 = Arithmetic.Divide(18, 1); return i1 + i2;
assertEquals(1, actual2); } }
a) Given test case won't be executed since test case can't be What would be the output for below test suite if add() has the
written for static method above functionality ?
b) First assert statement will be passed and second assert public void testAdd1() throws Throwable {
will be failed int actual1 = Arithmetic.add(1,8);
c) Both assert statement will be passed assertEquals(9, actual1);
d)Test case is not required for this method int actual2 = Arithmetic.add(1, 8);
assertEquals(9, actual2);
420.Ideally, at what stage in the SDLC cycle Unit Testing tool int actual3 = Arithmetic.add(0, 8);
is applicable? assertEquals(8, actual3);
1 CUT phase 2 Testing phase 3 Design phase 4 }
UAT phase All assert statements will be passed
The given assertEquals() syntax is wrong
421.Ideally, Unit Testing tool is supposed to be used by Test case will be failed in second assert statement
___________ Parameters given to assertEquals() are wrong
1 only Project Managers 2 All Developers 3 only Test
Engineers 4 only Quality Analyst 429.How to write best test case for below method by "re-
usability test logic" ?
422.Select the correct statement related to Unit Testing tool public String getStudentName(Student student){
It is a system functionality and regression testing tool return student.getName();
It is a system level control flow testing tool }
It is a unit level black-box and white-box testing tool Test case can't be written since it has user defined object
It is a system level black-box and white-box testing tool It can be tested using Object Repository and Data Driven
Testing
423.What is Function coverage in Unit Testing ? Test case can be written with normal assertEquals()
Checks whether each function (or subroutine) in the TestCase can be written with assertNull()
program has been called
Checks whether each function (or subroutine) in the 430.How to ensure condition coverage for below method ?
program has been returning values public static divide ( int a, int b){
Checks whether each function (or subroutine) in the if(b<=0)
program has been returned correct data type value -------- some statement--------------
Checks whether each function (or subroutine) in the else()
program returns null value --------some statement---------------
}
424.What is Statement coverage in Unit Testing? It should be tested with <= 0 values for a and any values for b.
Has each node in the program been executed It should be tested with <= 0 values for b and any values for a.
Checks whether each function (or subroutine) in the It should be tested with any values only for b.
program has been called It can be tested with any values for a and b.
checks whether the requirements of each branch of each
control structure has been met as well as not met 431.assertTrue(boolean)
checks whether each boolean sub-expression has evaluated asserts that a given condition is true
both to true and false asserts that a given condition is null
asserts that a given condition is false
425.What is Decision coverage in Unit Testing? asserts that an object is null
checks whether the requirements of each branch of each
control structure has been met as well as not met 432.assertNull(Object)
Has each node in the program been executed asserts that an object is null
Checks whether each function (or subroutine) in the asserts that a given condition is true
program has been called asserts that two objects references the same object
checks whether each boolean sub-expression has evaluated Asserts that a condition is false
both to true and false
433.assertSame(Object, Object)
426.What is Condition coverage in Unit Testing? asserts that two objects references the same object
checks whether each boolean sub-expression has evaluated asserts that an object is null
both to true and false asserts that a given condition is true
Checks whether each function (or subroutine) in the Asserts that a condition is false
program has been called
Has each node in the program been executed 434.assertFalse(boolean condition)
checks whether the requirements of each branch of each Asserts that a condition is false
control structure has been met as well as not met asserts that two objects references the same object
asserts that an object is null
427.What is the default unit testing framework available in asserts that a given condition is true
42