0% found this document useful (0 votes)
13 views53 pages

Abstract Classes and Interfaces Quiz

The document discusses various concepts related to abstract classes and interfaces in Java, including method signatures, accessibility modifiers, and the behavior of abstract methods. It poses multiple-choice questions regarding valid declarations, inheritance, and expected behaviors when compiling code snippets. The content serves as a study guide or quiz for understanding Java's object-oriented programming principles.

Uploaded by

Pavan Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views53 pages

Abstract Classes and Interfaces Quiz

The document discusses various concepts related to abstract classes and interfaces in Java, including method signatures, accessibility modifiers, and the behavior of abstract methods. It poses multiple-choice questions regarding valid declarations, inheritance, and expected behaviors when compiling code snippets. The content serves as a study guide or quiz for understanding Java's object-oriented programming principles.

Uploaded by

Pavan Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Topic: Abstract Classes, Interfaces c)The class definition must include the words

[Link] is a valid method signature in an interface? implements Threads and contain a method called
a)private int getArea(); run().
b)protected float getVol(float x); d)The mandatory method must be public, with a
c) public static void main(String [] args); return type of void, must be called run(), and cannot
d)boolean setFlag(Boolean [] test []); take any arguments.

[Link] statement is true about interfaces? [Link] is a valid declaration within an interface?
a)Interfaces allow multiple implementation a)protected short stop = 23;
inheritance. b)final void madness(short stop);
b)Interfaces can extend any number of other c)public Boolean madness(long bow);
interfaces. d)static char madness(double duty);
c) Members of an interface are never static.
d)Members of an interface can always be declared [Link] an abstract class define both abstract methods
static. and non-abstract methods ?
a)No-it must have all one or the other.
[Link] statement is true about interfaces? b) No-it must have all abstract methods.
a)The keyword extends is used to specify that an c)Yes-but the child classes do not inherit the abstract
interface inherits from another interface. methods.
b) The keyword extends is used to specify that a class d)Yes-the child classes inherit both.
inherits from an interface. [Link] one of the following statements is true ?
c) The keyword implements is used to specify that an a) An abstract class can be instantiated.
interface inherits from another interface. b)An abstract class is implicitly final.
d)The keyword implements is used to specify that a c)An abstract class can declare non-abstract methods.
class inherits from another class. d)An abstract class can not extend a concrete class.

[Link] of the field declaration is legal within the [Link] is an abstract method?
body of an interface? a)An abstract method is any method in an abstract
a) protected static int answer = 42; class.
b)volatile static int answer = 42; b)An abstract method is a method which cannot be
c)int answer = 42; inherited.
d)private final static int answer = 42; c)An abstract method is one without a body that is
declared with the reserved word abstract.D)An
[Link] declaration prevents creating a subclass of a abstract method is a method in the child class that
top level class?
overrides a parent method.
a) private class Javacg{}
b)abstract public class Javacg{} [Link] is an abstract class?
c)final public class Javacg{} a)An abstract class is one without any child classes.
d)final abstract class Javacg{} b)An abstract class is any parent class with more than
one child class.
[Link] is an abstract method defined in the parent: c)An abstract class is a class which cannot be
public abstract int sumUp ( int[] arr ); instantiated.
Which of the following is required in a non-abstract d)An abstract class is another name for "base class."
child?
a)public abstract int sumUp ( int[] arr ) { . . . } [Link] declaration in the below code represents a
b)public int sumUp ( int[] arr ) { . . . } valid declaration within the interface ?
c)public double sumUp ( int[] arr ) { . . . } 1. public interface TestInterface {
d)public int sumUp ( long[] arr ) { . . . } 2. volatile long value=98L;
3. transient long amount=67L;
[Link] statement is true for any concrete class 4. Long calculate(long input);
implementing the [Link] interface? 5. static Integer getValue();
a)The class must contain an empty protected void 6. }
method named run(). a)Declaration at line 2.
b)The class must contain a public void method named b)Declaration at line 3.
runnable().
1
c)Declaration at line 4. 1. interface I1 {
d)Declaration at line 5. 2. int process();
3. }
[Link]: 4. class C implements I1 {
1. public interface Constants { 5. int process() {
2. static final int SEASON_SUMMER=1; 6. [Link]("process of C invoked");
3. final int SEASON_SPRING=2; 7. return 1;
4. static int SEASON_AUTUMN=3; 8. }
5. public static const int SEASON_WINTER=4; 9. void display() {
6. } 10. [Link]("display of C invoked");
What is the expected behaviour on compiling the 11. }
above code? 12.}
a)Compilation error occurs at line 2. [Link] class TestC {
b)Compilation error occurs at line 3. 14. public static void main(String... args) {
c)Compilation error occurs at line 4. 15. C c = new C();
d)Compilation error occurs at line 5. 16. [Link]();
17. }
[Link] the following, 18.}
1. abstract class A { What is the expected behaviour?
2. abstract short m1() ; a)Compilation error at line 5.
3. short m2() { return (short) 420; } b)Compilation error at line 9.
4. } c) Runtime error occurs.
5. d)Prints "process of C invoked".
6. abstract class B extends A {
7. // missing code ? [Link]:
8. short m1() { return (short) 42; } 1. public interface Alpha {
9. } 2. String MESSAGE = "Welcome";
Which of the following statements is true? 3. public void display();
a) Class B must either make an abstract declaration of 4. }
method m2() or implement method m2() to allow the To create an interface called Beta that has Alpha as its
code to compile. parent, which interface declaration is correct?
b) It is legal, but not required, for class B to either a)public interface Beta extends Alpha { }
make an abstract declaration of method m2() or b)public interface Beta implements Alpha {}
implement method m2() for the code to compile. c)public interface Beta instanceOf Alpha {}
c) As long as line 8 exists, class A must declare method d)public interface Beta parent Alpha { }
m1() in some way.
d) If class A was not abstract and method m1() on line [Link]:
2 was implemented, the code would not compile. 1. abstract class AbstractClass {
2. void setup() { }
[Link] the following, 3. abstract int execute();
1. interface Base { 4. }
2. boolean m1 (); 5. class EC extends AbstractClass {
3. byte m2(short s); 6. int execute() {
4. } 7. [Link]("execute of EC invoked");
Which of the following code fragment will compile? 8. return 0;
a)interface Base2 implements Base {} 9. }
b) abstract class Class2 extends Base { 10.}
public boolean m1() { return true; } } [Link] class TestEC {
c) abstract class Class2 implements Base { 12. public static void main(String... args) {
public boolean m1() { return (7 > 4); } } 13. EC ec = new EC();
d) class Class2 implements Base { 14. [Link]();
boolean m1() { return false; } 15. [Link]();
byte m2(short s) { return 42; } } 16. }
17.}
[Link]: What is the expected behaviour?
2
a)Compilation error at line 2. c)1 2 3 4
b)Compilation error at line 14. d)Compilation fails
c)Runtime error occurs.
d)Prints "execute of EC invoked". [Link] the following,
1. interface DoMath {
[Link] the code below: 2. double getArea(int rad); }
interface MyInterface { 3.
void doSomething ( ) ; 4. interface MathPlus {
} 5. double getVol(int b, int h); }
class MyClass implements MyInterface { 6.
// xx
}
7.
Choose the valid option that can be substituted in 8.
place of xx in the MyClass class . Which code fragment inserted at lines 7 and 8 will
a)public native void doSomething ( ) ; compile?
b) void doSomething ( ) { /* valid code fragments */ } a) class AllMath extends DoMath {
c)private void doSomething ( ) { /* valid code double getArea(int r); }
fragments */ } b)interface AllMath implements MathPlus {
d)protected void doSomething ( ) { /* valid code double getVol(int x, int y); }
fragments */ } c)interface AllMath extends DoMath {
float getAvg(int h, int l); }
[Link] I1 { d)class AllMath implements MathPlus {
void draw(); double getArea(int rad); }
}
class C implements I1 { [Link] I1 {}
xxxxxx interface I2 {}
} class Base implements I1 {}
Which of the following when inserted at xxxxxx is a class Sub extends Base implements I2 {}
legal definition and implementation ? class Red {
a)void draw() { } public static void main(String args[]) {
b)public void draw() { } Sub s1 = new Sub();I2 i2 = s1; // 1
c)protected void draw() { } I1 i1 = s1; // 2
d)abstract void draw() { } Base base = s1; // 3
Sub s2 = (Sub)base; // 4
[Link] the following,
1. interface Count { }
2. short counter = 0; }
3. void countUp(); A compile-time error is generated at which line?
4. } a) 2
5. public class TestCount implements Count { b) 3
6. c) 4
7. public static void main(String [] args) { d) No error will be generated.
8. TestCount t = new TestCount();
9. [Link](); [Link]:
10. } 1. public interface IDrawable {
11. public void countUp() { 2. static final int SHAPE_CIRCLE=1;
12. for (int x = 6; x>counter; x--, ++counter) { 3. final int SHAPE_SQUARE=2;
13. [Link](" " + counter); 4. static int SHAPE_RECTANGLE=3;
14. } 5. public static const int SHAPE_TRIANGLE=4;
15. } 6. }
16. } What is the expected behaviour on compiling the
What is the result? above code?
a)1 2 3 a) Compilation error occurs at line 2.
b)0 1 2 3 b) Compilation error occurs at line 3.
3
c) Compilation error occurs at line 4. [Link] of the following member level (i.e.
d) Compilation error occurs at line 5. nonlocal) variable declarations will not compile?
a) transient int b = 3;
[Link]: b) public static final int c;
1. abstract class MyClass { c) volatile int d;
2. void init() { } d) private synchronized int e;
3. abstract int calculate();
4. } [Link] of the following modifiers can be applied
5. class MyImpl extends MyClass { to the declaration of a field?
6. int calculate() { a) abstract
7. [Link]("Invoking calculate..."); b) volatile
8. return 1; c) native
9. } d) synchronized
10.}
[Link] class TestMyImpl { [Link] statement is true about the use of
12. public static void main(String[] args) { modifiers?
13. MyImpl mi = new MyImpl(); a) If no accessibility modifier (public, protected, and
14. [Link](); private) is specified for a member declaration, the
15. [Link](); member is only accessible for classes in the same
16. } package and subclasses of its class in any package.
17.} b) You cannot specify accessibility of local variables.
What is the expected behaviour? They are only accessible within the block in which
a) Prints "Invoking calculate...". they are declared.
c) Subclasses of a class must reside in the same
package as the class they extend.
b) Runtime error occurs. d) Local variables can be declared static.
c) Compilation error at line 2.
d) Compilation error at line 14. [Link] is the most restrictive access modifier that
will allow members of one class to have access to
members of another class in the same package?
Topic: Access Modifiers a) abstract
b) protected
[Link] one of the following modifiers can be c) synchronized
applied to a method? d) default access
a) transient
b) native [Link] statement is true?
c) volatile a) Constructors can be declared abstract.
d) friend b) A subclass of a class with an abstract method must
provide an implementation for the abstract method.
[Link] a method in a class, what access modifier c) Transient fields will be saved during serialization.
do you use to restrict access to that method to only d) Instance methods of a class can access its static
the other members of the same class? members implicitly.
a) static
b) private [Link] statement is true?
c) protected
d) volatile a) A static method can call other non-static methods
in the same class by using the this keyword.
[Link] of the following modifiers can be applied b) A class may contain both static and non-static
to a constructor? variables and both static and non-static methods.
a) protected c) Each object of a class has its own instance of each
b) static static variable.
c) synchronized d) Instance methods may access local variables of
d) transient static methods.

4
[Link] of the following modifiers cannot be a) final
applied to a top level class? b) transient
a) public c) volatile
b) private d) synchronized
c) abstract
d) final [Link] restrictive is the default accessibility
compared to public, protected, and private
[Link] of the following modifiers cannot be accessibility?
applied to a method? a) Less restrictive than public.
a) final b) More restrictive than public, but less restrictive
b) synchronized than protected.
c) transient c)More restrictive than protected, but less restrictive
d) native than private.
d)More restrictive than private.
[Link] of the following modifiers can be applied [Link] is printed out following the execution of the
to a constructor? code below ?
a)private 1. class Test {
b) abstract final volatile 2. static String s;
3. public static void main(String []args) {
[Link] statement is true about modifiers? 4. int x = 4;
a) Fields can be declared native. 5. if (x < 4)
b) Non-abstract methods can be declared in abstract 6. [Link]("Val = " + x);
classes. 7. else
c) Classes can be declared native. 8. [Link](s);
d) Abstract classes can be declared final. 9. }
10. }
[Link] which of the following can the keyword a) Nothing. The code fails to compile because the
"synchronized" be placed, without causing a compile String s isn’t declared correctly.
error. b) The text "Val = null" is displayed.
a) class variables c) The text "null" is displayed.
b) instance methods d) Runtime error due to NullPointer exception.
c) instance variables
d) a class [Link] the following 2 classes and select the
correct statement.
41.A protected method can be overridden by class A {
a) A private method private int x = 0;
b) A method without any access specifiers (i.e. static int y = 1;
default) protected int q = 2;
c) A protected method }
d) All of the above class B extends A {
void method() {
[Link] statement is true about accessibility of [Link](x);
members? [Link](y);
a) Private members are always accessible from within [Link](q);
the same package. }
b)Private members can only be accessed by code from }
within the class of the member. a) The code fails to compile because the variable x is
c) A member with default accessibility can be not available to class B.
accessed by any subclass of the class in which it is b) The code compiles correctly, and the following is
defined. displayed:012
d) Package/default accessibility for a member can be c) The code fails to compile because you can’t
declared using the keyword default. subclass a class with protected variables.
d) The code fails to compile because you can’t
[Link] of the following modifiers cannot be subclass a class with static variables.
applied to the declaration of a field?
5
[Link] the following class, which of these is valid }
way of referring to the class from outside of the public static void main(String [] args) {
package [Link]?
package [Link]; int k = [Link](5,10);
public class MyClass { [Link](k);
// ... }
} }
a) By simply referring to the class as MyClass. What is the result?
b) By simply referring to the class as [Link]. a) 70
c) By simply referring to the class as [Link]. b) 52
d) By importing with com.* and referring to the class c) Compilation error
as [Link]. d) An exception is thrown at runtime

[Link] the following member declarations, which [Link] the following,


statement is true? 1. package testpkg.p1;
int a; // (1) 2. public class ParentUtil {
static int a; // (2) 3. public int x = 420;
int f() { return a; } // (3) 4. protected int doStuff() { return x; }
static int f() { return a; } // (4) 5. }
Declarations (1) and (3) cannot occur in the same class 1. package testpkg.p2;
definition. 2. import [Link];
Declarations (2) and (4) cannot occur in the same class 3. public class ChildUtil extends ParentUtil {
definition. 4. public static void main(String [] args) {
Declarations (1) and (4) cannot occur in the same class 5. new ChildUtil().callStuff();
definition. 6. }
7. void callStuff() {
Declarations (2) and (3) cannot occur in the same class 8. [Link]("this " + [Link]() );
definition. 9. ParentUtil p = new ParentUtil();
10. [Link](" parent " + [Link]() );
49.// Class A is declared in a file named [Link]. 11. }
package [Link]; 12. }
public class A { Which statement is true?
public void m1() {[Link]("A.m1, ");} a) The code compiles and runs, with output this 420
void m2() {[Link]("A.m2, ");} parent 420.
} b) If line 8 is removed, the code will compile and run.
// Class D is declared in a file named [Link]. c) If line 10 is removed, the code will compile and run.
package [Link]; d) Both lines 8 and 10 must be removed for the code
import [Link].A; to compile.
public class D {
public static void main(String[] args) { [Link] would be the result of attempting to
A a = new A(); compile and run the following program?
a.m1(); // 1 class MyClass {
a.m2(); // 2 static MyClass ref;
}} String[] arguments;
What is the result of attempting to compile and run public static void main(String[] args) {
the program? ref = new MyClass();
a) Prints: A.m1, A.m2, [Link](args);
b) Runtime error occurs. }
c) Compile-time error at 1. public void func(String[] args) {
d) Compile-time error at 2. [Link] = args;
}
[Link] class MyClass { }
int calculate(int i, int j) a) The program will fail to compile, since the static
{ method main() cannot have a call to the non-static
return 2+i*j; method func().
6
b) The program will fail to compile, since the non- a) final void h() {} // (1)
static method func() cannot access the static variable b) MyOtherClass(int n) { m = n; } // (2)
ref. c) void k() { i++; } // (3)
c) The program will fail to compile, since the d) void l() { j++; } // (4)
argument args passed to the static method main()
cannot be passed on to the non-static method func(). [Link] the following code, which statement can be
d) The program will compile and run successfully. placed at the indicated position without causing
compilation errors?
[Link] [Link]; public class ThisUsage {
public class A { int planets;
public void m1() {[Link]("A.m1, ");} static int suns;
protected void m2() {[Link]("A.m2, ");} public void gaze() {
private void m3() {[Link]("A.m3, ");} int i;
void m4() {[Link]("A.m4, ");} // ... insert statements here ...
} }
class B { }
public static void main(String[] args) { a) this = new ThisUsage();
A a = new A(); b) this.i = 4;
a.m1(); // 1 c) [Link] = i;
a.m2(); // 2 d) i = [Link];
a.m3(); // 3
a.m4(); // 4 [Link] the following:
}} class Gamma {
Assume that the code appears in a single file named public int display() {
[Link]. return 3;
What is the result of attempting to compile and run }
the program? }
public class Delta extends Gamma {
a) Prints: A.m1, A.m2, A.m3, A.m4, @Override
b) Compile-time error at 2. protected int display() {
c) Compile-time error at 3. return 4;
d) Compile-time error at 4. }
}
[Link] the following source code, which comment What will be the result of compiling the above code ?
line can be uncommented without introducing a) The code compiles correctly without any errors.
errors? b) The code fails to compile, because you can’t
abstract class MyClass { override a method to be more private than its parent.
abstract void f(); c) The code fails to compile, because @Override
final void g() {} cannot be mentioned above a protected method.
// final void h() {} // (1) d) The code fails to compile, because public methods
protected static int i; cannot be overriden.
private int j;
} [Link] the following:
final class MyOtherClass extends MyClass { class TestAccess {
// MyOtherClass(int n) { m = n; } // (2) public int calculate() {
public static void main(String[] args) { int a=5,b=6;
MyClass mc = new MyOtherClass(); return a+b;
} }
void f() {} }
void h() {} public class MyChild extends TestAccess {
// void k() { i++; } // (3) @Override
// void l() { j++; } // (4) int calculate() {
int m; return 100;
} }
}
7
What will be the result of compiling the above code ? [Link] would you declare and initialize the array to
a) The code fails to compile, because you can’t declare an array of fruits ?
override a method to be more private than its parent. a) String[] arrayOfFruits = {"apple", "mango",
b) The code fails to compile, because @Override "orange"};
cannot be mentioned above a default method. b) String[] arrayOfFruits= ("apple", "mango",
c) The code fails to compile, because public methods "orange");
cannot be overriden. c) String[] arrayOfFruits= ["apple", "mango",
d) The code compiles correctly without any errors. "orange"];
d) String[] arrayOfFruits = new String{"apple, mango,
Topic: Arrays orange"};

[Link] is the value of [Link] for the [Link] type parameter must the following method
following array? be called with?
String[] seasons = {"winter", "spring", "summer", int myMethod ( double[] ar )
"fall", }; {
undefined ....
a) 4 }
b) 5 a) An empty double array.
c) 22 b) A reference to an array that contains elements of
type double.
[Link] of the following will declare an array and c) A reference to an array that contains zero or more
initialize it ? elements of type int.
a) Array a = new Array(5); d) An array of any length that contains double and
b) int array[] = new int [5]; must be named ar
c) int a[] = new int(5); .
d)int [5] array; [Link] the declaration:
char[] c = new char[100];
[Link] of the following is an illegal declaration of What is the value of c[50]?
array ? a) 49
a) int [] myscore[]; b) 50
b) char [] mychars; c) ‘\u0020’
c) Dog mydogs[7]; d) ‘\u0000’
d) Dog mydogs[];
[Link] will legally declare, construct, and initialize
[Link] will legally declare, construct, and initialize an array?
an array? a) int [] myList = {"9", "6", "3"};
a) int [] myList = {"5", "8", "2"}; b) int [3] myList = (9, 6, 3);
b) int [3] myList = (5, 8, 2); c) int myList[] [] = {9,6,3,0};
c) int myList[] [] = {5,8,2,0}; d) int [] myList = {9, 6, 3};
d) int [] myList = {5, 8, 2}; [Link] the following code snippet:
float average[] = new float[6];
[Link] of these array declaration statements is Assuming the above declaration is a local variable in a
not legal? method of a class, after the above statement is
a) int[] i[] = { { 1, 2 }, { 1 }, {}, { 1, 2, 3 } }; executed, which of the following statement is false ?
b) int i[][] = new int[][] { {1, 2, 3}, {4, 5, 6} }; a) [Link] is 6
c) int i[4] = { 1, 2, 3, 4 }; b) average[0] is 0.0
d) int i[][] = { { 1, 2 }, new int[ 2 ] }; c) average[5] is undefined
d) average[6] is undefined
[Link] of the following is a legal declaration of a
two-dimensional array of integers? Topic: Assignments, Expressions, Operators
a) int[5][5]a = new int[][];
b) int a = new int[5,5]; [Link] one of the below expression is equivalent
c) int[]a[] = new int[5][]; to 16>>2 ?
d) int[][]a = new int[][5]; a) 16/4
b) 16/2
8
c) 16*2 c) x >>> 1;
d) 16/2^2 d) x << -1;

[Link] of the following is correct? [Link] you have four int variables: x, y, z, and
a) 8 >> 2 gives 2 result.
b) 16 >>> 2 gives 2 Which expression sets the value of z to x if result has a
c) 4 << 2 gives 2 value of 1, and the value of y to x otherwise?
d) 2 << 1 gives 2 a) x = (result == 1) ? z : y;
b) x = (result == 1) ? y : z;
[Link] of the following is correct? c) x = (result == 1) : y ? z;
128>>> 1 gives d) x = (result == 1) : z ? y;
a) 32
b)64 [Link] a variable x of type int ( which can contain
c) -64 a negative value), which of these expressions always
d) -32 gives a positive number irrespective of the value of
x?
[Link] is the value of -32 % 6 ? a) x << 1;
a) 5 b) x >> 1;
b) -5 c) x >>> 1;
c) 2 d) x << 2;
d) -2
[Link]:
[Link] one of the following is a short-circuit int x = 7;
operator ? x <<= 2;
a)| What best describes the second line of code?
b) && a) It assigns the value of 2 to x, and shifts it to left by
c) & one place.
d) ^ b) It assigns the value to x after shifting x to 2 places
left.
[Link] the following code snippet: c) It assigns the value to x after shifting 2 to x places
double sum = 10.0, price=100; left.
sum += price>=100 ? price*1.1 : price; d) It is invalid because there is no such operator as
What value is placed in sum? Choose the most <<=.
appropriate answer.
a) 90 [Link] the variables defined below:
b) 100 int one = 1;
c) 110 int two = 2;
d) 120 char initial = ‘2’;
boolean flag = true;
[Link] x, y, and z are all integers, which expression will Which one of the following is invalid?
produce a runtime error? a) if( one == two ){}
NOTE: The expressions are always evaluated with all b) switch( one ){}
the integers having a value of 1. c) switch( flag ){}
a) z = x/y--; d) switch( initial ){}
b) z = -x/x;
c) z = y/x--; [Link] the shift operator that returns -1 as the
d) z = y%--x value of the variable in the following statement:
int a= -4 MISSING OPERATOR 2;
[Link] a variable x of type int ( which contains a a) >>>
positive value), which is the correct way of doubling b) >>
the value of x, barring any wrapping of out-of-range c) <<<
intermediate values ? d) <<

a) x << 1; [Link] class TestOperator {


b) x >> 1; public static void main(String[] args) {
9
byte x = 0x0F; 3. float f1 = 2.0f;
byte y = 0x08; 4. double d1 = 4.0;
byte z = x & y;logical operations returns int 5. double result = f1 * d1;
[Link](z); 6. [Link](result);
} 7. }
} 8. }
What is the result? What is the output ?
a) 8 a) 8.0
b) 15 b) Compilation error at Line 3
c) 23 c) Compilation error at Line 4
d) Compilation error d) Compilation error at Line 5

[Link] class TestExpression { [Link] class Test {


private static int value=0; public static void main(String[] args)
private static boolean method2(int k) { {
value+=k; [Link]( 6 ^ 4);
return true; }
} }What is the output?
public static void method1(int index) { a) 1296
boolean b; b) 24
b = index >= 15 && method2(30); c) 2
b = index >= 15 & method2(15); d) Compilation error
}
public static void main ( String args[]) { [Link] will happen if you try to compile and run the
method1(0); following code?
[Link](value); int a = 200;
} byte b = a;
} [Link] ("The value of b is " + b );
What is the output? a) It will compile and print The value of b is 200
a) 0 b) It will compile but cause an error at runtime
b) 15 c) Compile-time error
c) 30 d) It will compile and print The value of b is -56
d) 45
88..Given:
[Link] class TestCondition { public class TestOperator {
public static void main (String... args) { int x=15;
int i=1; public void method(int x) {
int j=2; x+=x;
int k=2; [Link](x);
if ((i ^ j) && (j ^ k)) { }
[Link]("true"); public static void main(String... args) {
} TestOperator t = new TestOperator();
else { [Link](10);
[Link]("false"); }
} }
} What is the output of the above code?
} a) 10
What is the expected output ? b)20
a) Prints true c) 25
b) Prints false d) 30
c)Compilation error occurs
d) Runtime error occurs 89.1. public class TestLiterals {
2. public static void main(String[] args) {
85.1. public class TestFloatDouble { 3. float f1 = 2.0;
2. public static void main(String[] args) { 4. float f2 = 4.0f;
10
5. float result = f1 * f2; c) 20
6. [Link](result); d) 30
7. }
8. } [Link]:
What is the output? 1. public class B {
a) A value which is exactly 8.0 2. Integer x;not initialized
b)Compilation error at Line 3 3. int sum;
c)Compilation error at Line 4 4. public B(int y) {
d) Compilation error at Line 5 5. sum=x+y;
6. [Link](sum);
[Link] class TestChar { 7. }
static double a; static float b; static int c; static char 8. public static void main(String[] args) {
d; 9. new B(new Integer(23));
public static void main(String[] args) { 10. }
a = b = c = d = ‘a’; 11. }
[Link](a+b+c+d == 4 * ‘a’); What is the expected output ?
} a) The value "23" is printed at the command line.
} b) Compilation fails because of an error in line 9.
What is the output? c) A NullPointerException occurs at runtime.
a) true d) A NumberFormatException occurs at runtime.
b) false
c) Compile-time error [Link] class TestOperator {
d) Run-time error public static void main(String[] args) {
int x = 0x04;
[Link] class TestOperator { int y = 0x20;
public static void main (String[] args) { int z = x && y;
int x = 2, y = 4; [Link](z);
[Link]("%d,%d", (x ^ y), (y ^ x)); }
} }
} What is the result?
What is the expected output ? a) 0
a) 8,8 b) 24
b) 6,8 c) 36
c) 6,6 d) Compilation error
d) 8,6
[Link] class TestOperation {
[Link] class Test { public static void main (String... args) {
private static int value =0; int a = 4;
private static boolean method2(int k) { int b = 3;
value+=k; a += (--b + a * 3);
return true; [Link]("a=%d,b=%d",a,b);
} }
public static void method1(int index) { }
boolean b; What is the value of a after this code is run?
b = index < 10 | method2(10); a) a=19,b=3
b = index < 10 || method2(20); b) a=18,b=2
} c) a=19,b=1
public static void main ( String args[]) { d) a=18,b=3
method1(0);
[Link](value); [Link] class TestIncrement {
} public static void main(String[] args)
} {
What is the output? int index=10;
a) 0
b)10 int result=0;
11
if (index++ > 10) [Link] class Test{
{ public static void main(String[] args) {
result = index; [Link]((-1 & 0x1f) + "," + (8 << -1));
} }
[Link]("index=" + index); }
[Link]("result=" + result); What is the result of attempting to compile and run
} the program?
What is the output? a) 0,0
a) index=10 b) 0x1f,8
result=0 c) 31,16
b) index=11 d) 31,0
result=0
c) index=10 [Link] is the value of x after this code is run?
result=10 int x = 3 ;
d) index=11 int y = 2 ;
result=11 x += (y + x * 2);
a) 9
[Link]: b) 10
if( val > 4 ) c) 11
{ [Link]( "Test A" ); Topic: Class / Method Concepts
}
else if( val > 9 ) [Link] of the following is illegal for a method
{ [Link]( "Test B" ); declaration?
} a) protected abstract void m1();
else [Link]( "Test C" ); b) static final void m2(){}
Which values of val will result in "Test C" NOT being c) transient private native void m3() {}
printed? d) synchronized public final void m4() {}
a) val < 0
b) val = 0 [Link] one of these statements is true about
c) 0 < val < 4 constructors?
d) 4 < val < 9 a) Constructors must not have arguments if the
superclass b)constructor does not have arguments.
[Link] class TestIncrement { c) Constructors are inherited.
public static void main(String[] args) d)Constructors cannot be overloaded.
{ e)The first statement of every constructor is a legal
int index=10; call to the super() or this()method.
int result=0;
if (++index > 10) [Link] is a method definition:
{ int compute( int a, double y ){ . . . .}
result = index; Which of the following has a different signature?
} a) int compute( int sum, double value ){ . . . .}
[Link]("index=" + index); b) double compute( int a, double y ){ . . . .}
[Link]("result=" + result); c) double compute( int sum, double y ){ . . . .}
} d) int compute( int a, int y ){ . . . .}
}
What is the output? [Link] one of the following is not a legal method
a) index=10 declaration?
result=0 a) static final void m2(){}
b) index=11 b) transient private native void m3() {}
result=0 c) synchronized public final void m4() {}
c) index=11 d) private native void m5();
result=10
d) index=11 [Link] a constructor, where can you place a call to the
result=11 super class constructor?
a) The first statement in the constructor
12
b) The last statement in the constructor
c) You can’t call super in a constructor [Link] one of the following is not a legal
d) Any where declaration for top level classes or interfaces ?
a) public abstract interface Test {}
[Link] one of the below statements is true? b) final abstract class Test {}
a) When a class has defined constructors with c) abstract interface Test {}
parameters, the compiler does not create a default d) public abstract class Test {}
no-args constructor.
b) When a constructor is provided in a class, a 112.A constructor is used to
corresponding destructor should also be provided. a) Free memory
c)The compiler always creates the default no-args b) Initialize a newly created object.
constructor for every class. c) Import packages
d) The no-args constructor can invoke only the no- d) Clean up the object
args constructor of the superclass. It cannot invoke
any other constructor of the superclass. [Link] class Constructor {
public Constructor (int x, int y, int z)
[Link] of the following techniques can be used to {}
prevent the instantiation of a class by any code }
outside of the class? Which of the following is considered as overloaded
a) Do not declare any constructors. constructor?
b) Do not use a return statement in the constructor. a) Constructor() {}
c) Declare all constructors using the keyword void to b) protected int Constructor(){}
indicate that nothing is returned. c) private Object Constructor() {}
d) Declare all constructors using the private access d) public void Constructor(int x, int y, byte z){}
modifier.
[Link] [Link] were compiled as an application
[Link] one of the following is legal declaration for and then run from the command line as
nonnested classes and interfaces? java MyProg I like myprogram
a) final abstract class Test {} What would be the value of args[1] inside the main( )
method?
b) public static interface Test {} a) MyProg
c) final public class Test {} b) I
d) protected interface Test {} c) like
d) 4
[Link] is a method’s signature?
a)The signature of a method is the name of the [Link] the following,
method and the type of its return value. 1. long test( int x, float y) {
b) The signature of a method is the name of the 2.
method and the names of its parameters. 3. }
c) The signature of a method is the name of the Which one of the following line inserted at line 2
method and the data types of its parameters. would not compile?
d) The signature of a method is the name of the a) return (long) y;
method, its parameter list, and its return type. b) return (int) 3.14d;
c)return ( y / x );
[Link] class MethodTest { d)return x / 7;
public void methodSam( int a, float b, byte c) {}
} [Link] one of the following is generally a valid
Which of the following is considered as overloaded definition of an application’s main() method ?
methodSam ? a) public static void main();
a) private int methodSam( int a, float b, byte c) {} b) public static void main( String args );
b) private int methodSam( float a, int b, byte c) c) public static void main( String[] args );
{return b;} d) public static void main( Graphics g );
c) private float methodSam( int a, float b, byte c) [Link] the following code segment and select
{return b;} the correct statement:
d) public void methodSam( int x, float y, byte z) {} 1. class Test {
13
2. final int tst; What value is placed in bValue?
3. final int w = 0; a) true
4.
5. Test() {
6. tst = 1; b) false
7. } c)"Hot Java"
8. d) null
9. Test(int x) {
10. tst = x; [Link] A {
11. } A() { }
12. } void display() {
a) The code fails to compile because a class cannot [Link]("display of A called");
have more than 1 constructor. }
b) The code fails to compile because the class Test has }
no constructors. class B {
c) The code compiles correctly without any warnings B() { }
or errors. void display() {
d) The code fails to compile because an attempt is [Link]("display of B called");
made to initialise a final variable at lines 6 and 10. }
}
[Link] the following, public class C extends A, B {
1. class A { public static void main(String[] args) {
2. public int foo; C c = new C();
3. } [Link]();
4. public class B extends A { }
5. private int bar; }
6. public void setBar(int b) { What is the output ?
7. bar = b; a) Compilation error is generated
8. } b) display of A called
9. } display of B called
Which is true about the classes described above? c) display of B called
a)Class A is tightly encapsulated. display of A called
b) Class B is tightly encapsulated. d)order of output is not predictable and can come in
c) Classes A and B are both tightly encapsulated. any order
d) Neither class A nor class B is tightly encapsulated.
[Link] the following,
[Link] the following, 1. import [Link].*;
1. public class Barbell { 2. public class NewTreeSet2 extends NewTreeSet {
2. public int getWeight() { 3. public static void main(String [] args) {
3. return weight; 4. NewTreeSet2 t = new NewTreeSet2();
4. } 5. [Link]();
5. public void setWeight(int w) { 6. }
6. weight = w; 7. }
7. } 8. protected class NewTreeSet {
8. public int weight; 9. void count() {
9. } 10. for (int x = 0; x < 7; x++,x++ ) {
Which is true about the class described above? 11. [Link](" " + x);
a) Class Barbell is tightly encapsulated. 12. }
b) Line 2 is in conflict with encapsulation. 13. }
c) Line 5 is in conflict with encapsulation. 14. }
d) Line 8 is in conflict with encapsulation. What is the result?
a) 0 2 4
[Link] the following code: b) 0 2 4 6
String str = "Hot Java"; c) Compilation fails at line 4
boolean bValue = str instanceof String; d) Compilation fails at line 8
14
}
[Link]: public static void main(String[] args)
1. class Fruit { {
2. private String name; TestConstructor tc = new TestConstructor();
3. public Fruit(String name) { [Link] = name; } }
4. public String getName() { return name; } }
5. } What will be the output?
6. public class MyFruit extends Fruit { a) No output
7. public void displayFruit() { } b) i=10 j=11
9. } c)Compilation error
Which of the following statement is true? d) Runtime error
a) The code will compile if public MyFruit() { Fruit(); }
is added to the MyFruit class. [Link] the following,
b) The code will compile if public Fruit() { MyFruit(); } 1. import [Link].*;
is added to the Fruit class. 2. class Ro {
c) The code will compile if public Fruit() { this("apple"); 3. Object[] testObject() {
} is added to the Fruit class. 4.
d) The code will compile if public Fruit() 5.
{ Fruit("apple"); } is added to the Fruit class. 6. }
7. }
[Link] the following, Which one of the following code fragments inserted
1. at lines 4, 5 will not compile?
2. public class NewTreeSet extends [Link]{ a) return null;
3. public static void main(String [] args) { b) Object t = new Object();
4. [Link] t = new [Link](); return t;
c) Object[] t = new Object[10];
5. [Link](); return t;
6. } d) Object[] t = new Integer[10];
7. public void clear() { return t;
8. TreeMap m = new TreeMap();
9. [Link](); [Link] the following,
10. } 1. public class ThreeConst {
11. } 2. public static void main(String [] args) {
Which statement added at line 1, allow the code to 3. new ThreeConst();
compile? 4. }
a) No statement is required 5. public void ThreeConst(int x) {
b) import [Link].*; 6. [Link](" " + (x * 2));
c) [Link]*; 7. }
d) import [Link].*Map; 8. public void ThreeConst(long x) {
9. [Link](" " + x);
[Link] the following, 10. }
public class TestConstructor extends Object 11.
{ 12. public void ThreeConst() {
TestConstructor() 13. [Link]("no-arg ");
{ 14. }
super(); 15. }
this(10); What is the result?
} a) 8 4 no-arg
TestConstructor(int i) b) no-arg 8 4
{ c) Compilation fails.
this(i, 11); d) No output is produced.
}
TestConstructor(int i, int j) [Link] the following,
{ 1. class Dog {
[Link]("i=" + i + " j=" + j); 2. Dog(String name) { }
15
3. } 27. }
If class Beagle extends Dog, and class Beagle has only What is the result?
one constructor, which of the following could be the a) Bar Bar Bar Bar
legal constructor for class Beagle? b)Foo Bar Foo Bar
a) Beagle() { } c) Foo Foo Foo Foo
b) Beagle() { super(); } d) Compilation fails.
c)Beagle() { super("fido"); }
d) No constructor, allow the default constructor to get [Link] the following piece of code:
generated automatically. class A {
int x = 0;
[Link] the following, A(int w) {
1. public class CheckType { x = w;
2. int check() { }
3. }
4. return y; class B extends A {
5. } int x = 0;
6. public static void main(String [] args) { B(int w) {
7. CheckType c = new CheckType(); x = w + 1;
8. int x = [Link](); }
9. } }
10.} a) The code compiles correctly.
Which line of code, inserted independently at line 3, b) The code fails to compile, because both class A and
will not compile? B do not have valid constructors.
a) short y = 7; c) The code fails to compile because there is no
b) int y = (int) 7.2d; default no-args constructor for class A.
c) Long y = 7; d) The code fails to compile because there is no
d) int y = 0xface; default no-args constructor for class B.

[Link] the following, [Link] the following,


class TestFooBar { 1. class Base {
public static Foo f = new Foo(); 2. Base() {
public static Foo f2; 3. [Link]("Base constructor
public static Bar b = new Bar(); invoked...");
5. 4. }
public static void main(String [] args) { 5. }
for (int x=0; x<4; x++) { 6.
f2 = getFoo(x); 7. public class Derived extends Base {
[Link](); 8. Derived() {
} 9. [Link]("Derived constructor
} invoked...");
static Foo getFoo(int y) { 10. }
if ( 0 == y % 2 ) { 11.
return f; 12. public static void main (String[] args) {
} else { 13. Base b = new Derived();
return b; 14. }
} 15.}
} What is the output ?
} a)Base constructor invoked...
20. Derived constructor invoked...
21. class Bar extends Foo { b) Base constructor invoked...
22. void react() { [Link]("Bar "); } c) Derived constructor invoked...
23. } d) Derived constructor invoked...
24. Base constructor invoked...
25. class Foo {
26. void react() { [Link]("Foo "); } [Link] the following,
16
[Link] class Error and class Exception are children
1. public class ThreeConst { of this parent:
2. public static void main(String [] args) { a)Throwable
3. new ThreeConst(4L); b) Catchable
4. } c) Runnable
5. public ThreeConst(int x) { d) Problem
6. this();
7. [Link](" " + (x * 2)); [Link] type of exception is thrown by parseInt() if
8. } it gets illegal data?
9. public ThreeConst(long x) { a) ArithmeticException
10. this((int) x); b) RunTimeException
11. [Link](" " + x); c) NumberFormatException
12. } d) NumberError
13.
14. public ThreeConst() { [Link] of the following lists exception types from
15. [Link]("no-arg "); MOST specific to LEAST specific?
16. } a) Error, Exception
17. } b) Exception, RunTimeException
What is the result? c) Throwable, RunTimeException
a) 4 8 d) ArithmeticException, RunTimeException
b) 8 4 no-arg
c) no-arg 8 4 [Link] of these statement is true ?
d) Compilation fails. a) finally block gets executed only when there are
exceptions.
[Link] the following, b) Finally gets always executed irrespective of the flow
1. in try catch block.
2. public class MyHashSet extends [Link]{ c) finally block can be present only when a catch block
3. public static void main(String [] args) { is present.
4. [Link] hs = new [Link](); d) finally block gets executed only when there are no
5. [Link](); exceptions.
6. }
7. public void hmClear() { [Link] occurrence of which of the following is it
8. HashMap hm = new HashMap(); possible for a program to recover?
9. [Link](); a) Errors
10. } b) Exceptions
11. } c) Both errors and exceptions
Which statement added at line 1, allow the code to d) Neither
compile?
a) import [Link].*; [Link] statement is true?
b) import [Link].*Map; a) If an exception is uncaught in a method, the
c) import [Link]*; method will terminate and normal execution will
d) No statement is required resume.
b) An overriding method must declare that it throws
Topic: Exceptions the same exception classes as the method it
overrides.
[Link] statement is TRUE about catch{} blocks? c) The main() method of a program cannot declare
a) There can only be one catch{} block in a try/catch that it throws checked exceptions.
structure. d) A method declaring that it throws a certain
b) The catch{} block for a child exception class must exception class may throw instances of any subclass
PRECEDE that of a parent exception class. of that exception class.
c) The catch{} block for a child exception class must
FOLLOW that of a parent exception class. [Link] A {A() throws Exception {}} // 1
d) A catch{} block need not be present even if there is class B extends A {B() throws Exception {}} // 2
no finally{} block. class C extends A {C() {}} // 3
Which one of the following statements is true?
17
a) Compile-time error at 1. 1. public class MyProgram {
b) Compile-time error at 2. 2. public static void main(String args[]){
c) Compile-time error at 3. 3. try {
d) No compile-time errors. 4. [Link]("Hello world ");
5. }
[Link] is a finally{} block executed? 6. finally {
a) Only when an unhandled exception is thrown in a 7. [Link]("Finally executing ");
try{} block. 8. }
b) Only when any exception is thrown in a try{} block. 9. }
c) Always after execution has left a try catch{} block, 10. }
no matter for what reason What is the result?
d) Always just as a method is about to finish. a) Nothing. The program will not compile because no
exceptions are specified.
[Link] statement is TRUE about the try{} block? b) Nothing. The program will not compile because no
a) It is mandatory for statements in a try{} block to catch clauses are specified.
throw at least one exception type. c) Hello world.
b) The statements in a try{} block can only throw one d) Hello world Finally executing
exception type and not several types.
c) The try{} block can contain loops or branches. [Link] is the result of compiling and executing the
d) The try{} block can appear after the catch{} blocks. below code ?
public class TryTest {
[Link] A { public static void main(String[] args)
public static void main (String[] args) { {
Object error = new Error(); try
Object runtimeException = new {
RuntimeException(); return;
[Link]((error instanceof Exception) + }
","); finally
[Link](runtimeException instanceof {
Exception); [Link]("Finally");
}} }
What is the result of attempting to compile and run }
the program? }
a) Prints: false,false a) Outputs nothing
b) Prints: false,true b) Finally
c) Prints: true,false c) Compilation Error
d) Prints: true,true d) Runtime Error
[Link] is the result of compiling and executing the
below code with the mentioned arguments ? [Link] A {
java TestInvocation Welcome Year 2009 public static void main (String[] args) {
public class TestInvocation Error error = new Error();
{ Exception exception = new Exception();
public static void main(String... args) [Link]((exception instanceof
{ Throwable) + ",");
String arg1 = args[1]; [Link](error instanceof Throwable);
String arg2 = args[2]; }}
String arg3 = args[3]; What is the result of attempting to compile and run
} the program?
} a) Prints: false,false
a) Compilation succeeds b) Prints: false,true
b) Throws exception at runtime c) Prints: true,false
c) Compilation fails d) Prints: true,true
d) None of the above. [Link] class MyClass {
public static void main(String[] args) {
[Link] the following, RuntimeException re = null;
18
throw re; [Link]
} class NewException extends Exception {
} }
What will be the result of attempting to compile and [Link]
run the above program? class Welcome {
a) The code will fail to compile, since the main() public String displayWelcome(String name)
method does not declare that it throws throws NewException {
RuntimeException in its declaration. if(name == null) {
b) The program will compile without error and will throw new NewException();
throw [Link] when run. }
c) The program will compile without error and will return "Welcome "+ name;
throw [Link] when run. }
d) The program will compile without error and will run 10.}
and terminate without any output. [Link]
[Link] TestNewException {
[Link] the following program, which one of the public static void main(String... args) {
statements is true? Welcome w = new Welcome();
public class Exceptions { [Link]([Link]("Ram"));
public static void main(String[] args) { }
try { 16.}
if ([Link] == 0) return; What is the result on compiling and executing it ?
[Link](args[0]); a) Compiles successfully and displays Ram when
} finally { TestNewException is executed.
[Link]("The end"); b) Runtime exception occurs on executing the class
} TestNewException.
} c) Compilation of [Link] fails.
} d)Compilation of [Link] fails
a) If run with one argument, the program will produce
no output. [Link] the following code:
b) If run with one argument, the program will simply public class ArithmeticTest {
print the given argument. public static void main(String[] args){
c) If run with one argument, the program will print the try
given argument followed by "The end". {
d) The program will throw an int x=0;
ArrayIndexOutOfBoundsException. int y=5/x;
[Link](y);
[Link] the following: }
public class TestDivide { catch (Exception e)
public static void main(String[] args) { {
int value=0; [Link]("Exception");
try { }
int result = 10/value; catch (ArithmeticException ae)
} finally { {
[Link]("f"); [Link]("ArithmeticException");
} }
} }
} }
What is the result ? What is the output?
a) Compilation fails since a catch block is not present. a) Exception
b) Prints only "f" in the output. b) ArithmeticException
c) Only a runtime error is displayed. c) NaN
d)Prints an "f" in the output and a runtime error is d) Compilation Error
also displayed.
[Link] the following,
[Link] the following code in the 3 java files: 1. import [Link].*;
19
2. public class MyProgram { 11. catch (Exception re ) {
3. public static void main(String args[]){ 12. [Link]("caught ");
4. FileOutputStream out = null; 13. }
5. try { 14. finally {
6. out = new FileOutputStream("[Link]"); 15. [Link]("finally ");
7. [Link](122); 16. }
8. } 17. [Link]("after ");
9. catch(IOException io) { 18. }
10. [Link]("IO Error."); 19. }
11. } What is the output ?
12. finally { a) hello throwit caught
13. [Link]();unhandled exception b) hello throwit RuntimeException caught after
14. } c) hello throwit caught finally after
15. } d) hello throwit caught finally after RuntimeException
16. }
and given that all methods of class FileOutputStream, [Link] class ExceptionTest {
including close(), throw an IOException, which one of public static void main(String[] args)
these is true? {
a) This program will compile successfully. try
b) This program fails to compile due to an error at line {
13. ExceptionTest a = new ExceptionTest();
c) This program fails to compile due to an error at line [Link]();
9. [Link]("A");
d) This program fails to compile due to an error at line }
6. catch (Exception e)
{
[Link] the following: [Link]("B");
1. class Base { }
2. void display() throws Exception { throw new finally
Exception(); } {
3. } [Link]("C");
4. public class Derived extends Base { }
5. void display() }
{ [Link]("Derived"); }
6. public static void main(String[] args) { void badMethod()
7. new Derived().display(); {
8. } throw new Error();
9. } }
What is the result ? }
a) Derived What is the output?
b) The code runs with no output. a) BC followed by Error exception
c) Compilation fails because of an error in line 2. b) Error exception followed by BC
d) Compilation fails because of an error in line 7. c) C followed by Error exception
d) Error exception followed by C
[Link] the following,
1. public class RTExcept { [Link] the following,
2. public static void throwit () { public class MyProgram {
3. [Link]("throwit "); public static void throwit() {
4. throw new RuntimeException(); throw new RuntimeException();
5. } }
6. public static void main(String [] args) { public static void main(String args[]){
7. try { try {
8. [Link]("hello "); [Link]("Hello world ");
9. throwit(); throwit();
10. } [Link]("Done with try block ");
20
} 9. catch(IOException e)
finally { 10. {
[Link]("Finally executing "); 11. [Link]("Caught IO Exception");
} 12. }
} 13. catch(Exception e)
} 14. {
Which answer most closely indicates the behavior of 15. [Link]("Caught Exception");
the program? 16. }
a) The program will not compile. 17. }
b) The program will print Hello world, then will print 18. static public void methodA()
that a RuntimeException has occurred, then will print 19. {
Done with try block, and then will print Finally 20. throw new IOException();
executing. 21. }
c) The program will print Hello world, then will print 22. }
that a RuntimeException has occurred, and then will What is the output ?
print Finally executing. a) The output is "Caught Exception".
d) The program will print Hello world, then will print b) The output is "Caught IO Exception".
Finally executing, then will print that a c) Code will not compile.
RuntimeException has occurred. d) Program executes normally without printing a
message.
[Link] the following,
1. [Link]("Start "); [Link]:
2. try { public class TestException {
3. [Link]("Hello world"); public static void main(String... args) {
4. throw new FileNotFoundException(); try {
5. } // some piece of code
6. [Link](" Catch Here "); } catch (NullPointerException e1) {
7. catch(EOFException e) { [Link]("n");
8. [Link]("End of file exception"); } catch (RuntimeException e2) {
9. } [Link]("r");
10. catch(FileNotFoundException e) { } finally {
11. [Link]("File not found"); [Link]("f");
12. } }
and given that EOFException and }
FileNotFoundException are both subclasses of }
IOException, and further assuming this block of code What is the output if NullPointerException occurs
is placed into a class, which statement is most true when executing the code in the try block ?
concerning this code? a) f
a) The code will not compile. b)nf
b) Code output: Start Hello world File Not Found. c) rf
c) Code output: Start Hello world End of file d) nrf
exception.
d) Code output: Start Hello world Catch Here File not [Link] the following:
found. 1. class ShapeException extends Exception {}
2.
[Link] the following code: 3. class CircleException extends ShapeException {}
1. import [Link]; 4.
1. 2. public class ExceptionTest 5. public class Circle2 {
2. { 6. void m1() throws ShapeException {throw new
3. public static void main(String[] args) CircleException();}
4. { 7.
5. try 8. public static void main (String[] args) {
6. { 9. Circle2 circle2 = new Circle2();
7. methodA(); 10. int a=0, b=0;
8. } 11.
21
12. try {circle2.m1(); a++;} catch (ShapeException [Link] option completes the code to print the
e) {b++;} message as long as number is greater than 20?
13. int number = 100 ;
14. [Link]("a=%d, b=%d", a, b); MISSING CODE {
15. } [Link]("The number = " + number);
16.} number --;
What is the expected output ? }
a) a=0, b=0 a) do while (number > 20)
b) a=1, b=0 b) for (number > 20)
c)a=0, b=1 c)while (number > 20)
d) Compile time error at line 6. d) if (number >20)

[Link] the following: [Link] you are writing code for a for loop that
1. class ShapeException extends Exception {} must execute three [Link] is the correct
2. declaration for the loop?
3. class CircleException extends ShapeException {} a) for (int i < 4; i = 1; i++)
b) for (int i = 0; i < 4; i++)
4. c) for (int i = 1; i++; i < 4)
5. public class Circle1 { d) for (int i = 3; i >=1; i--)
6. void m1() throws CircleException {throw new
ShapeException();} [Link] flow control mechanism determines when
7. a block of code should run more than once?
8. public static void main (String[] args) { a) iteration
9. Circle1 circle1 = new Circle1(); b) sequence
10. int a=1, b=1; c) selection
11. d) exceptions
12. try {circle1.m1(); a--;} catch (CircleException e)
{b--;} [Link] of the following is a legal loop definition?
13. a) while (int a == 0) { /* whatever */ }
14. [Link]("a=%d, b=%d", a, b); b) do { /* whatever */ } while (int a = 0);
15. } c) do { /* whatever */ } while (int a == 0);
16.} d) for (int a=0; a<100; a++) { /* whatever */ }
What is the expected output ?
[Link] the following code:
a) a=1, b=1 public class SwitchTest {
b) a=0, b=1 public static void main(String [] args) {
c) a=1, b=0 int i=5, j=0;
d)Compile time error at line 6. switch(i){
case 2: j+=3;
Topic: Flow Control case 4: j+=5;
default : j+=1;
[Link] your code needs to traverse through an case 0: j+=7;
array named array1. Which code would you use to do }
this ? [Link]("j value " + j);
a) for(int i = 0; i <= [Link]; i++) }
b)for(int i = 0; i < [Link]; i++) }
c) for(int i = 0; i <= [Link](); i++) What is the result?
d) for(int i = 0; i < [Link](); i++) a) j value 16
b) j value 8
[Link] of the following is legal? c) j value 7
a)for (int i=0, j=1; i<10; i++, j++) { } d) Compilation error ( "default" should be at the last
b) for (int i=0, j=1; i<10; i++; j++) { } of the switch statement)
c) for (int i=0, j=1; i<10,j<10; i++, j++) { }
d) for (int i=0, float j=1.0; ; i++, j++) { } [Link] the following code:
public class TestBreak {
22
public static void main(String [] args) { value is three
int i = 2; d) value is 2
if (i < 2) {
i++; [Link] the following:
break printAndExit; public class TestLoop
} {
i++; public static void main(String... args)
printAndExit: {
[Link](i); int index = 2;
} while( --index > 0 )
} [Link]( index );
What will be the result of the above code? }
a) 2 }
b) 3 What is printed to standard output?
c) 4 a)1
d) Compilation error 0
b) 1
[Link] the following: 2
public class DoWhileTest { c) 1
public static void main(String [] args) { d) Nothing is printed
int i=2, j=5;
do [Link] the following,
{ 1. int i = 0;
if(i++ > --j) continue; 2. label:
}while(i < 3); 3. if (i < 2) {
[Link]("i=%d, j=%d",i,j); 4. [Link](" i is " + i);
} 5. i++;
} 6. continue label;
After execution, what are the values of i and j? 7. }
a) i=4, j=4 What is the result?
b) i=3, j=4 a) Compilation fails.
c) i=2, j=4 b) Produces no output
d) i=2, j=5 c) i is 0
d) i is 0 i is 1
[Link] statement is true about the following code
fragment? [Link] the following:
1. int j = 2; public class TestLoop {
2. switch (j) { public static void main(String... args) {
3. case 2: outer: for( int i = 0; i <2; i++ )
4. [Link]("value is two"); { inner: for( int j = 0; j < 2; j++ )
5. case 2 + 1: { if( j==1 )
6. [Link]("value is three"); continue outer;
7. break; [Link]( "i=%d, j=%d\n",i,j);
8. default: }
9. [Link]("value is " + j); }
10. break; }
11. } }
The code is illegal because of the expression at line 5. What is printed to standard output?
a) The output would be a) i=0, j=0
value is two b) i=0, j=0
b) The output would be i=1, j=0
value is two c) i=0, j=0
value is three i=0, j=1
c) The output would be d) i=0, j=0
value is two i=1, j=1
23
int i; // Line 3
[Link] the following code: for (i=0; i<1; i++) {[Link](i);} //
public class PESTest { Line 4
public static void main (String[] args) { [Link](TestFor.i);
int j = 0; }}
do for (int i = 0; i++ < 2;) What is the result of attempting to compile and run
[Link](i); the program?
while (j++ < 1); a) Prints: 1100
} b) Prints: 1102
} c) Compile-time error at Line 1
What is the result of attempting to compile and run d) Compile-time error at Line 4
the program?
a) Prints: 12 [Link] the code snippet:
b)Prints: 1212 int m = 0;
c) Prints: 121212 while( ++m < 2 )
d) Compile-time error [Link]( m );
What is printed to standard output?
[Link]: a) 0
switch( i) b)1
{ c) 2
default : d) Nothing is printed
[Link]("Hello");
} [Link] the following code:
What is the acceptable type for the variable i? public class TestForSwitch {
public static void main (String[] args) {
a) byte for (int i = 0; i < 3; i++) {
b) float switch (i) {
c) double default: [Link]("D");
d) Object case 0: [Link]("0");
case 1: [Link]("1");
[Link] the following code: }}}}
public class TestSwitch { What is the result of attempting to compile and run
public static void main(String args[]) { the program?
byte b = -1; a) Prints: DDD
switch(b) { b) Prints: 01D
case -1: [Link]("-1"); break; c) Prints: 01D01
case 127: [Link]("127"); break; d)Prints 011D01
case 128: [Link]("128"); break;
default: [Link]("Default "); [Link] the following code:
}}} class SwitchTest {
What is the result of attempting to compile and run public static void main(String args[]) {
the program? int x = 3; int success = 0;
a) Prints: -1 do {
b) Prints: 128 switch(x) {
c) Prints: Default case 0: [Link]("0"); x += 5; break;
d) Compile-time error case 1: [Link]("1"); success++;
break;
[Link] the following code: case 2: [Link]("2"); x += 1; break;
public class TestFor { case 3: [Link]("3"); x -= 2; break;
static int i; default: break;
public static void main(String args[]) { }
for (i=1; i<2; i++) {[Link](i);} // } while ((x != 1) || (success < 2));
Line 1 }}
for (int i=1; i<2; i++) {[Link](i);} // What is the result of attempting to compile and run
Line 2 the program?
24
a) Prints: 3631 a) 3210
b) Prints: 3621 b)321
c) Prints: 311 c) Will go into an infinite loop
d) Compile-time error d)Compilation error

[Link] the following, [Link] the following code:


1. public class Test { 1. public class Test1
2. public static void main(String [] args) { 2. {
3. int i = 1; 3. public static void main(String[] args)
4. do while ( i < 1 ) 4. {
5. [Link](" i is " + i); 5. int i=0;
6. while ( i > 1 ) ; 6. while(i)
7. } 7. {
8. } 8. if(i==4) break;
What is the result? 9. i++;
a) i is 1 10. }
b) i is 1 i is 1 11. }
c)No output is produced. 12. }
d) i is 1 i is 1 ... in an infinite loop. What will be the value of i at line 11?
a) 0
[Link] the following code: b)4
public class JavaRunTest { c)5
public static void main (String[] args) { d)The code will not compile.
int i = 0, j = 8;
do { [Link] the following code what is the effect of the
if (j < 4) {break;} else if (j-- < 7) {continue;} parameter "num" passed a value of 1.
i++; public class LoopTest {
} while (i++ < 5); public static void process(int num) {
[Link](i + "," + j); loop: for (int i = 1; i < 2; i++){
} for (int j = 1; j < 2; j++) {
} if (num > j) {
What is the result of attempting to compile and run break loop;
the program? }
a) Prints: 5,4 [Link](i * j);
b) Prints: 6,5 }
c) Prints: 6,4 }
d) Prints: 5,7 }
public static void main (String[] args) {
[Link] the following: process(1);
public class DoTest }
{ }
public static void main(String[] args) a) Generates a runtime error
{ b) 3
boolean flag; int index=3; c) 2
do d) 1
{
flag = false; [Link] the following code:
[Link](index); public class TestIf {
index--;
flag = (index>0);
continue; public static void main(String[] args) {
} while ((flag) ? true : false); boolean bFlag = true;
} if (bFlag = false) {[Link]("X");
} } else if (bFlag) {[Link]("Y");
What will be the output of above code? } else {[Link]("Z");}
25
}} }
What is the result of attempting to compile and run What is the expected output ?
the program? a) A
a) Prints: X b) B
b) Prints: Y c) C
c) Prints: Z
d) Compile-time error d) [Link] is thrown at runtime

[Link] the following: [Link] the following,


public class TestLoop2 1. int j = 7;
{ 2. label:
public static void main(String... args) 3. if (j > 5) {
{ 4. [Link](" j is " + j);
int count = 10; 5. j--;
while( count++ < 11 ) 6. continue label;
[Link]( count ); 7. }
} What is the result?
} a) j is 7
What is the output ? b) j is 7 j is 6
a) 10 c) Compilation fails
11 d) Produces no output
b) 10
c) 11
d) Nothing is printed Topic: Inheritance Concepts

[Link] the following: [Link] statement is true?


public class TestDoWhile a) A super() or this() call must always be provided
{ explicitly as the first statement in the body of a
public static void main(String... args) constructor.
{ b) If both a subclass and its superclass do not have
int count = 20; any declared constructors, the implicit default
do { constructor of the subclass will call super() when run.
[Link]( count ); c) If neither super() nor this() is declared as the first
} while ( count++ < 21 ); statement in the body of a constructor, then this() will
} implicitly be inserted as the first statement.
} d) If super() is the first statement in the body of a
What is the output ? constructor, then this() can be declared as the second
a) 20 statement.
21
b) 20 197.A class Car and its subclass Yugo both have a
c) 21 method run() which was written by the programmer
d) Nothing is printed as part of the class definition. If junker refers to an
object of type Yugo, what will the following code do?
[Link] the following: [Link]();
public class TestIfBoolean { a) The run() method defined in Yugo will be called.
public static void main(String[] args) { b) The run() method defined in Car will be called.
Boolean bFlag=null; c) The compiler will complain that run() has been
if (bFlag) { defined twice.
[Link]("A"); d) Overloading will be used to pick which run() is
} else if (bFlag == false) { called.
[Link]("B");
} else { [Link] is a situation:
[Link]("C"); Birthday happy;
} happy = new AdultBirthday( "Joe", 39);
} [Link]();
26
Which greeting() method is run ? a) A subclass must override all the methods of the
a) The one defined for Birthday because that is the superclass.
type of the variable happy. b)It is possible for a subclass to define a method with
b) The one defined for AdultBirthday because that is the same name and parameters as a method defined
the type of the object referred to by happy. by the superclass.
c) The one closest in the source code to the c) Aggregation defines a has-a relationship between a
[Link]() statement. superclass and its subclasses.
d) The assignment statement where the AdultBirthday d) Inheritance defines a is-a relationship between a
object is assigned to happy variable is an error. superclass and its subclasses.

[Link] an object of a child type be assigned to a [Link] statement is true?


variable of the parent type? For example, a) Inheritance defines a has-a relationship between a
Card crd; superclass and its subclasses.
BirthDay bd = new BirthDay("Lucinda", 42); b) Every Java object has a public method named
crd = bd; // is this correct? equals.
a) No-there must always be an exact match between c) Every Java object has a public method named
the variable and the object types. length.
b) No-but a object of parent type can be assigned to a d) A final class can be extended by any number of
variable of child type. classes
c)Yes-an object can be assigned to a reference
variable of the parent type. [Link] statement is true?
d) Yes-any object can be assigned to any reference a) Private methods of a superclass cannot be
variable. overridden in subclasses.
b) A subclass can override any method present in a
[Link] A { A(int i) {} } // 1 superclass.
class B extends A { } // 2 c) An overriding method can declare that it throws
Which one of the following statements is correct? more exceptions than the method it is overriding.
d) The parameter list of an overriding method must be
a) compiler attempts to create a default constructor a subset of the parameter list of the method that it is
for class A. overriding.
b)Compile-time error at 1.
c) Compile-time error at 2. [Link] statement is true?
d) Compiles successfully without any errors. a) The subclass of a non-abstract class can be declared
abstract.
[Link] want subclasses in any package to have b) All the members of the superclass are inherited by
access members of a superclass. Which is the most the subclass.
restrictive access modifier that will accomplish this c) A final class can be abstract.
objective? d) A class in which all the members are declared
a) public private, cannot be declared public.
b) private
c)protected [Link] restriction is there on using the super
d)transient reference in a constructor?
a) It can only be used in the parent’s constructor.
[Link] determines what method is run in the b) Only one child class can use it.
following: c) It must be used in the last statement of the
Card crd = new BirthDay("Lucinda", 42); constructor.
[Link](); d) It must be used in the first statement of the
a) The type of the object or the type of the reference constructor.
variable?
b) The type of the object. [Link] classes A, B, and C, where B extends A, and
c) The type of the reference variable. C extends B, and where all classes implement the
d) Both (type of object as well as the reference instance method void doIt(). How can the doIt()
variable). method in A be called from an instance method in C?
a) [Link]();
[Link] one of the following statement is false? b) [Link]();
27
c) [Link](); 1. class ParentClass {
d) It is not possible. 2. public int doStuff(int x) {
3. return x * 2;
[Link] one of the following statement is false? 4. }
a) The subclass of a non-abstract class can be declared 5. }
abstract. 6.
b) All members of the superclass are inherited by the 7. public class ChildClass extends ParentClass {
subclass. 8. public static void main(String [] args ) {
c) A final class cannnot be abstract. 9. ChildClass cc = new ChildClass();
d) A top level class in which all the members are 10. long x = [Link](7);
declared private, can be declared public. 11. [Link]("x = " + x);
12. }
[Link] statement is true? 13.
a) Public methods of a superclass cannot be 14. public long doStuff(int x) {
overridden in subclasses. 15. return x * 3;
b) Protected methods of a superclass cannot be 16. }
overridden in subclasses. 17. }
c) Methods with default access in a superclass cannot What is the result?
be overridden in subclasses. a) x = 14
d) Private methods of a superclass cannot be b) x = 21
overridden in subclasses. c) Compilation fails at line 2.
d) Compilation fails at line 14.
[Link] statement is true?
a) A subclass must define all the methods from the 214.1. public class TestPoly {
superclass. 2. public static void main(String [] args ){
b) It is possible for a subclass to define a method with 3. Parent p = new Child();
the same name and parameters as a method defined 4. }
by the superclass. 5. }
c) Aggregation defines a is-a relationship between a 6.
superclass and its subclasses. 7. class Parent {
d) It is possible for two classes to be the superclass of 8. public Parent() {
each other. 9. super();
10. [Link]("instantiate a parent");
[Link] the following: 11. }
class Vehicle { } 12. }
class FourWheeler extends Vehicle { } 13.
class Car extends FourWheeler { } 14. class Child extends Parent {
public class TestVehicle 15. public Child() {
{ 16. [Link]("instantiate a child");
public static void main(String[] args) 17. }
{ 18. }
Vehicle v = new Vehicle(); What is the result?
FourWheeler f = new FourWheeler(); a) instantiate a child
Car c = new Car(); b) instantiate a parent
xxxxxxx ic) nstantiate a child
} instantiate a parent
} d) instantiate a parent
Which of the following statement is legal, which can instantiate a child
be substituted for xxxxxxx ?
a) v = c; 215.1 abstract class AbstractIt
b) c = v; 2{
c) f = v; 3 abstract float getFloat();
d) c = f; 4}
5 public class Test1 extends AbstractIt
[Link] the following, 6{
28
7 private float f1 = 1.0f; Which one of the following will cause a compiler
8 private float getFloat(){ return f1;} error?
9 a) rod = rat;
10 public static void main(String[] args) b) rod = mos;
11 { c) pkt = null;
12 } d) pkt = rat;
13 }
a) Compilation error at line no 5 [Link] would be the result of attempting to
b) Runtime error at line 8 compile and executing the following code?
c)Compilation error at line no 8 // Filename: [Link]
d) Compilation succeeds public class MyClass {
public static void main(String[] args) {
[Link]: C c = new C();
interface I1 {} [Link]([Link](13, 29));
class A implements I1 { } }
class B extends A {} }
class C extends B { class A {
public static void main( String[] args) { int max(int x, int y) { if (x>y) return x; else return y; }
B b = new B(); }
xxxxxxx // insert statement here class B extends A{
} int max(int x, int y) { return [Link](y, x) - 10; }
} }
Which code, inserted at xxxxxxx, will cause a cte? class C extends B {
a) A a = b; int max(int x, int y) { return [Link](x+10, y+10); }
b) I1 i= (C)b; }
c) I1 i= (A)b; a) The code will fail to compile because the max()
d) B b2 = (B)(A)b; method in B passes the arguments in the call
[Link](y, x) in the wrong order.
[Link] will be the result of attempting to compile b) The code will fail to compile because a call to a
and run the following program? max() method is ambiguous.
public class Polymorphism { c) code will compile without errors and will print 29
public static void main(String[] args) { when run.
A ref1 = new C(); d) code will compile without errors and will print 39
B ref2 = (B) ref1; when run.
[Link](ref2.f());
} [Link] the following class heirarchies
} class A { }
class A { int f() { return 0; } } class B extends A { }
class B extends A { int f() { return 1; } } class C extends B { }
class C extends B { int f() { return 2; } } And the following method declaration
a) The program will fail to compile. public B doSomething ( ) {
b) The program will compile without error, but will // some valid code fragments
throw a ClassCastException when run. return xx;
c) The program will compile without error and print 1 }
when run. Objects of which class ( from the heirarchy shown
d) The program will compile without error and print 2 above ) can be safely substituted in place of xx in the
when run. method doSomething ( ) ?
a) Object of class A
[Link] that class Rodent has a child class Rat and b) An array object of class B
another child class Mouse. Class Mouse has a child c) Object of class C
class PocketMouse. Examine the following d) An array object of class C
Rodent rod;
Rat rat = new Rat(); [Link] the following code, which is the simplest
Mouse mos = new Mouse(); print statement that can be inserted into the print()
PocketMouse pkt = new PocketMouse(); method?
29
// Filename: [Link] }
public class MyClass extends MySuperclass { public void baz() {
public static void main(String[] args) { [Link]("B");
MyClass object = new MyClass(); }
[Link](); }
} What is the result?
public void print() { a) A
// INSERT CODE HERE THAT WILL PRINT b)B
// THE "Hello, world!" STRING FROM THE c)Compilation fails.
Message d) An exception is thrown at runtime.
// CLASS.
} [Link] the following:
} 1. public class MyClass {
class MySuperclass { 2. public static void main(String[] args) {
Message msg = new Message(); 3. Derived d = new Derived("hello");
} 4. }
class Message { 5. }
// The message that should be printed: 6.
String text = "Hello, world!"; 7. class Base {
} 8. Base() { this("a", "b"); }
a) [Link]([Link]); 9.
b) [Link]([Link]); 10. Base(String x, String y) { [Link](x +
c) [Link]([Link]); y); }
d) [Link]([Link]); 11. }
12.
[Link] the following code, which of these 13. class Derived extends Base {
constructors can be added to MySub class without 14. Derived(String s) { [Link](s); }
causing a compile-time error? 15. }
class MySuper { What is the output?
int number; a) It will print hello followed by ab.
MySuper(int i) { number = i; } b) It will print ab followed by hello.
} c) It will print hello.
class MySub extends MySuper { d) It will print ab
int count;
MySub(int cnt, int num) { [Link] the code below:
super(num); 1. class Fruit {
count=cnt; 2. Fruit getInstance() {
} 3. return this;
// INSERT ADDITIONAL CONSTRUCTOR HERE 4. }
} 5. void print()
a) MySub() {} 6. {
b) MySub(int cnt) { count = cnt; super(cnt); } 7. [Link]("Fruit");
c)MySub(int cnt) { this(cnt, cnt); } 8. }
d) MySub(int cnt) { super(cnt); this(cnt, 0); } 9. }
10. 10.
[Link] the following, 11. public class Apple extends Fruit {
class A { 12. Apple getInstance() {
public void baz() { 13. return this;
[Link]("A"); 14. }
} 15. void print()
} 16. {
public class B extends A { 17. [Link]("Apple");
public static void main(String [] args) { 18. }
A a = new B(); 19. public static void main(String... args)
[Link](); 20. {
30
21. Fruit fr = new Apple().getInstance(); public void draw() { }
22. [Link](); }
23. } Which one of the following statement is correct?
24. } a) Shape s = new Shape();
What will be the output? [Link]();
a) Fruit b) Circle c = new Shape();
b)Apple [Link]();
c) Compilation error at Line 12; Return type of the c) Shape s = new Circle();
overriding method getInstance() cannot be different [Link]();
from the return type of the overridden method of the d) Shape s = new Circle();
super class. s->draw();
d) [Link] Exception at Line 21 since Apple
instance cannot be assigned to Fruit. [Link] the following code, which statement is
true?
[Link] the following, public interface HeavenlyBody { String describe(); }
1. class B extends A { class Star implements HeavenlyBody {
2. int getID() { String starName;
3. return id; public String describe() { return "star " + starName; }
4. } }
5. } class Planet {
6. class C { String name;
7. public int name; Star orbiting;
8. } public String describe() {
9. class A { return "planet " + name + " orbiting " +
10. C c = new C(); [Link]();
11. public int id; }
12. } }
Which one is correct about instances of the classes a) The code will fail to compile.
listed above? b)The use of aggregation is justified, since Planet has-
a) A is-a B a Star.
b) C is-a A c) The code will fail to compile if the name starName
c) B has-a A is replaced with the name bodyName throughout the
d) B has-a C declaration of the Star class.
d) An instance of Planet is a valid instance of a
[Link] the following, HeavenlyBody.
1. class Over {
2. int doStuff(int a, float b) { [Link] the following,
3. return 7; class Foo {
4. } String doStuff(int x) { return "hello"; }
5. } }
6. Which method would not be legal in a subclass of
7. class Over2 extends Over { Foo?
8. // insert code here a) String doStuff(int x) { return "hello"; }
9. } b) int doStuff(int x) { return 42; }
Which method, if inserted at line 8, will not compile? c) public String doStuff(int x) { return "Hello"; }
a) public int doStuff(int x, float y) { return 4; } d) protected String doStuff(int x) { return "Hello"; }
b) protected int doStuff(int x, float y) {return 4; }
c)private int doStuff(int x, float y) {return 4; } [Link]:
d)private int doStuff(int x, double y) { return 4; } 1. public class TestOverload {
2.
[Link]: 3. public void process() {
abstract class Shape { 4. }
public abstract void draw(); 5.
} 6. public String process() {
public class Circle extends Shape { 7. return "hello";
31
8. } a) The statement b.f(); is legal.
9. b) The statement a.j = 5; is legal.
10. public float process(int x) { c) The statement a.g(); is legal.
11. return 67.5f; d) The statement b.i = 3; is legal
12. }
13.} [Link] that class Rodent has a child class Rat and
What is the result? another child class Mouse. Class Mouse has a child
a) An exception is thrown at runtime. class PocketMouse. Examine the following
b) Compilation fails because of an error in line 10. Rodent rod;
c) Compilation fails because of an error in line 6. Rat rat = new Rat();
d) Compilation succeeds and no runtime errors with Mouse mos = new Mouse();
class TestOverload occur. PocketMouse pkt = new PocketMouse();
Which of the following array declarations is correct for
[Link] the following code: an array that is expected to hold up to 10 objects of
class MySuper { types Rat, Mouse, and PocketMouse?
final int calculate(int i, int j) a) Rat[] array = new Rat[10];
{ b) Rodent[] array = new Rat[10];
return i*j; c) Rodent[] array = new Rodent[10];
} d) Rodent[10] array;
}
public class MySub extends MySuper { [Link] the following,
int calculate(int i, int j) 1. class MySuper {
{ 2. public MySuper(int i) {
return 2*i*j; 3. [Link]("super " + i);
} 4. }
5. }
public static void main(String [] args) { 6.
MySuper sup = new MySub(); 7. public class MySub extends MySuper {
int k = [Link](2,5); 8. public MySub() {
[Link](k); 9. super(2);
} 10. [Link]("sub");
} 11. }
What is the result? 12.
a) 10 13. public static void main(String [] args) {
b) 20 14. MySuper sup = new MySub();
c) Compilation error 15. }
d) An exception is thrown at runtime 16. }
What is the result?
[Link] the following classes and declarations, a) sub
which statement is true? super 2
// Classes b) super 2
class Foo { sub
private int i; c) Compilation fails at line 9.
private void f() { /* ... */ } d) Compilation fails at line 14.
public void g() { /* ... */ }
} [Link]:
class Bar extends Foo { public class Employee {
public int j;
public void g() { /* ... */ } private String empID;
} public String empName;
// Declarations: private Integer age;
// ... public void setEmployeeInfo(String empID, String
Foo a = new Foo(); empName, Integer age) {
Bar b = new Bar(); [Link] = empID;
// ... [Link] = empName;
32
[Link] = age; A ref1 = new C();
} B ref2 = (B) ref1;
} [Link](ref2.g());
Which is true? }
a) The class is fully encapsulated. }
b)The empName variable breaks encapsulation. class A {
c) The empID and age variables break polymorphism. private int f() { return 0; }
d) The setEmployeeInfo method breaks public int g() { return 3; }
encapsulation. }
class B extends A {
[Link] Card is the base class of Valentine, private int f() { return 1; }
Holiday and Birthday, in order for the following code public int g() { return f(); }
to be correct, what must be the type of the reference }
variable card? class C extends B {
_________ card; public int f() { return 2; }
card = new Valentine( "Joe", 14 ) ; }
[Link](); a) The program will compile without error and print 0
card = new Holiday( "Bob" ) ; when run.
[Link](); b) The program will compile without error and print 1
card = new Birthday( "Emily", 12 ) ; when run.
[Link](); c) The program will compile without error and print 2
a) Valentine when run.
b) Holiday d) The program will compile without error and print 3
c) Birthday when run.
d)Card
[Link] the following code:
[Link] the following: class B { int m = 7; }
1. class Animal { class D extends B { int m = 9; }
2. String name = "No name"; public class TestBaseDerived {
3. public Animal(String nm) { name = nm; } public static void main(String[] args) {
4. } B b = new B();
5. D d = new D();
6. class DomesticAnimal extends Animal { B bd = new D();
7. String animalFamily = "nofamily"; [Link]("%d %d %d", b.m, d.m, bd.m);
8. public DomesticAnimal(String family) }
{ animalFamily = family; } }
9. } What will be the output on executing the above
10. code ?
11. public class AnimalTest { a) 7 9 7
12. public static void main(String[] args) { b) 7 9 9
13. DomesticAnimal da = new c) 9 7 9
DomesticAnimal("cat"); d) 9 9 7
14. [Link]([Link]);
15. } [Link] the following,
16. } 1. class MyInherit {
What is the result ? 2. int calculate(int m, float n) {
a) cat 3. return 9;
b) nofamily 4. }
c) An exception is thrown at runtime. 5. }
d) Compilation fails due to an error in line 8. 6.
7. class MyInheritChild extends MyInherit {
[Link] will be the result of attempting to compile 8. // insert code here
and run the following program? 9. }
public class Polymorphism2 { Which method, if inserted at line 8, will NOT compile?
public static void main(String[] args) { a) private int calculate(int a, float b) {return 25; }
33
b) private int calculate(int a, double b) { return 25; } [Link] of the following is a reserved word in the
c) public int calculate(int a, float b) { return 25; } Java programming language ?
d) protected int calculate(int a, float b) {return 25; } a) reference
b) method
Topic: Keywords, Literals, Identifiers c)native
d) array
[Link] of the following keywords is reserved but
not used in Java? [Link] of the following describes an incorrect
a) delete default value for the types indicated?
b) const a) float -> 0.0f
c) constant b) boolean -> false
d) unsigned c) Dog -> null
d) String -> "null"
[Link] of the following is a valid initialization ?
a) boolean b = TRUE; [Link] statement is true?
b) float f = 27.893; a) return, goto, and default are keywords in the Java
c) int i = 0xDeadCafe; language.
d) long l = 79,653; b) new and delete are keywords in the Java language.
c) exit, class, and while are keywords in the Java
[Link] of the following is a valid declaration of language
String ? d) static, unsigned, and long are keywords in the Java
a) String S1=‘null’; language
b) String S2=null;
c) String S3 = (String) ‘face’; [Link] of the following variable initialization is
d) String S4=(String)\ufeed; invalid?
a) byte myByte=254;
[Link] is the correct way to create a String object b) double myDouble=12341.509D;
whose value can be shared and which does not create c) int myInt = 0xFACE;
new object for each similar declaration ? d)long myLong=45678L;
a) StringBuffer hello = new StringBuffer(14);
b) String hello = new String("Welcome to Java"); [Link] of the following is a valid Java identifier?
c) String hello = "Welcome to Java"; a) _underscore
d) String hello[] = "Welcome to Java"; b) %percent
c) @attherate
[Link] is the default data type of the literal d) 3numbers
represented as 48.0 ?
a) float [Link] create a class level constant, which of the
b)double following two keywords should be used:
c) int a) public and constant
d) byte b) const and final
c) final and constant
[Link] of the following is a valid declaration of d) final and static
char ?
a) char ch="a"; [Link] of the following is an invalid initialization ?
b) char ch = ‘cafe’; a) byte y=0x7a;
c) char ch = ‘\ucafe’; b) short s=679;
d) char ch = ‘\u10100’; c)boolean b=FALSE;
d) double d=14.67f;
[Link] of the following is a non-primitive data
type in Java? [Link] of the following is an invalid intialization ?
a) int a) float f = 85.3f;
b) float b) byte t = 0x5e;
c) String c) long l = 9876L;
d) double d)boolean n = TRUE;

34
[Link]: 3. public static void main(String[] args)
1. public class Test { 4. {
2. public static void main(String[] args) { 5. byte b1=198;
3. unsigned byte b=0; 6. byte b2=1;
4. b--; 7. [Link](b1+b2);
5. 8. }
6. } 9. }
7. } a) Compilation error at Line 5.
What is the value of b at line 5? b) Compilation error at Line 7.
a) -1 c) Prints 199
b) 255 d) Prints a number different from 199.
c)Compilation error at line 3 as there is nothing like
unsigned byte in Java. [Link] results would print from the following code
d) Compilation succeeds and throws runtime snippet:[Link]("12345 ".valueOf(54321));
exception at line 4. a) 12345 54321
b)54321
[Link] is the result of compiling and executing the c) The application won’t compile.
below code ? d) Runtime error
1. public class Test
2. { [Link]:
3. public static void main(String[] args) 1. public class ValueCheck {
4. { 2. public static void main(String[] args) {
5. byte b=127; 3. unsigned byte y = -1;
6. byte c=15; 4. y++;
7. byte a = b + c; 5.
8. } 6. }
9. } 7. }
a) Throws runtime exception at line no 7 saying "out What is the value of y at line 5?
of range". a) 0
b) Compilation succeeds and a takes the value of 142. b) 2
c) Compilation error at line 5. Byte cant take value of c)Compilation error at line 3 as there is nothing like
127. unsigned byte in Java.
d) Compilation error at line 7. d) Compilation succeeds and throws runtime
exception at line 4.
[Link] will be the output after compiling the
following statements? [Link] is the result of compiling and executing the
public class TestIdentifier below code ?
{ 1. public class ByteTest
public static void main(String[] args) 2. {
{ 3. public static void main(String[] args)
double volatile = 21+3.775; 4. {
[Link](volatile); 5. byte x=100;
} 6. byte y=127;
} 7. byte z = x + y;
8. }
a) 25 9. }
b) 24.775 a) Throws runtime exception at line no 7 saying "out
c) 24 of range".
d) Compilation error as volatile is a keyword and b) Compilation succeeds and a takes the value of 227.
cannot be used as identifier. c) Compilation error at line 6. Byte cant take value of
127.
[Link] is the result of compiling and executing the d)Compilation error at line 7.
below code ?
1. public class Test [Link] will be the output after compiling the
2. { following statements?
35
public class TestIdentifier
{ [Link] range of values is valid for all integral
public static void main(String[] args) types, where n is the number of bits?
{ a) 2^(n-1) to 2^(n+1)+1
float volatile = 53+4.289; b) -2^(n-1) to 2^(n-1)-1
[Link](volatile); c) -2^(n-1) to 2^(n-1)+1
} d) -2^(n)-1 to 2^(n-1)-1
}
a) 58 [Link] char c = ‘A’;
b) 57.289 What is the simplest way to convert the character
c) 57 value in c into an int?
d) Compilation error as volatile is a keyword and a) int i = [Link](c);
cannot be used as identifier. b) int i = (int) c;
c) int i = int (c);
[Link] is the result of compiling and executing the d) int i = c;
below code ?
1. public class Test [Link] primitive type ranges from -2^31 to
2. { (2^31)-1?
3. public static void main(String[] args) a) long
4. { b) int
5. byte y1=3; c) short
6. byte y2=225; d) byte
7. [Link](y1+y2);
8. } [Link] primitive type char in Java consists of
9. } a) 8 bits
a) Compilation error at Line 6. b)16 bits
b) Compilation error at Line 7. c) 24 bits
c) Prints 228 d) 32 bits
d) Prints a number different from 228.
[Link] which of these variable declarations will the
[Link] results would print from the following code variable remain uninitialized unless explicitly
snippet:[Link]("ABCDE ".valueOf(98765)); initialized?
a) ABCDE 98765 a) Declaration of an instance variable of type boolean
b)98765 b) Declaration of a static variable of type double
c) The application won’t compile. c)Declaration of a local variable of type short
d) Runtime error d) Declaration of a static variable of type String

[Link]: [Link] the following section of code:


1. public class TestByte { int area;
2. int perimeter;
3. public static void main(String[] args) { String name;
4. unsigned byte t=255; How many objects have been created?
5. t++; a)None, there is one object reference variable, but no
6. objects yet.
7. } b) One, there is one object reference variable so there
8. } must be one object.
What is the value of t at line 6? c) Three, one for each variable.
a) Compilation succeeds and throws runtime d) Two, one for each data type.
exception at line 5.
b)Compilation error at line 4 as there is nothing like [Link] is the numerical range of char?
unsigned byte in Java. a) -128 to 127
c) 256 b) -( 2 ^ 15) to (2 ^ 15) -1
d) 0 c) 0 to 32767
d) 0 to 65535
Topic: Primitive Types, Objects, References
36
[Link] i is an int and s is a short, how do you assign i to int a,b;
s? b=5;
a) i = s; a) Local variable a is not declared.
b) i = (int) s; b) Local variable b is not declared.
c) s = (short) i; c) Local variable a is declared but not initialized.
d) s = i; d) Local variable b is declared but not initialized.

[Link] one of the following primitive type [Link]:


conversion is permitted implicitly without using int index = 2;
casting? boolean[] test = new boolean[3];
a) long to int boolean foo = test [index];
b) double to long What is the result?
c) float to double a) foo has the value of 0.
d) double to float b) foo has the value of null.
c) foo has the value of true.
[Link] which of the following answers does the d) foo has the value of false.
number of bits increase from fewest (on the left) to
most (on the right)?
a) byte long short int [Link] the following:
b) int byte short long 1 public class Test {
c)byte short int long 2 public static void add( Integer i)
d) short byte long int 3 {
4 int val = [Link]();
[Link] of the following is a valid declaration of 5 val +=3;
boolean? 6 i = new Integer(val);
a) boolean b2 = no; 7 }
b) boolean b3 = yes; 8
c)boolean b4 = false; 9 public static void main (String[] args)
d) boolean b5 = [Link](); 10 {
11 Integer i = new Integer(0);
[Link] primitive type ranges from -2^15 to 12 add(i);
(2^15)-1? 13 [Link]([Link]());
a) char 14 }
b) int 15 }
c)short What will be the output?
d) byte a) Compilation error
b) Run time error at Line no. 4
[Link] : c) 3
int a = 4; d) 0
byte b = 0;
Which line assigns the value of a to b? [Link] will be the result of attempting to compile
a) b = a; and run the following program?
b)b = (byte) a; public class Integers {
c) b = byte a; public static void main(String[] args) {
d)b = byte(a); [Link](0x10 + 10 + 010);
}
[Link] of the following primitive data type is an }
integer type? a) The program will not compile. The compiler will
a) boolean complain about the expression 0x10 + 10 + 010
b) byte b) When run, the program will print 30
c) float c) When run, the program will print 34
d) double d) When run, the program will print 101010

[Link] the following code within a method, which [Link] class Test
statement is true? {
37
static void operate( StringBuffer x, StringBuffer y) c) The code will compile correctly and will display 10
{ when run.
[Link](y); d) The code will compile correctly and will display 20
y = x; when run.
}
public static void main(String[] args) 289.
{ Given:
StringBuffer x = new StringBuffer("Sun"); int index = 2;
StringBuffer y = new StringBuffer("Java"); Boolean[] test = new Boolean[3];
operate(x,y); Boolean foo = test [index];
[Link](x + "," + y); What is the result?
} a) foo has the value of true.
} b) foo has the value of false.
What is the result? c)foo has the value of null.
a)The code compiles and prints "Sun,Java". d) foo has the value of 0.
b) The code compiles and prints "Sun,Sun".
The code compiles and prints "Java,Java". Topic: String Concepts
b) The code compiles and prints "SunJava,java".
c)The code compiles and prints "SunJava,SunJava". [Link] function does the trim() method of the
d)None of the above String class perform?
a) It returns a string where the leading white space of
[Link] class Test1 the original string has been removed.
{ b) It returns a string where the trailing white space of
private float f1 = 1.0f; the original string has been removed.
float getFloat(){ return f1;} c) It returns a string where both the leading and
public static void main(String[] args) trailing white space of the original string has been
{ removed.
String foo = "ABCDE"; d) It returns a string where all the white space of the
[Link](3); original string has been removed.
[Link]("XYZ");
[Link](foo); [Link] one of the following operators cannot be
} used in conjunction with a String object?
} a) +
What will be the output? b) -
a) Compilation error in the line where "substring" is c) +=
invoked d) .
b) ABXYZ
c) ABCXYZ [Link] method is not defined in the StringBuffer
d)ABCDE class?
a) trim()
[Link] will be the result of attempting to compile b) length()
and run the following class? c) append(String)
public class Assignment { d) reverse()
public static void main(String[] args) {
int a, b, c; [Link] method is not defined in the String class?
b = 10; a) reverse()
a = b = c = 20; b) length()
[Link](a); c) concat(String)
} d)hashCode()
}
a) The code will fail to compile, since the compiler will [Link] statement concerning the charAt() method
recognize that the variable c in the assignment of the String class is true?
statement a = b = c = 20; has not been initialized. a) The index of the first character is 1.
b) The code will fail to compile because the b) The charAt() method returns a Character object.
assignment statement a = b = c = 20; is illegal. c) The expression "abcdef".charAt(3) is illegal.
38
d) expression "abcdef".charAt(3) evaluates to the
character ‘d’. [Link] the following,

[Link] one of the statements is true? 1. public class StringRef {


a) StringBuffer is thread safe whereas StringBuilder is 2. public static void main(String [] args) {
not thread safe 3. String s1 = "abc";
b) StringBuffer is not thread safe whereas 4. String s2 = "def";
StringBuilder is thread safe 5. String s3 = s2;
c) Both String and StringBuilder are immutable 6. s2 = "ghi";
d) Both StringBuffer and StringBuilder are immutable 7. [Link](s1 + s2 + s3);
8. }
[Link] one of the expressions will evaluate to true 9. }
if preceded by the following code? What is the result?
String a = "hello"; a) abcdefghi
String b = new String(a); b) abcdefdef
String c = a; c) abcghidef
char[] d = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ }; d) abcghighi
a) (a == "Hello")
b) (a == b) [Link] the following code snippet,
c) [Link](b) 13. String x = new String("xyz");
d) [Link](d) 14. y = "abc";
15. x = x + y;
[Link] one of the expressions will evaluate to true How many String objects have been created? Assume
if preceded by the following code? the code given above is a portion of the code present
String str1 = "unread"; in a method.
String str2 = new String(str1); a) 2
String str3 = str1; b) 3
char[] str4 = { ’u’, ’n’, ’r’, ’e’, ’a’, ’d’ }; c) 4
a) (str1 == "Unread") d) 5
b) (str1 == str2)
c) [Link](str2) [Link] the following:
d) [Link](str4) public class TestSubstring {
public static void main(String[] args) {
[Link] expression will extract the substring "kap" String str = "international";
from a string defined by String str = "kakapo"? str = [Link](6,9);
a) [Link](2, 2) char b = [Link](2);
b) [Link](2, 3) str = str + b;
c) [Link](2, 4) [Link](str);
d) [Link](2, 5) }
}
What is the result? Assume the code given above is a
[Link] one of the following statements is true? portion of the code present in a method.
a) String class cannot be subclassed. a) atia
b) Subclasses of the String class can be mutable. b)atii
c) All objects have a public method named clone(). c) atioa
d) The expression ((new StringBuffer()) instanceof d) atiot
String) is always true.
[Link] will be the result of attempting to compile
[Link] the code snippet: and run the following code?
String str = new String("Hello"); public class StringMethods {
Which of the below mentioned is an invalid call ? public static void main(String[] args) {
a) [Link]('H','h'); String str = new String("eenny");
b) [Link](2); [Link](" meeny");
c) [Link]("World"); StringBuffer strBuf = new StringBuffer(" miny");
d) [Link](); [Link](" mo");
39
[Link](str + strBuf); [Link] will be the result of attempting to compile
} and run the following program?
} public class MyClass {
a) The program will print "eenny meeny miny" when public static void main(String[] args) {
run. String s = "hello";
b) The program will print "eenny meeny miny mo" StringBuffer sb = new StringBuffer(s);
when run. [Link]();
c) The program will print "meeny miny mo" when run. if (s == sb) [Link]("a");
d) The program will print "eenny miny mo" when run. if ([Link](sb)) [Link]("b");
if ([Link](s)) [Link]("c");
[Link] will be the result of attempting to compile }
and run the following code? }
public class RefEq { a) The program will throw a ClassCastException when
public static void main(String[] args) { run.
String s = "ab" + "12"; b) The code will fail to compile since the expression (s
String t = "ab" + 12; == sb) is illegal.
String u = new String("ab12"); c) The code will fail to compile since the expression
[Link]((s==t) + " " + (s==u)); ([Link](sb)) is illegal.
} d) The program will print c when run.

} [Link] will be the result of attempting to compile


a) The program will print true true when run. and run the following program?
b) The program will print false false when run. public class MyClass {
c) The program will print false true when run. public static void main(String[] args) {
d) The program will print true false when run. StringBuffer sb = new StringBuffer("have a nice
day");
[Link] the following code snippet, [Link](6);
String x = "xyz"; [Link](sb);
[Link](); }
String y = [Link](‘Y’, ‘y’); }
y = y + "abc"; a) The code will fail to compile since there is no
[Link](y); method named setLength in the StringBuffer class.
What is the result? Assume the code given above is a b) The program will throw a
portion of the code present in a method. StringIndexOutOfBoundsException when run.
a) abcXyZ c) The program will print "have a" when run.
b) abcxyz d) The program will print "ce day" when run.
c)xyzabc
d) XyZabc [Link] will the following program print when run?
public class Search {
[Link] the following: public static void main(String[] args) {
public class TestStringBuffer { String s = "Contentment!";
public static void main(String[] args) { int middle = [Link]()/2;
StringBuffer strBuff = new StringBuffer("java String nt = [Link](middle-1, middle+1);
platform"); [Link]([Link](nt, middle));
[Link](4); }
[Link](strBuff); }
} a) 2
} b) 4
What is the output ? c) 5
a) jav d) 7
b)java
c) platform [Link] will be the result of attempting to compile
d) javaplatform and run the following code?
class MyClass {
public static void main(String[] args) {
40
String str1 = "str1"; [Link] will be the result of attempting to compile
String str2 = "str2"; and run the following code?
String str3 = "str3"; public class TestStringOperation {
[Link](str2); public static void main(String[] args) {
[Link]([Link](str1)); String str1 = new String("java");
} [Link](" world");
} StringBuffer strBuf1 = new StringBuffer("
a) The program will print str3str1 when run. magazine");
b) The program will print str3str1str2 when run. [Link](" article");
c) The program will print str3 when run. [Link](str1 + strBuf1);
d) The program will print str3str2 when run. }
}
[Link] one of the following is not legal? a) The program will print "java magazine article" when
a) [Link]("st".concat("ep")); run.
b) [Link]("st" + "ep"); b) The program will print "world magazine article"
c) [Link](’s’ + ’t’ + ’e’ + ’p’); when run.
d) [Link]("st" + new String(’e’ + ’p’)); c) The program will print "java world magazine" when
run.
[Link] will be written to the standard output when d) The program will print "java world magazine
the following program is run? article" when run.
import static [Link];
public class TestOutput { Topic: Package, Import, Jar Concepts
public static void main(String[] args) {
String space = " "; [Link] is true about the import statement in
String composite = space + "windows" + space + Java?
space; a) When .* is used in an import statement, all the
[Link]("server"); classes in that package and the sub-packages will be
String trimmed = [Link](); imported.
[Link]([Link]()); b) The import statements must appear before any
} package statement is declared.
} c) The import statement must be the first statement
a) 7 after any package declaration in a file.
b) 9 d) The import statement is mandatory when using
c) 13 classes of other packages since there is no other way
d) 15 to use a class.

[Link] expression will evaluate to true? [Link] JAR files are packaged using the following
a) "Hello there".toLowerCase().equals("hello there") format
b) "HELLO THERE".equals("hello there") a) TAR
c) ("hello".concat("there")).equals("hello there") b) ZIP
d) "Hello There".compareTo("hello there") == 0 c) ARJ
d) CAB
[Link] the following code snippet,
4. String d = "bookkeeper"; [Link] order to run a jar file, say "[Link]" using the
5. [Link](1,7); command "java -jar [Link]", what condition should
6. d = "w" + d; be satisfied?
7. [Link]("woo"); a) [Link] should be given executable permission
8. [Link](d); b) The manifest file of the jar should specify the class
What is the result? Assume, the code given above is a whose main method should be executed.
portion of the code present in a method. c) "-jar" is an invalid option for java command and an
a) wookkeewoo error will be displayed.
b) wbookkeewoo d) There should be a class "[Link]" with the same
c) Compilation fails. name as the jar file for the command to work.
d) An exception is thrown at runtime.

41
[Link] one of the following is not a valid header a) JPG
in the manifest of jar file? b) PNG
a) Specification-Title c) TIF
b)Application-Version d) JAR
c) Implementation-Vendor
d) Name [Link] is the manifest header that is used to
specify the application’s entry point in a JAR file?
321.A special file which is present inside the JAR that a) Class-Path
contain information about the files packaged in a JAR b) Entry-Class
file is known as c) Start-Class
a) Metafest d)Main-Class
b) Metadata
c) Manifest [Link] a class named App1 is located in the
d) Manidata [Link] package. You have compiled the
class. How do you execute the class?
[Link] decide that you wish to add your a) java App1
application’s class to a group of classes that are stored b) java [Link].App1
in the location /examples/basics. c) javac [Link].App1
Complete the code to do this d) java [Link]
a) package [Link];
b) import [Link]; [Link] is the main() method special in a Java
c) import package [Link]; program?
d) package examples/basics; a) It is where the Java interpreter starts whole
program running.
[Link] want the code in [Link] to access the b) Only the main() method may create objects.
[Link] class which is stored within c) Every class must have a main() method.
the [Link] file in the directory /jars. How would d) main() method must be the only static method in a
you compile your code? program.
a) javac -classpath /jars/[Link] [Link]
b) javac -classpath /jars/example [Link] [Link] the following code:
c) javac -classpath /jars/ [Link] public class Test {
d) javac -classpath /jars [Link] public static void main(String[] args)
{
[Link] you are creating a class named Button [Link](args[0]);
that you want to include in a group of related classes }
called controls. }
Identify the correct code that includes the class in that If the above code is compiled and run as follows
group. java Test Hello 1 2 3
a) package controls; What would be the output ?
b) public class Button a) java
c) package Button; b) Test
d) import controls; c) Hello
d) Hello 1 2 3
[Link] is true about the package statement in
Java? Topic: Command Line, System Properties
a) It can appear anywhere in the file as long as the
syntax is correct. [Link] the below mentioned code
b) It should appear after all the import statements but and the command-line invocation as,
before the class declaration.
c) There can be more than one package statement. java CommandArgsThree 1 2 3
d)It should be the first non-comment line in the Java public class CommandArgsThree {
source file. public static void main(String [] args) {
String [][] argCopy = new String[2][2];
[Link] is a file format which enables to bundle int x;
multiple files into a single file argCopy[0] = args;
42
x = argCopy[0].length; d) An attempt to run B from the command line fails.
for (int y = 0; y < x; y++) {
[Link](" " + argCopy[0][y]);
} [Link] the below mentioned code
} and the command-line invocation as,
} java CommandArgs 1 2 3 4
What is the result? 1. public class CommandArgs {
a) 0 0 2. public static void main(String [] args) {
b) 1 2 3. String s1 = args[1];
c) 0 0 0 4. String s2 = args[2];
d) 1 2 3 5. String s3 = args[3];
6. String s4 = args[4];
[Link] the below mentioned code 7. [Link](" args[2] = " + s2);
and the command-line invocation as, 8. }
java CommandArgsTwo 1 2 3 9. }
1. public class CommandArgsTwo { What is the result?
2. public static void main(String [] argh) { a) args[2] = 2
3. String [] args; b) args[2] = 3
4. int x; c) args[2] = 1
5. x = [Link]; d) An exception is thrown at runtime
6. for (int y = 1; y <= x; y++) {
7. [Link](" " + argh[y]); [Link] the following code:
8. } public class Foo {
9. } public static void main(String[] args)
10. } {
What is the result? [Link](args[1]);
a) 0 1 2 }
b) 1 2 3 }
c) 0 0 0 If the above code is compiled and run as follows
d) An exception is thrown at runtime java Foo Apples 9 8 7
What would be the output ?
[Link] the following code: a) java
public class Test { b) Foo
public static void main(String[] args) c) Apples
{ d) 9
[Link]([Link]);
} [Link] the below mentioned code
} and the command-line invocation as,
If the above code is compiled and run as follows java CommandArgsFour 9 6 3
java Test Hello 1 2 3
What would be the output ? public class CommandArgsFour {
a) 6 public static void main(String [] argh) {
b) 5 String [] args;
c) 4 int a;
[Link] [Link] contains a = [Link];
class A {public static void main(String... args) {}} // 1 for (int b= 1; b < a; b++) {
and [Link] contains [Link](" " + argh[b]);
class B {protected static void main(String[] args) {}} // }
2 }
What is the result of attempting to compile each of }
the two class declarations and invoke each main What is the result?
method from the command line? a) null null
a) Compile-time error at line 1. b) 9 6
b) Compile-time error at line 2. c) 6 3
c) An attempt to run A from the command line fails. d) An exception is thrown at runtime
43
b)WiproStyle is a static analysis tool
[Link] the below mentioned code c) WiproStyle is a structural analysis tool
and the command-line invocation as, d) WiproStyle is a testing tool
java CommandArgsFive 9 8 7 6
public class CommandArgsFive { [Link] of the following refers to the analysis of
public static void main(String [] args) { computer software that is performed without actually
Integer i1 = new Integer(args[1]); executing programs?
Integer i2 = new Integer(args[2]); a) runtime analysis
Integer i3 = new Integer(args[3]); b) static analysis
Integer i4 = new Integer(args[4]); c) profiling
[Link](" args[3] = " + i3); d) none of the above
}
} [Link] are coding standards?
What is the result?
a) args[3] = 8 a) Standards to avoid code construct having high
b) args[3] = 7 probability of resulting in an error.
c) args[3] = null b) Standards to be followed during System testing.
d) An exception is thrown at runtime c) Stdards used for defining designing guidelines for
the system.
Topic: WiproStyle d) Standards that cannot be followed during the CUT
phase
[Link] does 'Avoid magic numbers' rule in
WiproStyle throw a violation? [Link] of the WiproStyle rule is violated in below
a) Integer variable is declared snippet of code,
b) A numeric literal that is not defined as a constant is public class Sample{
detected public int method1() {
c) When the integer variable is made global int a =10; int b=20;
d) No such rule in WiproStyle int c = a*b;
return c;
[Link] of the following are advantages of using }
WiproStyle for code review? }
a) Reduces code review effort a) Minimize the number of lines by joining multiple
b) Code is generated automatically shorter lines
c) Code can be reverse engineered b) Avoid return statements
d) All the above c) Declare all variables in a single line
d) Avoid multiple variable declaration in single line
[Link] of the following can be used to automate
code review in Java? [Link] of the following is a benefit of using static
a) Junit analyzer?
b) Jprofiler a) Non-Compliance to coding guidelines can be
c)WiproStyle detected automatically.
d) None of the above b) Unit testing can be performed
c) Code coverage can be measured
[Link] of the following is correct with respect to d) can reverse engineer the code
severity level information in Static Analyzers?
a) Severity levels information helps to fix only the [Link] is the earliest phase in which Wiprostyle
violations with critical severity can be used?
b) Severity levels information helps to ignore the a) System testing
violations with minor severity b) Design
c) Severity levels information helps in better c) Requirements
prioritization of violations d) Coding
d) All of the above
[Link] of the WiproStyle error category is violated
[Link] is WiproStyle? in below snippet of code,
a) WiproStyle is a unit testing tool class Foo{
44
public void testA () { }
[Link]("Entering test");//VIOLATION a) Avoid Nested Blocks
} b) Use arraylist instead of vector
} c) Missing Switch Default
a) Maintainability d) Multiple variable declaration on the same line
b) Security
c) Reliability [Link] of the following violations is thrown by
d) Efficiency WiproStyle in below code section?
class A{
int x, y, z;
[Link] of the WiproStyle error category is violated String firstName, LastName;
if we use tab character in our source code? int myAge, mySize, numShoes = 28;
a)Maintainability int a = 4, b = 5, c = 6;
b) Efficiency }
c) Reliability a) Avoid Nested Blocks
d) Portability b) Multiple variable declaration on the same line
c) Empty Block
[Link] of the following rules does WiproStyle d) Missing Switch Default
handle?
a) Rules to detect code coverage [Link] of the following violations is thrown by
b) Formatting ,naming conventions, java doc WiproStyle in below code section?
c) Rules to detect failed test cases public class SampleViolation{
d) None of the above
protected void finalize () throws Throwable { //
[Link] of the software code quality attribute can VIOLATION
be improved by following consistent formatting }
standard? }
a) Security a) Empty Block
b)Maintainability b) Avoid Nested Blocks
c) Efficiency c) Use SuperFinalize()
d) Formatting related standards do not improve any d) Missing Switch Default
code quality attributes
[Link] of the following violations is thrown by [Link] of the following options should be used to
WiproStyle in below code section? correct the violation on line 9?
public class SrrayListExample { [Link] Foo {
int method(int a, int b) { 2. void bar() {
int i = a + b; [Link]
return i; 4.{
} 5. compressThumbnailToDisk(metadata, image);
} 6.}
a) Use arraylist instead of vector [Link] (IOException e)
b) Class should define a constructor 8.{
c) Avoid instantiating string objects 9. [Link](); //Violation
d) Unused import 10. throw new ResourceError([Link]());
11.}
[Link] of the following violations is thrown by a) [Link]()
WiproStyle in below code section? b) java doc
public class Foo { c) [Link]
public void bar() { d) logger
int x = 2;
switch (x) { [Link] of the following violations is thrown by
case 2: WiproStyle in below code section?
int j = 8; public class SampleViolation {
} public int publicVariable; // VIOLATION
} protected int protectedVariable; // VIOLATION
45
int packageVariable; // VIOLATION a) Simple Statements - line with more than a single
} statement
a) Trailing Array Comma b) Avoid chaining assignment operators
b) Visibility Modifier c) Trailing Array Comma
c) SuperFinalize d) Avoid assignments in operands
d) Missing Switch Default
[Link] int convert(String s) {
[Link] of the following violations is thrown by int i, i2;
WiproStyle for below code section? i = [Link](s).intValue(); // Violation
import java.*; i2 = [Link](i).intValue(); // Violation
import [Link].*; return i2;
import [Link]; }
public void Helllo{ What is the cause of the violation in the above code ,
} that wiprostyle may throw.
a) Use only Star (Demand) Imports a) Do not add empty strings
b) Trailing Array Comma b) Consider replacing this Vector with the newer
c) Avoid Star (Demand) Imports [Link]
d) Avoid multiple import statements c) Unneccessary Wrapper Object creation
d) Avoid instantiating String objects; this is usually
[Link] of the following violations is thrown by unnecessary
WiproStyle in below code section?
public interface Foo { [Link] class Foo {
public void method (); // VIOLATION public void bar() {
abstract int getSize (); // VIOLATION try {
static int SIZE = 100; // VIOLATION // do something
} } catch (Throwable th) { //violation
a) Redundant Modifier [Link]();
b) Trailing Array Comma }
c) Avoid Star (Demand) Imports }
d) SuperFinalize }
a) Avoid using exceptions as flow control
361."Explicitly invalidate Session when user logs off" . b) Avoid catching NullPointerException; consider
This rule address removing the cause of the NPE
a) Java secure coding c)Avoid throwing raw exception types
b) Concurrency and Timing problems d) A catch statement should never catch throwable
c) Data handling problems since it includes errors
d) Logical problems
websession [Link] class InvokeWait {
public void method () throws InterruptedException
[Link] of the following violations will be thrown {
on the given code snippet. wait (); // VIOLATION
class Foo { boolean bar(String a, String b) { return a } What is the cause of the above violation.
== b; }} a) Avoid using exceptions as flow control
a) Do not instantiate a StringBuffer with a char b) Avoid throwing raw exception types
b) Use equals() to compare object references c) Do not implement 'SingleThreadModel' interface
c) Avoid chaining assignment operators d) Call wait() inside while or do-while
d) Always initialize static fields
[Link] class Test {
[Link] violation is expected to be thrown by public static void main() { // VIOLATION
wiprostyle on the below code ? }
public class Test { public void test() {
int method (int a, int b) { }
int i = a + b; return i; // Violation public void test1() {
} }
}
46
What may be the possible coding standard violation 371."The ability of a software product to keep
in the above snippet operating over time without failures that renders the
a) Placement of Constants system unusable" is called ( as per ISO 9126)
b) Avoid Multple overloaded methods a) Portability
c) Place Main method as last method b) Maintainability
d) Use Chain Constructors c) Reliability
d) Efficiency
[Link] class Test {
int AGE; // Violation 372."The aptitude of the source code to undergo
public void method1() { repair and evolution". Is called ( as per ISO 9126)
int AGE; a) Efficiency
} b) Reliability
String NA__ME11; // Violation c) portability
} What is the java coding standard violation d) Maintainability
expected in the code snippet above?
a) Reduntant Modifiers [Link] of code intended to find and fix
b) Declare fields with uppercase character names as mistakes overlooked in the initial development phase.
'final' a) Profiling
c) Avoid unused private fields b) unit testing
d) Always initialize static fields c) defect tracking
[Link] class MI { d) code review
public String[] getNames() {
String[] names = {"ashik","hema"}; [Link] is the ideal time for starting the usage of
if([Link] != 0) { static analyzers
return names; a) as soon as the coding starts.
} else { b) once all the coding is over
return null;//Violation c) along with system testing
} d) after unit testing
}
} [Link] is the recommended procedure for usage of
How can the above highlighted coding standard static analyzers if you have legacy code ? (existing
violation be fixed? code base)
a) Return Zero length array instead of null a) Static analyzer should be run on the legacy code as
b) Avoid return statements well
c) Do not add empty strings b) No need to run static analyzer on Legacy code base.
d) Avoid instantiating String objects; this is usually c) static analyzer usage is not reccomended in this
unnecessary scenario
d) Static analyzers are supposed to be run on the
[Link] abstract class Sample { //VIOLATION newly developed LOCs by you.
public abstract StringBuffer getText();
public abstract int getStartPosition(); [Link] capability of the software product to avoid
public abstract int getEndPosition(); unexpected effects from modifications of the
public abstract int getStartLine(); software. (ISO 9126) is termed as
public abstract int getEndLine(); a) adaptability
} b) portability
What may be the violation thrown by a static c) testability
analyzer at the highlighted line. d) stability
a) If a class Extends / Implements other class then it
should have a Naming Convention as defined by the [Link] class Foo {
user void bar(int a) {
b) anonymous classes used as interface implementors switch (a) {
c) Redeclare non-functional class as interface case 1:
d) Avoid multiple Class or Interface // do something
break;
mylabel: // Violation
47
break; [Link] Foo {
default: boolean bar(String x) {
break; return [Link]("2"); // Violation
} }
} }
} What is the cause of above violation?
What may be the cause of the above violation? a) Unneccessary Wrapper Object creation
a) The default label should be the last label in a switch b) Position literals first in String comparisons
statement c) Avoid instantiating String objects; this is usually
b)A non-case label was present in a switch statement unnecessary
c) Case with no break d) Do not instantiate a StringBuffer with a char
d) Non-static initializers are confusing
[Link] class Foo {
[Link] class Foo { Object bar;
public void bar() { // bar is data or an action or both?
int x = 2; void bar() { //Violation
x = x; //Violation }
} }
} Reason for the violation at the highlighted line in the
What is the java coding standard violation that may code snippet may be due to
be thrown on the above code at the highlighted line? a) The field name indicates a constant but its
a) Possible unsafe assignment to a non-final static modifiers do not
field in a constructor b) It is somewhat confusing to have a field name
b) Unused Local Variable matching the declaring class name
c) Consider simply returning the value vs storing it in c) It is somewhat confusing to have a field name with
local variable ''{0}'' the same name as a method
d) Avoid idempotent operations (like assigning a d) Non-static initializers are confusing
variable to itself)
[Link] class Foo extends Bar {
[Link] class Foo { int foo; //Violation
void bad() { }
List foo = getList(); Reason for the violation at the highlighted line in the
if ([Link]() == 0) {//Violation code snippet may be due to
// blah a) It is somewhat confusing to have a field name
} matching the declaring class name
} b) It is somewhat confusing to have a field name with
How the above violation be fixed regarding collection? the same name as a method
a) Perhaps ''{0}'' could be replaced by a local variable c) The field name indicates a constant but its
b)Position literals first in String comparisons modifiers do not
c) Substitute calls to size() == 0 (or size() != 0) with d)Non-static initializers are confusing
calls to isEmpty()
d) Avoid instantiating String objects; this is usually [Link] Phase in which code review tools / static
unnecessary analyzers are supposed to be used for best results
a) CUT phase
[Link] capability of the software product to protect b) System Testing
information and data so that unauthorized persons or c) Design
systems cannot read or modify them and authorized d) Integration Testing
persons or systems are not denied access to them is
termed as [Link] class SampleViolation {
a) Security public copyArray (int[] array) {
b) Efficiency int k =0;
c) Stability int length = [Link];
d) Usability Compliance int[] copy = new int [length];
for(int i = 1; i < length;i++) {
copy[i] = array[i]; // VIOLATION
48
} a) Above statement is correct only in case of large
while(k < length){ applications
copy[k] = array[k++]; // VIOLATION b) Above statement is correct only in case of small
} applications
} c) Above statement is correct in case of all
} applications
What is the reccomended procedure to fix the above d) Above statement is NOT correct in case of all
violations thrown on coping two arrays applications
a) Instead of copying data between two arrays, use
[Link] method which is efficient. [Link] is unit testing?
b) Do not add empty arrays a) Testing each unit of code in an isolation
c) Trailing Array Comma b) Testing code linewise
d) Avoid arraylength in loops c) Testing individual class of code in an isolation
d) None of the above
386.A form of static analysis based on the definition
and usage of variables [Link] is the purpose of Data Driven Test (DDT)
a) Profiling testing feature?
b) Data Flow Analysis a)editing of tests to change values in tool generated
c) peer review test cases
d) coverage analysis b) generation of more number of test so that method
can be tested with all possible values
[Link] Foo { void bar(Object x) { if (x != null && x c) Customization of test classes. It allows users to add
instanceof Bar)// Violation. any number of test classes
What may be the cause of the violation? d) Parameterization of tests with user defined test
a) Reduntant Modifiers data
b) Avoid chaining assignment operators
c) No need to check for null before an instanceof [Link] is the basic intention of performing unit
d) Avoid assignments in operands testing?
a) to avoid system testing
Topic: WUT b) to avoid system functionality testing
c) to detect problems early in the development stage
[Link] done unit testing can replace d) to avoid regression testing
system testing. Check the correctness
a) Yes, unit testing can replace system testing in all [Link] of the following is given highest priority
cases while fixing unit testing problems ?
b) Yes, unit testing can replace sys testing only if it is a) Assertion failures
tool based b) Exceptions
c) Yes, unit testing can replace sys testing only if it is c) Timeout errors
JUnit based testing d) No prioritization is required
d) No, unit testing can NOT replace system testing
[Link] is Code coverage analysis?
[Link] the correct statement related to unit a) Process of finding areas of a program NOT
testing exercised by a set of test cases
a) Systematically done unit testing can replace system b) Process of finding failed test cases
testing c) Process of finding areas of programs throwing
d) If code reviews & code inspections are done errors
thoroughly unit testing is NOT required d) Process of finding areas of program NOT exercised
b) Both Unit testing and System testing are required because of exceptions
as they compliment each other
c) In any case either system testing or unit testing is [Link] of the below statements is correct
required; but NOT the both regarding Unit testing?
a) Unit tests can be thrown away once the code is
[Link] testing is required even if code reviews & tested
code inspections are done thoroughly. Check the b) Unit testing is NOT required if system testing is
correctness done with effectiveness
49
c) Unit testing and System testing compliment each b) When a method is declared as "protected", it can
other only be accessed within the same package where the
d) Unit testing is required only in projects using Agile class is [Link] order to test a "protected" method
development process of a target class, you need to define your test class in
the same package as the target class.
[Link] is considered as fundamental unit of
coverage?
a) Type coverage c) When a method is declared as "protected", it can
b) Block coverage only be accessed within the same package where the
c) Package coverage class is defined we can write a test case inside target
d) Test coverage class.
d) None of the above
[Link] does calculating and tracking of metrics
help? [Link] are the benefits of Unit Testing?
a) Helps in reducing static analysis effort a) The modular approach during Unit testing
b) Helps to identify some of the symptoms of poor eliminates the dependency on other modules during
design testing.
c) Helps to avoid unit testing b) We can test parts of a project with out waiting for
d) None of the above the other parts to be available.
c) Designers can identify and fix problem immediately,
[Link] the code coverage for below code. as the modules are best known to them. This helps in
public void testAdd1() throws Throwable { fixing multiple problems simultaneously
int actual1 = [Link](338,18); d) All of the above
assertEquals(356, actual1);
int actual2 = [Link](36, 39); [Link] of the following statement is wrong about
assertEquals(75, actual2); unit testing
int actual3 = [Link](100, 8); a) Integration Test is a replacement of Unit testing
assertEquals(108, actual3); which will Catch all the Bugs Anyway.
} b) Cost of fixing a defect identified during the early
a) Full Coverage stages is less compared to that during later stage.
b) Partial coverage c) We can test parts of a project with out waiting for
c) Not Covered the other parts to be available
d) None of the above d) Designers can identify and fix problem
immediately, as the modules are best known to them.
[Link] of the following statement is correct with This helps in fixing multiple problems simultaneously
respect to private method in Unit Testing ?
a) Private methods can't be tested during unit testing [Link] is meant by Code Coverage in Unit Testing ?
b) When a method is declared as "private", it can only a) A code coverage tool simply keeps track of which
be accessed within the same class. So there is no way parts of your code get executed and which parts do
to test a "private" method of a target class from any not.
test class. So we can write a test case inside target b) A code coverage tool simply keeps track of pass and
class failure scenario of test cases.
c) When a method is declared as "private", it can only c) A code coverage tool simply keeps track of which
be accessed within the same class. So there is no way parts of your code has private and protected method.
to test a "private" method of a target class from any d) None of the above
test class. You have to perform unit testing manually.
Or you have to change your method from "private" to [Link] a Unit testing framework will be helpful for
"protected". Unit Testing
d) None of the above a) It helps to skip unit testing and do functional testing
directly so as to reduce effort
[Link] of the following statement is correct with b)It helps to simplify the process of unit testing by
respect to protected method ? reusable set of libraries or classes that have been
a) Protected methods can not be tested during unit developed for a wide variety of languages
testing c) which helps to test values with boundary conditions
d) None of the above
50
a) public void testDivide1() throws Throwable { int
[Link] is Data Driven Testing in Unit Testing ? actual1 = [Link](1, -2147483648);
a) It is a test approach to test private method in the assertEquals(1, actual1); int actual2 =
class [Link](-2147483648, 1); assertEquals(1,
b) It is single test to verify many different test cases by actual2); }
driving the test with input and expected values from b) Test case can't be written since it is static method
an external data source c) Test case can't be written since it is public method
c) It is a test approach to test protected method in the d) None of the above
class
d) It is a test approach to test values with boundary [Link] a test case can be written for this method ?
conditions public static boolean startsWith(String str,String
match){
[Link] of the below statements are true about for (int i= 0; i < [Link](); ++i) {
Data Driven Testing in Unit Test? if([Link](i)!= [Link](i))
1) all input data and expected results for your return false;
automated tests are kept in one place, which makes it }
easier to maintain test cases return true;
2)you can also execute expressions specified in cells of }
the processed storage (for example, your storage can a) public void testStartsWith1() throws Throwable
contain the value of 5+5) { boolean actual1 =
3)After first failure test case remaining test cases will [Link]("853956.85395645", "d R0");
not be executed assertEquals(false, actual1); boolean actual2 =
a) Both 1 & 2 [Link]("853956.85395645", (String)
b) Both 1 & 3 null); assertEquals(true, actual2); }
c) Both 2 & 3
d) All three statements b) public void testStartsWith1() throws Throwable
{ boolean actual1 =
[Link] to write a test case for the method add in [Link]("853956.85395645", "d R0");
the below class Sample. assertNotNull(false, actual1); boolean actual2 =
[Link]("853956.85395645", (String)
a) public class Sample { private int addInteger(int i, null); assertNotNull(true, actual2); }
int j){ int sum; sum=i+j; return sum; } }
b) Private methods can't be tested during unit testing c)Test case can't be written since it is static method
Test case can be written inside target class itself d) Test case can't be written since it is public method
c) Unit testing needs to be done either manually or
test case can be written by changing access modifier [Link] class Student { public void setAge(int age) {
"private" to "protected" [Link] = age;
d) None of the above }}
How the case can be written for the above bean class
[Link] int addInteger(int i, int j){ int sum; method?
sum=i+j; return sum; } a) No need to write a test case for bean class
How a test case can be written for this method? methods
a) Protected methods can not be tested during unit b) public void testSetAge1() throws Throwable
testing { Student student = new Student(); [Link](0);
b) Test case can be written by defining the test class in [Link](1); [Link](-1);
the same package as the target class. [Link](2147483647); [Link](-
c) Since protected methods can't be accessed outside 2147483648); }
the package unit testing needs to be done either c) Bean class methods can not be tested during unit
manually or test case can be written by changing testing
access modifier "protected" to "public" d) None of the above
d) None of the above
[Link] class TestDb {
[Link] static int Divide (int i1, int i2) { return public String readABC(Connection c,String
i1/i2; } table_name) throws SQLException{
How a test case can be written for this method ? Statement stm=[Link]();
51
ResultSet rs=[Link]("select a a) Test case is not required as there is no functionality
from"+table_name); in this method affected by external calls
int a=0; b) Stubs can be used to write test cases
a=[Link]("a"); c) Data Driven Testing can be used to write test cases
String result; d) None of the above
result =" result "+ a ;
return result; [Link] of the following is a framework for Java
} Unit testing ?
} 1 JUnit 2 GUnit 3 NUnit 4 Unit++
How test case can be written for the above method?
a) Test case can't be written since it has Connection [Link] identify Java Unit testing tools
object as a parameter 1) JDeveloper 2) JTest 3) WiproUT 4)JUnit
b) Object mocking can be used to write test cases
c) Data Driven Testing can be used to write test cases 2,3,4
d) None of the above 1,2,4
All 1,2,3 &4
[Link] class ConstructorExample { Only 4
public static long getFileLength (String path)
throws IOException { 419.
RandomAccessFile file = new RandomAccessFile public static int Divide (int i1, int i2) { return i1/i2; }
(path, "rw"); Please examine the below test case for the above
return [Link] (); method.
} public void testDivide1() throws Throwable {
} int actual1 = [Link](16,8);
How a test case can be written for this method ? assertEquals(2, actual1);
a) Test case can't be written for this method int actual2 = [Link](18, 1);
b) Stubs can be used to write test cases assertEquals(1, actual2); }
c) Data Driven Testing can be used to write test cases a) Given test case won't be executed since test case
d) None of the above can't be written for static method
b) First assert statement will be passed and second
[Link] static List getScores(String team_name) assert will be failed
throws SQLException { c) Both assert statement will be passed
_loggedCalls.add("getScores: " + team_name); d)Test case is not required for this method
prepare();
List list_scores = new ArrayList(); [Link], at what stage in the SDLC cycle Unit
Statement stmt = _connection.createStatement(); Testing tool is applicable?
ResultSet rs = stmt 1 CUT phase 2 Testing phase 3 Design phase
.executeQuery("SELECT * FROM SCORES WHERE 4 UAT phase
TEAM_NAME='"
+ team_name + "'"); [Link], Unit Testing tool is supposed to be used
while ([Link]()) { by ___________
int score = [Link]("SCORE"); 1 only Project Managers 2 All Developers 3 only
list_scores.add(new Integer(score)); Test Engineers 4 only Quality Analyst
}
return list_scores; [Link] the correct statement related to Unit
} Testing tool
How a test case can be written for this method ? It is a system functionality and regression testing tool
a) Test case can't be written for this method It is a system level control flow testing tool
b) Stubs can be used to write test cases It is a unit level black-box and white-box testing tool
c) Data Driven Testing can be used to write test cases It is a system level black-box and white-box testing
d) None of the above tool

[Link] static void addsample() [Link] is Function coverage in Unit Testing ?


{ int i,j,k; k=i+j;} Checks whether each function (or subroutine) in the
How test case can be written for the above method? program has been called
52
Checks whether each function (or subroutine) in the The given assertEquals() syntax is wrong
program has been returning values Test case will be failed in second assert statement
Checks whether each function (or subroutine) in the Parameters given to assertEquals() are wrong
program has been returned correct data type value
Checks whether each function (or subroutine) in the [Link] to write best test case for below method by
program returns null value "re-usability test logic" ?
public String getStudentName(Student student){
[Link] is Statement coverage in Unit Testing? return [Link]();
Has each node in the program been executed }
Checks whether each function (or subroutine) in the Test case can't be written since it has user defined
program has been called object
checks whether the requirements of each branch of It can be tested using Object Repository and Data
each control structure has been met as well as not Driven Testing
met Test case can be written with normal assertEquals()
checks whether each boolean sub-expression has TestCase can be written with assertNull()
evaluated both to true and false
[Link] to ensure condition coverage for below
[Link] is Decision coverage in Unit Testing? method ?
checks whether the requirements of each branch of public static divide ( int a, int b){
each control structure has been met as well as not if(b<=0)
met -------- some statement--------------
Has each node in the program been executed else()
Checks whether each function (or subroutine) in the --------some statement---------------
program has been called }
checks whether each boolean sub-expression has It should be tested with <= 0 values for a and any
evaluated both to true and false values for b.
It should be tested with <= 0 values for b and any
[Link] is Condition coverage in Unit Testing? values for a.
checks whether each boolean sub-expression has It should be tested with any values only for b.
evaluated both to true and false It can be tested with any values for a and b.
Checks whether each function (or subroutine) in the
program has been called [Link](boolean)
Has each node in the program been executed asserts that a given condition is true
checks whether the requirements of each branch of asserts that a given condition is null
each control structure has been met as well as not asserts that a given condition is false
met asserts that an object is null

[Link] is the default unit testing framework [Link](Object)


available in Java Eclipse IDE ? asserts that an object is null
1NUnit 2 C++Unit 3 JUnit 4 Cactus asserts that a given condition is true
asserts that two objects references the same object
[Link] static int add (int i1, int i2) { Asserts that a condition is false
return i1 + i2;
} [Link](Object, Object)
What would be the output for below test suite if add() asserts that two objects references the same object
has the above functionality ? asserts that an object is null
public void testAdd1() throws Throwable { asserts that a given condition is true
int actual1 = [Link](1,8); Asserts that a condition is false
assertEquals(9, actual1);
int actual2 = [Link](1, 8); [Link](boolean condition)
assertEquals(9, actual2); Asserts that a condition is false
int actual3 = [Link](0, 8); asserts that two objects references the same object
assertEquals(8, actual3); asserts that an object is null
} asserts that a given condition is true
All assert statements will be passed
53

Common questions

Powered by AI

The code contains a compilation error. The bitwise XOR operator (^) returns an integer value and cannot be directly used in an if statement as a boolean without comparison, causing a type mismatch. Therefore, option 'c' is correct since 'Compilation error occurs' .

The code will output 'Finally'. The finally block is executed even after the return statement in the try block .

Unit testing frameworks simplify the process by providing reusable libraries and support for various languages, facilitating consistent and efficient testing practices. They streamline the creation, execution, and verification of test cases .

Unit testing is essential because it facilitates early detection of issues, offers insights through modular testing without waiting for system availability, and helps identify specific areas of bugs, all of which code reviews and inspections might not reveal comprehensively. This remains true across all applications .

The code results in a compile-time error because 'while(i)' expects a boolean condition but is given an integer instead. Java does not inherently convert integers to boolean, so 'while(i)' is invalid .

The program will print 'Z'. The conditional statement 'if (bFlag = false)' assigns false to bFlag rather than comparing it, leading to else if check being false and the final else block gets executed .

The output of the code is '20'. The parameter x in method() hides the instance variable x. The operation 'x+=x;' doubles the value of the method's parameter, resulting in 20 when 10 is passed to method().

The output will be '6,6'. The XOR operator ^ between 2 (binary 0010) and 4 (binary 0100) results in 6 (binary 0110). Since XOR is commutative, (y ^ x) is the same as (x ^ y), both yielding 6 .

If run with no arguments, it will print only 'The end'. The absence of arguments makes args.length zero, so return is executed before attempting to print args[0], skipping the output of any argument but still executing finally .

Code coverage is crucial for unit testing as it ensures that all parts of the program are exercised by test cases, highlighting sections of the code that have not been tested, thus ensuring thorough validation and reducing potential areas of uncovered bugs .

You might also like