QUESTION NO : 1
QUESTION STATEMENT : What will happen when you attempt to compile and
run the following code?
public class Static
{
static
{
int x = 5;
}
static int x,y;
public static void main(String args[])
{
x--;
myMethod();
System.out.println(x + y + ++x);
}
public static void myMethod()
{
y = x++ + ++x;
}
}
CHOICES :
a) Compiletime error
b) prints : 1
c) prints : 2
d) prints : 3
e) prints : 7
f) prints : 8
CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. The above code will not give any compilation error.
Note that "Static" is a valid class name. Thus choice A is incorrect.
In the above code, on execution, first the static variables (x and y) will
be initialized to 0.
Then static block will be called and finally main() method will be called.
The execution of static block will have no effect on the output as it declares
a new variable (int x).
The first statement inside main (x--) will result in x to be -1.
After that myMethod() will be executed.
The statement "y = x++ + ++x;" will be evaluated to y = -1 + 1 and
x will become 1.
In case the statement be "y =++x + ++x", it would be evaluated to
y = 0 + 1 and x would become 1.
Finally when System.out is executed "x + y + ++x" will be evaluated
to "1 + 0 + 2" which result in 3 as the output.
Thus choice D is correct.
--------------------------------------------------------------------
QUESTION NO : 2
QUESTION STATEMENT : Which of the following is the last line of output,
when the following code is executed?
public class Test
{
public static void main(String args[])
{
int counter = 0;
outer: for(int i = 0; i < 4; ++i)
middle: for(int j = 0; j < 4; ++j)
inner: for(int k = 0; k < 4; ++k)
{
System.out.println("Hello - " + ++counter);
if((k % 4) == 0)
break outer;
}
}
}
CHOICES :
a) Hello - 1
b) Hello - 4
c) Hello - 0
d) None of the above
CORRECT ANSWER : a
EXPLANATION :
A is correct. Since 0 mod 4 is 0, the inner loop is only executed once and then
break will be called which completes the main method and thus the final line
of output would be Hello - 1.
--------------------------------------------------------------------
QUESTION NO : 3
QUESTION STATEMENT : What will happen if you attempt to compile and
run the following code?
public class MyClass
{
public static void main(String args[])
{
Integer ten = new Integer(10);
System.out.println(ten);
}
}
CHOICES :
a) 10
b) Compilation error
c) Error: can't convert java.lang.Integer
d) None of the above
CORRECT ANSWER : a
EXPLANATION :
A is correct answer. What actually happens is when System.out.println(ten);
is executed, the toString() method of Integer class is invoked which returns
the String representation of Integer which in this case is 10. Thus 10 is printed.
--------------------------------------------------------------------
QUESTION NO : 4
QUESTION STATEMENT : What will happen when you attempt to compile and
run the following code?
public class MyClass
{
int i = 99;
public static void main(String argv[])
{
MyClass mc = new MyClass();
mc.myMethod();
}
void myMethod()
{
int i;
System.out.println(i);
}
}
CHOICES :
a) The value 99 will be output
b) The value 0 will be output
c) Compile time error
d) Run time error
CORRECT ANSWER : c
EXPLANATION :
C is correct. You will get a compile time error indicating that variable i may
not have been initialized. The class level variable i will be shadowed by the
method level version. Method level variables do not get any default initialization.
--------------------------------------------------------------------
QUESTION NO : 5
QUESTION STATEMENT : From code that has no current "this"
reference, how can you create an instance of an inner class?
CHOICES :
a) Outer.Inner i = new Outer().new Inner();
b) Without a "this" reference an inner class cannot be created.
c) Outer.Inner i = Outer().new new Inner();
d) Outer i = Outer.new().Inner();
CORRECT ANSWER : a
EXPLANATION :
A is correct. In this situation the creation of instance of outer class is combined
with the inner class instance creation. With "this" reference the
outer class instance is not required.
--------------------------------------------------------------------
QUESTION NO : 6
QUESTION STATEMENT : What will be the result of executing the following
code?
// Filename; SuperclassX.java
package packageX;
public class SuperclassX
{
protected void superclassMethodX()
{
}
int superclassVarX;
}
// Filename SubclassY.java
1. package packageX.packageY;
2.
3. public class SubclassY extends SuperclassX
4. {
5. SuperclassX objX = new SubclassY();
6. SubclassY objY = new SubclassY();
7. void subclassMethodY()
8. {
9. objY.superclassMethodX();
10. int i;
11. i = objY.superclassVarX;
12. }
13. }
CHOICES :
a) Compilation error at line 5
b) Compilation error at line 9
c) Runtime exception at line 11
d) None of these
CORRECT ANSWER : d
EXPLANATION :
D is correct. When no access modifier is specified for a member, it is only
accessible by another class in the package where its class is defined. Even
if its class is visible in another package, the member is not accessible there.
In the question above the variable superclassVarX has no access modifier specified
and hence it cannot be accessed in the packageY even though the class SuperclassX
is visible and the protected method superclassMethodX() can be accessed. Thus
the compiler will raise an error at line 11.
--------------------------------------------------------------------
QUESTION NO : 7
QUESTION STATEMENT : Given the following classes, which of the following
will compile without error?
interface IFace{}
class CFace implements IFace{}
class Base{}
public class ObRef extends Base
{
public static void main(String argv[])
{
ObRef ob = new ObRef();
Base b = new Base();
Object o1 = new Object();
IFace o2 = new CFace();
}
}
CHOICES :
a) o1 = o2;
b) ob = b;
c) b = ob;
d) o1 = b;
CORRECT ANSWER : acd
EXPLANATION :
A, C and D are correct. A is correct as every class extends Object by default
and child class object can be assigned to parent class without casting. B is
incorrect as in this case parent class is assigned to child class(without casting)
which will give compilation error. C is correct as child class can be assigned
to parent class without casting. Similar to A , D is also correct (an object
of class implementing an interface can be assigned to interface variable).
--------------------------------------------------------------------
QUESTION NO : 8
QUESTION STATEMENT : Which of the following are valid statements?
CHOICES :
a) System.out.println(1+1);
b) int i= 2 + '2';
c) String s= "on" + 'one';
d) byte b = 255;
CORRECT ANSWER : ab
EXPLANATION :
A and B are correct. Option C is not valid because single quotes are used to
indicate a character constant and not a string. Option D will not compile because
255 is out of the range of a byte. The range of byte variables is -128 to 127.
--------------------------------------------------------------------
QUESTION NO : 9
QUESTION STATEMENT : What will happen when you attempt to compile and
run the following code?
class Background implements Runnable
{
int i = 0;
public void run(int i)
{
while(true)
{
i++;
System.out.println("i = " + i);
}
}
}
CHOICES :
a) It will compile and the run method will print out the increasing value of
i.
b) It will compile and calling start will print out the increasing value of
i.
c) The code will cause an error at compile time.
d) Compilation will cause an error because while cannot take a parameter of
true.
CORRECT ANSWER : c
EXPLANATION :
C is correct as run() method of Runnable interface doesn't take any parameter.
Thus the condition of implementing the Runnable interface is not satisfied(the
run method is not implemented).
--------------------------------------------------------------------
QUESTION NO : 10
QUESTION STATEMENT : Which of the following statements are true about
a variable created with the static modifier?
CHOICES :
a) Once assigned the value of a static variable may not be altered.
b) A static variable created in a method will keep the same value between calls.
c) Only one instance of a static variable will exist for any amount of class
instances.
d) The static modifier can only be applied to a primitive value.
CORRECT ANSWER : c
EXPLANATION :
C is correct. A is incorrect as the value of static variable can be changed
after it's assigned. B is incorrect as it may be true in VB but not in Java.
C is correct, as static variable is same for every instance of class. D is incorrect
as static can be applied to Object types also.
--------------------------------------------------------------------
QUESTION NO : 11
QUESTION STATEMENT : What results from compiling and running the following
code fragment?
Byte myByte = new Byte("111");
if(myByte.toString() == myByte.toString())
System.out.println("True");
else
System.out.println("False");
CHOICES :
a) Compilation error, toString() is not available for Byte.
b) Prints "True"
c) Prints "False"
d) None of the above
CORRECT ANSWER : c
EXPLANATION :
C is correct. The toString() method returns a String object representing this
Byte's value. Please note that operator == checks for the memory address of
two object references being compared and not their value. The toString() method
will create a new object each time it is called. Thus else statement will be
executed and False will be printed out.
--------------------------------------------------------------------
QUESTION NO : 12
QUESTION STATEMENT : What will be the result when you attempt to compile
and run the following code?
public class MyClass
{
public static void main (String args [])
{
/*
if (true)
{
Test5 = new test5();
System.out.println("Done the test");
}
/* ... A comment */
System.out.println ("The end");
}
}
CHOICES :
a) Prints out "Done the test" and nothing else.
b) Program produces no output but terminates correctly.
c) Program does not terminate.
d) The program will not compile.
e) The program generates a runtime exception.
f) The program prints out "The end" and nothing else.
CORRECT ANSWER : f
EXPLANATION :
F is correct. Carefully look at the comments(/*... */). The comment starts before
"if" loop and ends after the loop. Thus only "The end "
will be printed.
--------------------------------------------------------------------
QUESTION NO : 13
QUESTION STATEMENT : What will happen when you compile and run the following
code?
import java.io.*;
abstract interface Test1
{
public void test() throws IOException;
}
public class Test implements Test1
{
public void test(){}
}
CHOICES :
a) Compilation Error
b) Runtime Exception
c) Compiles without error
d) None of these
CORRECT ANSWER : c
EXPLANATION :
C is correct. First of all please note that interface may or may not have abstract
key word. The methods of interface also may or may not have abstract key word.
Then the class implementing the interface should be abstract if it doesn't define
all the methods. The method implemented in the implementing class need not throw
an Exception even if the method in the interface throws an exception.
--------------------------------------------------------------------
QUESTION NO : 14
QUESTION STATEMENT : Which of the following lines will print false?
1. public class MyClass
2. {
3. static String s1 = "I am unique!";
4. public static void main(String args[])
5. {
6. String s2 = "I am unique!";
7. String s3 = new String(s1);
8. System.out.println(s1 == s2);
9. System.out.println(s1.equals(s2));
10. System.out.println(s3 == s1);
11. System.out.println(s3.equals(s1));
12. System.out.println(TestClass.s4 == s1);
13. }
14. }
15.
16. class TestClass
17. {
18. static String s4 = "I am unique!";
19. }
CHOICES :
a) Lines 10 and 12
b) Line 12 only
c) Line 8 and 10
d) None of these
CORRECT ANSWER : d
EXPLANATION :
D is correct. Only line 10 will print false. Strings are immutable objects.
That is, a string is read only once the string has been created and initialized,
and Java optimizes handling of string literals; only one anonymous string object
is shared by all string literals with the same contents. Hence in the above
code the strings s1, s2 and s4 refer to the same anonymous string object, initialized
with the character string: "I am unique!". Thus s1 == s2 and TestClass.s4
will both return true and obviously s1.equals(s2) will return true. But creating
string objects using the constructor String(String s) creates a new string,
hence s3 == s1 will return false even though s3.equals(s1) will return true
because s1 and s3 are referring to two different string objects whose contents
are same.
--------------------------------------------------------------------
QUESTION NO : 15
QUESTION STATEMENT : What will be the result of executing the following
code?
1. boolean a = true;
2. boolean b = false;
3. boolean c = true;
4. if (a == true)
5. if (b == true)
6. if (c == true) System.out.println("Some things are true in this world");
7. else System.out.println("Nothing is true in this world!");
8. else if (a && (b = c)) System.out.println("It's too confusing
to tell what is true and what is false");
9. else System.out.println("Hey this won't compile");
CHOICES :
a) The code won't compile
b) "Some things are true in this world" will be printed
c) "Hey this won't compile" will be printed
d) None of these
CORRECT ANSWER : d
EXPLANATION :
D is correct. This is a very good question to test the concepts of execution
flow in case of if conditions. The rule for attaching else statements with if
conditions is the same as attaching close brackets with open brackets. A close
bracket attaches with the closest open bracket, which is not already closed.
Similarly an else statement attaches with the closest if statement, which doesn't
have an else statement already, attached to it. So the else statement at line
7 attaches to the if statement at line 6. The else statement at line 8 attaches
to the if statement at line 5. The else statement at line 9 attaches to the
if statement at line 8.
Now let's look at the execution. At line 4 since a is equal to true the execution falls to line 5. At line 5 since b is not true the execution goes to the corresponding else statement at line 8. Now it evaluates the condition inside the if statement. Please note here that an assignment statement also has a value equal to the value being assigned, hence (b = c) evaluates to true and subsequently a && (b = c) evaluates to true and "It's too confusing to tell what is true and what is false" will be printed. Hence the correct answer is choice D.
--------------------------------------------------------------------
QUESTION NO : 16
QUESTION STATEMENT : What will be the result of executing the following
main() method?
public static void main(String[] args)
{
int x = 10;
int y;
if (x < 100) y = 100;
if (x >= 100) y = x * 10;
System.out.println("The y is: " + y);
}
CHOICES :
a) The code will compile with a warning that variable y might not have been
initialized
b) The code will compile without any warnings
c) Whether the code will compile or not will depend on the if conditions
d) None of these
CORRECT ANSWER : d
EXPLANATION :
D is correct. The code will not compile raising an error that variable y might
not have been initialized. Local variables are not initialized when they are
instantiated at method invocation. The compiler reports an error if a local
variable is being used uninitialized.
--------------------------------------------------------------------
QUESTION NO : 17
QUESTION STATEMENT : What results from running the following code?
public class XOR
{
public static void main(String args[])
{
byte a = 13; // 00001101 binary
byte b = 10; // 00001010 binary
a = (byte)(a ^ b);
System.out.println("Value is - " + a);
}
}
CHOICES :
a) prints : Value is - 130
b) prints : Value is - 23
c) prints : Value is - 3
d) prints : Value is - 7
CORRECT ANSWER : d
EXPLANATION :
D is correct. The "^" operator represents bitwise XOR operation which
produces the result as below
a 00001101
b 00001010
a ^ b 00000111
Please note that the result contains 1 bit where exactly one of the operands
has 1 bit, otherwise it contains 0 bit(where either both the operands have 0
bits or both have 1 bits). The result is the binary representation of 7, hence
D is the correct choice.
--------------------------------------------------------------------
QUESTION NO : 18
QUESTION STATEMENT : Which one is true about the application below?
1. class StaticClass
2. {
3. static int a = 7;
4. static {a += 5;}
5.
6. public static void main(String args[])
7. {
8. System.out.prinltn("a = " + a);
9. }
10. static {a /= 3;}
11. }
CHOICES :
a) The code will not compile as method names and return types are missing on
lines 4 and 10.
b) The code will not compile as you can have at the most only one static initializer.
c) The code runs successfully and prints 4.
d) The code runs successfully and prints 12.
e) The code runs successfully and prints 7.
CORRECT ANSWER : c
EXPLANATION :
C is correct. Multiple static initializers are legal. All static initializers
code is executed at the class load time, so even before main() is called the
value of static variable is initialized to 7, then jumped to 12(by adding 5)
and then to 4(dividing by 3). Hence C is correct.
--------------------------------------------------------------------
QUESTION NO : 19
QUESTION STATEMENT : Which of the statements below is true?
CHOICES :
a) Object references can be converted in assignments but not in method calls.
b) Object references can be converted in both method calls and assignments,
but the rules governing these conversions are very different.
c) Object references can never be converted.
d) Object references can be converted in both method calls and assignments,
and the rules governing these conversions are identical.
e) Object references can be converted in method calls but not in assignments.
CORRECT ANSWER : d
EXPLANATION :
D is correct. Object references can be converted. The same rules applies in
method call and assignment for conversion.
--------------------------------------------------------------------
QUESTION NO : 20
QUESTION STATEMENT : What will be printed out if you attempt to compile
and run the following code?
int i = 9;
switch (i)
{
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
CHOICES :
a) default
b) default, zero
c) Error : default clause not defined
d) No output displayed
CORRECT ANSWER : b
EXPLANATION :
B is correct. Although it is normally placed last, the default statement does
not have to be the last item as you fall through the case bock. Since there
is no case label found matching the expression, the default label is executed
and the code continues to fall through until it encounters a break statement.
--------------------------------------------------------------------
QUESTION NO : 21
QUESTION STATEMENT : What will be the result of attempting to compile
and run the following code ?
1 import java.awt.*;
2 public class TestFrame extends Frame
3 {
4 Button firstOne = new Button("First");
5 Button secondOne = new Button("Second");
6 public TestFrame()
7 {
8 add(firstOne,BorderLayout.NORTH);
9 add(firstOne,BorderLayout.NORTH);
10 add(secondOne,BorderLayout.NORTH);
11 setLayout(new FlowLayout());
12 setSize(400,400);
13 setVisible(true);
14 }
15 public static void main(String args[])
16 {
17 TestFrame tf = new TestFrame();
18 }
19 }
CHOICES :
a) Exception is raised - a component cannot be added twice to a container.
b) Exception is raised - a component cannot be added to a region which is already
occupied by other.
c) The Frame comes up and only the button with label "Second" occupying
the North region.
d) The Frame comes up and both the buttons appear at their preferred sizes.
CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. There is no rule that a component cannot be added to
a container more than once. It will be added once, only the last add() statement
will have effect. If a component is added to a region, which is already occupied
by another, the last one added will hide the previous ones. The Frame would
have come up showing only the button with label "Second" occupying
the North region. But since we have set the layout to FlowLayout finally, the
frame arranges both the buttons in a row honoring their preferred sizes.
--------------------------------------------------------------------
QUESTION NO : 22
QUESTION STATEMENT : Given the following code, what test would you need
to put in place of the comment line "//place test here" to result
in an output of "Equal"?
public class EqTest
{
public static void main(String argv[])
{
EqTest e = new EqTest();
}
EqTest()
{
String s = "Java";
String s2 = "java";
//place test here
{
System.out.println("Equal");
}
else
{
System.out.println("Not equal");
}
}
}
CHOICES :
a) if(s == s2)
b) if(s.equals(s2)
c) if(s.equalsIgnoreCase(s2))
d) if(s.noCaseMatch(s2))
CORRECT ANSWER : c
EXPLANATION :
C is correct. String comparison is case sensitive so using the equals string
method will not return a match. Using the == operator just compares where memory
address of the references and noCaseMatch was just something made up to give
a fourth slightly plausible option.
--------------------------------------------------------------------
QUESTION NO : 23
QUESTION STATEMENT : Consider the following piece of code and select
the correct statement from the following.
1. String s = new String("abcdefgh");
2. s.replace('d', 'q');
3. System.out.println(s);
CHOICES :
a) The code fails to compile, reporting an error at line 2. Strings are immutable,
and therefore a replace() method is meaningless.
b) The code compiles correctly, and displays the text "abcqefgh".
c) The code compiles correctly, and displays the text "abcdefgh".
d) The code compiles, but an exception is thrown when line 2 is executed.
e) The code compiles, but an exception is thrown at line 3.
CORRECT ANSWER : c
EXPLANATION :
C is correct. Strings are immutable, and so they cannot be modified. However,
as the JDK API documentation will show, the String class has a replace() method,
so answer A is incorrect. If line 2 read as "s = s.replace('d', 'q')"
then a new object would be created and assigned to s. The value of this new
String object would be "abcqefgh". However, as line 2 is presented,
no new object is created, and so 's' remains unchanged.
--------------------------------------------------------------------
QUESTION NO : 24
QUESTION STATEMENT : Before which of the following can the keyword "synchronized"
be placed, without causing a compile error?
CHOICES :
a) class methods
b) instance methods
c) any block of code within a method
d) variables
e) a class
CORRECT ANSWER : abc
EXPLANATION :
A, B and C are correct. Variables and classes cannot be synchronized. Any code
block within a method can be synchronized by enclosing it in {}.
--------------------------------------------------------------------
QUESTION NO : 25
QUESTION STATEMENT : In a thread, the wait() method must be called inside
which of the following:
CHOICES :
a) A while() loop
b) The run() method
c) synchronized code
d) The constructor
e) It doesn't matter where the wait() is called from.
CORRECT ANSWER : c
EXPLANATION :
C is correct. The wait() method can only be called inside synchronized code.
Please refer to the Java Language Specification for details.
--------------------------------------------------------------------
QUESTION NO : 26
QUESTION STATEMENT : What is displayed when the following piece of code
is executed:
1. String val = null;
2. int x = Integer.parseInt(val);
3. System.out.println(x);
CHOICES :
a) 0
b) null
c) A NumberFormatException is thrown at line 2.
d) Nothing is displayed
CORRECT ANSWER : c
EXPLANATION :
C is correct. An exception is thrown because the string is null, and can therefore
not be parsed into an integer.
--------------------------------------------------------------------
QUESTION NO : 27
QUESTION STATEMENT : What will be the result of compiling and executing
the following code?
1 import java.awt.*;
2 public class TestGrid extends Frame
3 {
4 public TestGrid()
5 {
6 GridLayout gout=new GridLayout();
7 setLayout(gout);
8 add(new Button("1"));
9 add(new Button("2"));
10 add(new Button("3"));
11 add(new Button("4"));
12 add(new Button("5"));
13 add(new Button("6"));
14 pack();
15 gout.setRows(2);
16 setVisible(true);
17 }
18 public static void main(String args[])
19 {
20 TestGrid tf = new TestGrid();
21 }
22 }
CHOICES :
a) Compiles and runs without error. All the buttons appear in a single row.
b) Compiles and runs without error. All the buttons appear in a single column.
c) Will not compile - GridLayout does not have a no argument constructor.
d) Compiles and runs without error. The buttons appear in two rows.
CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. GridLayout does have a no argument constructor which
creates a grid layout with a default of one column per component, in a single
row. The setRows() method is used to set the number of rows in the layout to
the specified value. But it does not work here since it is used after a call
to the pack() method.pack() causes the frame to be sized to fit the preferred
size and layouts of its components. If we move the pack() statement after setRows(),
the buttons will appear in two different rows.
--------------------------------------------------------------------
QUESTION NO : 28
QUESTION STATEMENT : What will happen when you attempt to compile and
run the following code?
class MyParent
{
int x, y;
MyParent(int x, int y)
{
this.x = x;
this.y = y;
}
public int addMe(int x, int y)
{
return this.x + x + y + this.y;
}
public int addMe(MyParent myPar)
{
return addMe(myPar.x, myPar.y);
}
}
class MyChild extends MyParent
{
int z;
MyChild (int x, int y, int z)
{
super(x,y);
this.z = z;
}
public int addMe(int x, int y, int z)
{
return this.x + x + this.y + y + this.z + z;
}
public int addMe(MyChild myChi)
{
return addMe(myChi.x, myChi.y, myChi.z);
}
public int addMe(int x, int y)
{
return this.x + x + this.y + y;
}
}
public class MySomeOne
{
public static void main(String args[])
{
MyChild myChi = new MyChild(10, 20, 30);
MyParent myPar = new MyParent(10, 20);
int x = myChi.addMe(10, 20, 30);
int y = myChi.addMe(myChi);
int z = myPar.addMe(myPar);
System.out.println(x + y + z);
}
}
CHOICES :
a) 300
b) 240
c) 120
d) 180
e) Compilation error
f)
None of the above
CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. In the above code, MyChild class overrides the addMe(int
x, int y) method of the MyParent class. And in both the MyChild and MyParent
class, addMe() method is overloaded. There is no compilation error anywhere
in the above code.
On execution, first, the object of MyChild class will be constructed. Please note that there is a super() call from the constructor of MyChild class, which will call the constructor of MyParent class. This will cause the value of z variable of MyChild class to be 30 and x, y variables of MyParent class will become 10 and 20 respectively. The next statement will again call the constructor of MyParent class with same x and y values. This is followed by execution of addMe() method of MyChild class with x as 10, y as 20 and z as 30. Also x and y are inherited by MyChild class from the MyParent class. Thus in the addMe() method of the MyChild class, the value of this.x will be 10, this.y will be 20 and this.z will be 30. The return value of this method will be "10 + 10 + 20 + 20 + 30 + 30", which is equal to 120. Thus x will become 120.
This is followed by the invocation of the other addMe() method which takes object reference of the MyChild class. From this method, the method which was called earlier is invoked. This call is exactly the same as the earlier one. Thus the value of y will also be 120 like x.
Now the addMe() method of MyParent class is invoked. This method invokes another addMe() method of the same class. Its equivalent to the invocation of addMe(int x, int y) method with x as 10 and y as 20. Also the value of instance variables x and y of My Parent class is 10 and 20 respectively. The value of z will be evaluated to "10 + 10 + 20 + 20", which is equal to 60. Thus the value of x, y and z after all the invocations will be 120, 120 and 60 respectively. As a result of this finally, "120 + 120 + 60" which is equal to 300 will be printed. Thus A is the correct choice.
--------------------------------------------------------------------
QUESTION NO : 29
QUESTION STATEMENT : Consider the following piece of code and select
the correct statement(s).
1. public class Test
2. {
3. static int x;
4. public static void main(String [] args)
5. {
6. x = x + 1;
7. System.out.println("Value is " + x);
8. }
9. }
CHOICES :
a) The code fails to compile. The compiler complains that the variable x is
used before it is initialized.
b) The code compiles correctly and displays "Value is 1" when executed.
c) The code compiles correctly, but throws a NullPointerException at line 7.
d) The code fails to compile because the 'main' method is incorrectly declared.
CORRECT ANSWER : b
EXPLANATION :
B is correct. Member variables(variables inside class) are initialized to 0
at compile time, so x is correctly initialized.
--------------------------------------------------------------------
QUESTION NO : 30
QUESTION STATEMENT : Assume that the file "out" exists and
contains the string "XYZ". What will be the contents of "out"
after this program is executed?
1 import java.io.*;
2
3 public class OutputTest
4 {
5 public static void main(String args[]) throws IOException
6 {
7 File file=new File("out");
8 FileOutputStream fout1=new FileOutputStream(file);
9 FileOutputStream fout2=new FileOutputStream(file);
10 PrintWriter pw=new PrintWriter(fout1,true);
11 fout1.write('A');
12 fout2.write('B');
13 pw.println("CD");
14 fout1.close();
15 fout2.close();
16 pw.close();
17
18 }
19 }
CHOICES :
a) XYZ
b) XYZABCD
c) ABCD
d) BCD
CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. "BCD" will be the contents of the file after
this program runs. When we write into a file using FileOutputStream , it overwrites
the file if it already exists. So in this case, "XYZ" will be replaced
by 'A' when fout1 writes. After that, fout2 will overwrite the same file again.
Now the file contains 'B'. Now whatever is written using the PrintWriter pw
will get appended to 'B' and not overwritten. The reason is that pw is actually
connected to fout1 and hence the stream used is the same. Thus D is the correct
choice.
--------------------------------------------------------------------
QUESTION NO : 31
QUESTION STATEMENT : What will be printed to the standard output when
the following program is run and the Test button is pressed 3 times.
import java.awt.*;
import java.awt.event.*;
public class ActionTest extends Frame
{
public ActionTest()
{
Button test=new Button("Test");
add(test);
test.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Clicked");
Button b=(Button)e.getSource();
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Clicked again");
}
});
}
});
setSize(100,100);
setVisible(true);
setTitle("My Frame");
}
public static void main(String rgs[])
{
new ActionTest();
}
}
CHOICES :
a) Clicked
Clicked again
Clicked
Clicked again
Clicked
Clicked again
b) Clicked
Clicked
Clicked
c) Clicked
Clicked
Clicked again
Clicked
Clicked again
Clicked again
d) Clicked
Clicked again
CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. When the button is clicked for the first time, the
actionPerformed method is invoked and it prints "Clicked". In actionPerformed,
one more listener is registered with the button. So when the button is clicked
for the second time, the actionPerformed of both the listeners is invoked. So
it prints "Clicked" and then "Clicked again". Now one more
listener is registered with the button. So for the third time the button is
clicked, 3 actionPerformed methods are invoked - result is the printing of "Clicked"
by first listener,"Clicked again" by the second and "Clicked
again" by the third one. Thus C is the correct choice.
--------------------------------------------------------------------
QUESTION NO : 32
QUESTION STATEMENT : Which of the following statements is true with
regard to persistence?
CHOICES :
a) "Serializable" is a keyword within the Java language.
b) "Serializable" is an interface, which classes can implement.
c) "Serializable" is a class, which other classes can extend.
d) None of the above.
CORRECT ANSWER : b
EXPLANATION :
B is correct. Serializable is an abstract interface, which has no methods or
fields. To quote the JDK, it "serves only to identify the semantics of
being serializable".
--------------------------------------------------------------------
QUESTION NO : 33
QUESTION STATEMENT : Select the valid code fragments from the following
list.
CHOICES :
a) public transient static final int _FRAMEX = 850;
b) this("a", "b");
[assuming a constructor of the type xxx(String, String) exists for this class]
c) private transient static final int _FRAMEX = 850;
d) boolean b = 0;
CORRECT ANSWER : abc
EXPLANATION :
A, B and C are correct. Answer D is incorrect, because a boolean must be either
true or false (unlike C/C++ where a non-zero value is taken as true, and a 0
is taken as false). Answers A and C are correct - they are valid ways of declaring
integer variables. Answer B is correct - but only assuming that there is a constructor
for the class with the signature "xxx(String, String)".
--------------------------------------------------------------------
QUESTION NO : 34
QUESTION STATEMENT : The argument for a while() statement MUST be a
boolean.
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
A is correct. Unlike C/C++, in Java the argument MUST be a boolean value (or
an expression that returns a boolean result).
--------------------------------------------------------------------
QUESTION NO : 35
QUESTION STATEMENT : Given the following definition:
String s = null;
Which code fragment will cause an exception of type NullPointerException to be thrown?
CHOICES :
a) if ((s != null) & (s.length()>0))
b) if ((s != null) && (s.length()>0))
c) if ((s != null) | (s.length()>0))
d) if ((s != null) || (s.length()>0))
e) None of the above.
CORRECT ANSWER : acd
EXPLANATION :
A, C and D are correct. Here the statement s.length()>0, if executed will
throw NullPointerException. This question revolves around the short-circuit
logical operators(&& and ||). Answer A must be fully evaluated. This
is an AND operation, and if the LHS is true, then the RHS must be evaluated
for the expression to be true. B is incorrect as && is short circuit
operator. Since LHS is evaluated to be false, RHS need not be evaluated and
thus no exception will be thrown. Answer C will also be fully evaluated. Therefore,
since the LHS is true, the RHS must be evaluated. D is also correct as LHS is
evaluated to be false and thus RHS must be evaluated.
--------------------------------------------------------------------
QUESTION NO : 36
QUESTION STATEMENT : You create a Long object using the following:
Long val = new Long("11");
Which of the following will return the value of the object as a byte value?
CHOICES :
a) byte b = (byte)val;
b) byte b = val.getByte();
c) byte b = (byte)val.getValue();
d) byte b = val.byteValue();
e) None of the above.
CORRECT ANSWER : d
EXPLANATION :
D is correct. Answer A is incorrect, because it is attempting to cast an object
to a primitive.
--------------------------------------------------------------------
QUESTION NO : 37
QUESTION STATEMENT : What will happen if you compile/run the following
code?
1. public class MyClass
2. {
3. int maxElements;
4. void MyClass()
5. {
6. maxElements = 100;
7. System.out.println(maxElements);
8. }
9. MyClass(int i)
10. {
11. maxElements = i;
12. System.out.println(maxElements);
13. }
14. public static void main(String[] args)
15. {
16. MyClass a = new MyClass();
17. MyClass b = new MyClass(999);
18. }
19. }
CHOICES :
a) Prints 100 and 999.
b) Prints 999 and 100.
c) Compilation error at line 3, variable maxElements was not initialized.
d) Compilation error at line 16.
CORRECT ANSWER : d
EXPLANATION :
D is correct. As there is an overloaded constructor defined, the default constructor
(with No arguments) will not be provided by the compiler. Please note that void
MyClass() is a normal method and not the default constructor.
--------------------------------------------------------------------
QUESTION NO : 38
QUESTION STATEMENT : Which statements about garbage collection are true?
CHOICES :
a) You can directly free the memory allocated by an object.
b) You can directly run the garbage collector whenever you want.
c) The garbage collector informs your object when it is about to be garbage
collected.
d) The garbage collector runs in low-memory situations.
CORRECT ANSWER : cd
EXPLANATION :
C and D are correct. C is correct as a low priority thread running, informs
the object about GC. D is correct because JVM tries its best to run GC under
low memory situation. You can't force the garbage collection.
--------------------------------------------------------------------
QUESTION NO : 39
QUESTION STATEMENT : What will be the result of compiling and executing
the following code?
1 import java.awt.*;
2 import java.awt.event.*;
3 public class ActionTest extends Frame implements ActionListener
4 {
5 public ActionTest()
6 {
7 Button test=new Button("Test");
8 add(test);
9 test.removeActionListener(this);
10 TextArea textArea=new TextArea(10,10);
11 textArea.addActionListener(this);
12 setSize(100,100);
13 setVisible(true);
14 }
15 public void actionPerformed(ActionEvent e)
16 {
17 System.out.println(e.getID());
18 }
19 public static void main(String rgs[])
20 {
21 new ActionTest();
22 }
23
24 }
CHOICES :
a) Exception at Line 9.
b) Compiler error at Line 11.
c) Compiler error at Line 17.
d) Code compiles and runs without error.
CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. No exception is thrown at Line9 even though no listeners
have been registered with the Test button previously.removeActionListener will
not perform any action if no listeners are registered or the listener object
passed is null. There is no function named addActionListener in the TextArea
class though it is present in the TextField class. So the compiler gives an
error at Line 11. There is no error in Line 17, getID() is a function in the
class AWTEvent, which returns the event type as an integer.
--------------------------------------------------------------------
QUESTION NO : 40
QUESTION STATEMENT : We have the following organization of classes:
class Parent { }
class DerivedOne extends Parent { }
class DerivedTwo extends Parent { }
Which of the following statements is correct for the following expression?
Parent p = new Parent();
DerivedOne d1 = new DerivedOne();
DerivedTwo d2 = new DerivedTwo();
p = d1;
CHOICES :
a) Illegal both compile and runtime,
b) Legal at compile time, but fails at runtime,
c) Legal at compile and runtime
CORRECT ANSWER : c
EXPLANATION :
C is correct. A variable of type of parent class can always refer to an object
of it's child (derived) class. Here since DerivedOne extends Parent, it is perfectly
valid for the variable "p" to refer to an object of class DerivedOne.
--------------------------------------------------------------------
QUESTION NO : 41
QUESTION STATEMENT : In the following class, Which code must replace
the <<>> to finish the outerloop (control moves out of the outerloop)
?
class Loop
{
public static void main( String [] args)
{
int x = 0; int y = 0;
outer: for (x = 0; x < 100; x++)
{
middle: for (y = 0 ; y < 100 ; y++)
{
System.out.println("x = " + x + "; y = " + y);
if (y == 10)
{
<<>>
}
}
}
} //End of main()
} // End of class Loop
CHOICES :
a) continue middle;
b) break outer;
c) break middle;
d) continue outer;
e) none of these.
CORRECT ANSWER : b
EXPLANATION :
B is correct. The break at middle will only break the inner loop not the outer
loop. The continue statement are to revive a loop not to end.
--------------------------------------------------------------------
QUESTION NO : 42
QUESTION STATEMENT : What happens if the file "Ran.test" does
not yet exist and you attempt to compile and run the following code?
import java.io.*;
class Ran
{
public static void main(String[] args) throws IOException
{
RandomAccessFile out = new RandomAccessFile("Ran.test", "rw");
out.writeBytes("Ninotchka");
}
}
CHOICES :
a) The code does not compile because RandomAccessFile is not created correctly.
b) The code does not compile because RandomAccessFile does not implement the
writeBytes() method.
c) The code compiles and runs but throws an IOException because "Ran.test"
does not yet exist.
d) The code compiles and runs but nothing appears in the file "Ran.test"
that it creates.
e) The code compiles and runs and "Ninotchka" appears in the file
"Ran.test" that it creates.
CORRECT ANSWER : e
EXPLANATION :
E is correct. This code compiles and runs fine. RandomAccessFile implements
the DataOutput interface, so it does implement writeBytes(), among others. RandomAccessFile
creates the file if it does not yet exist.
--------------------------------------------------------------------
QUESTION NO : 43
QUESTION STATEMENT : If you supply a target object when you create a
new Thread, as in:
Thread t = new Thread(targetObject);
What test of instanceof does targetObject have to pass for this to be legal?
CHOICES :
a) targetObject instanceof Thread
b) targetObject instanceof Object
c) targetObject instanceof Applet
d) targetObject instanceof Runnable
e) targetObject instanceof String
CORRECT ANSWER : d
EXPLANATION :
D is correct. The target object for a Thread must implement Runnable, which
means it will pass the test: targetObject instanceof Runnable
--------------------------------------------------------------------
QUESTION NO : 44
QUESTION STATEMENT : What will the result of following code?
1. class MyClass
2. {
3. public static void main(String args[])
4. {
5. double a = 0.5;
6. int b = 0;
7. b = Math.ceil(a);
8. System.out.print(b);
9. b = Math.floor(a);
10. System.out.print(b);
11. b = Math.round(a);
12. System.out.print(b);
13. }
14. }
CHOICES :
a) Compilation error at line 7 and 9 only
b) Compilation error at line 11 only
c) The code will compile and run perfectly fine and 1 0 1 will be printed
d) The code will compile and run perfectly fine and 1 0 0 will be printed
e) None of these
CORRECT ANSWER : e
EXPLANATION :
E is correct. There will be a compilation error at line 7, 9 and 11. At line
7 and 9 because the return type for Math.ceil() and Math.floor() is double and
therefore an explicit cast is required to convert them into an int. Compilation
error at line 11 because the return type for Math.round() is long and therefore
an explicit cast is required to convert into an int. Choice C and D don't make
any sense. Hence E is the correct choice.
--------------------------------------------------------------------
QUESTION NO : 45
QUESTION STATEMENT : What will be the output when you compile and execute
the following program?
public class Base
{
private void test()
{
System.out.println(2^6);
}
static public void main(String[] a)
{
new Base().test();
}
}
CHOICES :
a) 0
b) 2
c) 32
d) Compilation Error. Incompatible type for ^. Can't convert int to boolean.
e) 8
f) 4
CORRECT ANSWER : f
EXPLANATION :
F is correct. The "^" operator provides bitwise XOR operation. 2^6
results in 4, hence E is correct.
--------------------------------------------------------------------
QUESTION NO : 46
QUESTION STATEMENT : Which of the following statements are true?
CHOICES :
a) An abstract method cannot be final
b) An abstract method cannot be static
c) An abstract method cannot be private
d) An abstract method must be specified inside an abstract class only
e) An abstract method cannot throw any exceptions
CORRECT ANSWER : abcd
EXPLANATION :
A, B, C and D are correct. Only E is incorrect as abstract method can throw
exceptions.
--------------------------------------------------------------------
QUESTION NO : 47
QUESTION STATEMENT : What will be the output when you compile and execute
the following program?
public class Base
{
private void test()
{
one:
for (int i = 0; i < 3; i ++)
{
two:
for(int j = 0; j < 3; j++)
{
if (i == 2)
continue two;
if ( j == 2)
continue one;
System.out.println("Values : " + i + "," + j);
}
}
}
static public void main(String[] a)
{
new Base().test();
}
}
CHOICES :
a) Values : 0,0
b) Values : 0,1
c) Values : 1,0
d) Values : 1,1
e) Values : 2,0
f) Values : 2,1
CORRECT ANSWER : abcd
EXPLANATION :
A, B, C and D are correct. The first continue statement breaks the loop for
i == 2, and the second continue statement breaks the loop for j == 2. Now since
i and j take values from 0 to 2, the only values of i and j for which the loop
executes are 0 and 1, therefore E and F are incorrect.
--------------------------------------------------------------------
QUESTION NO : 48
QUESTION STATEMENT : A monitor thread has executed wait() method. Which
of the following statements are true?
CHOICES :
a) Causes current thread to wait until another thread invokes the notify()
or notfyAll()
b) Monitor should call wait() on another object's thread to get control
c) wait() should only be called by a thread that is the owner of that object's
monitor.
d) This monitor will get control when some other thread interrupts, or a certain
amount of real time has elapsed.
CORRECT ANSWER : ac
EXPLANATION :
A and C are correct. A thread that calls wait() releases the virtual CPU; at
the same time, it releases the lock of that object (the object whose wait()
was called). This thread then enters a pool of waiting threads, which is managed
by the object whose wait() method got called. Now this thread gets a chance
to execute only when another thread ceases the lock of this object and calls
notify() or notifyAll() of this object. Thus A is correct. Now wait() and notify()
must be called in syschronized code, which means that the thread calling the
wait() or notify() method must first own the monitor (owning the monitor is
equivalent to having the lock) of that object, hence C is correct. Monitor is
an object that controls it's client threads as explained above, it never gets
control rather it just manages which thread gets a control of it and when (via
wait() and notify() methods), thus B and D are meaningless.
--------------------------------------------------------------------
QUESTION NO : 49
QUESTION STATEMENT : Consider the following code:
1. Object a = new Object();
2. String arr[] = new String[100];
3. Float f = new Float(3.14159f);
4.
5. a = arr;
6. a = arr[5];
7. f = a;
8. a = f;
Which line above will not compile?
CHOICES :
a) 5
b) 6
c) 7
d) 8
CORRECT ANSWER : c
EXPLANATION :
C is correct. Line 7 will not compile because changing an object to a float
is going down the hierarchy, therefore an explicit cast is needed.
--------------------------------------------------------------------
QUESTION NO : 50
QUESTION STATEMENT : What will be the result of compiling and running
the following program?
1 import java.io.*;
2
3 public class FileTest
4 {
5 public static void main(String args[]) throws IOException
6 {
7 InputStreamReader in=new InputStreamReader(new FileInputStream("abc"));
8 RandomAccessFile rf=new RandomAccessFile("abc","w");
9 rf.seek(rf.length());
10 rf.write(10);
11 rf.close();
12 }
13 }
CHOICES :
a) Compiler error in line 7.
b) Runtime exception in line 8.
c) Compiles and runs without error, data is added to the file.
d) Compiles and runs without error, no data is added to the file.
CORRECT ANSWER : b
EXPLANATION :
B is the correct choice. IllegalArgumentException in line 8 because the mode
argument for RandomAccessFile can be either "r" or "rw"
only. There is no error in line 7. The InputStreamReader reads bytes from the
FileInputStream and converts to characters. If the mode argument was "rw"
instead of "w", data would have been added to the file and C would
have been the correct choice.
--------------------------------------------------------------------
QUESTION NO : 51
QUESTION STATEMENT : How many locks does an Object have?
CHOICES :
a) One for each method
b) One for each synchronized block or method
c) 0
d) 1
e) 2
CORRECT ANSWER : d
EXPLANATION :
D is correct as an object has only one lock, which controls access to all synchronized
methods and synchronized blocks.
--------------------------------------------------------------------
QUESTION NO : 52
QUESTION STATEMENT : Which of the following expressions are legal?
CHOICES :
a) int a = 5; a = !a;
b) int a = 5; if(!(a > 2)) {}
c) int a = 5; a = ~a;
d) int a = 5; a = !(~a);
CORRECT ANSWER : bc
EXPLANATION :
B and C are correct. "!" is a valid operator only for a boolean, hence
A and D are incorrect. In B "!" operator is used on (a > 2) which
is a boolean operand. In C "~"(bitwise NOT) is used on a (an int)
and hence a valid expression.
--------------------------------------------------------------------
QUESTION NO : 53
QUESTION STATEMENT : What will happen if the following code is run through
an appletviewer?
import java.awt.*;
public class Visual extends java.applet.Applet
{
static Button b = new Button("TEST");
public void init()
{
add(b);
}
public static void main(String args[])
{
Frame f = new Frame("Visual");
f.setSize(300,300);
f.add(b);
f.setVisible(true);
}
}
CHOICES :
a) Displays an empty frame.
b) Displays a frame with a button covering the entire frame.
c) Displays a frame with a button large enough to accommodate its label.
d) Nothing is displayed.
CORRECT ANSWER : c
EXPLANATION :
C is correct. Since its run as an applet and not as standalone application,
the main() method will not be invoked. Applet by default uses Flow Layout, which
honors Button's preferred size.
--------------------------------------------------------------------
QUESTION NO : 54
QUESTION STATEMENT : What will be the result of compiling and executing
the following code?
1 import java.awt.*;
2 public class TestHide extends Frame
3 {
4 public TestHide()
5 {
6 Button first=new Button("First");
7 Button second=new Button("Second");
8 Button third=new Button("Third");
9
10 setLayout(new FlowLayout());
11 second.setVisible(false);
12 add(first);
13 add(second);
14 add(third);
15 pack();
16 setVisible(true);
17 }
18 public static void main(String args[])
19 {
20 TestHide tf = new TestHide();
21 }
22 }
CHOICES :
a) Exception in Line 11. Component cannot be made invisible before adding to
a container.
b) The 3 buttons appear in a single row from left to right.
c) The buttons first and third appear in a single row with a gap in between.
d) The buttons first and third appear in a single row with no gap in between.
CORRECT ANSWER : d
EXPLANATION :
D is the correct choice. There is no rule that a component cannot be made invisible
before adding to a container. Since it is invisible, it does not appear on the
frame. Only the components which are visible are laid out on the container.
Since the button second was already invisible, only the other two buttons are
arranged from left to right. If the button had been made invisible after the
frame was shown, the gap would have been there between the first and third buttons.
--------------------------------------------------------------------
QUESTION NO : 55
QUESTION STATEMENT : What will happen when you attempt to compile and
run the following code?
public class MyArray
{
public static void arrange(int[] array)
{
int length = array.length;
int half = length/2;
while( half>= 1)
{
for (int i = half; i<length; i++)
{
int temp = array[i];
int test = i;
while( test>= half && temp < array[test - half])
{
array[test] = array[test - half];
test -= half;
}
array[test] = temp;
}
half/=2;
}
}
public static void main(String args[])
{
int[] array = {2,3,1};
arrange(array);
for(int i=0; i<array.length; i++)
{
System.out.print(array[i]);
}
}
}
CHOICES :
a) Compiletime error
b) Runtime error
c) No output
d) Prints : 231
e) Prints : 123
f) Prints : 012
CORRECT ANSWER : e
EXPLANATION :
E is the correct choice. Arrays can be used as arguments of a user-defined method
exactly as any other type. However, since arrays in Java are actually hidden
references, the method can change the elements in the array.
In the above code, there will not be any compiletime or runtime error. Inside the main method, first an array is initialized and then its passed to the arrange method and finally the array is printed. The arrange method performs sorting (shell sort) on the array passed to it as an input. After the execution of arrange() method, the array is sorted. As stated earlier, since arrays in Java are actually hidden references, the method can change the elements in the array. Thus finally when array is printed, the sorted array will be printed which will have its elements as 1,2 and 3 in the order. Thus "123" will be the output of the above code.
--------------------------------------------------------------------
QUESTION NO : 56
QUESTION STATEMENT : Which of the following are valid ways to assign
the value of 5 to a variable of type "int" called testValue?
CHOICES :
a) int testValue = 0x5;
b) int testValue = (int)(2.1F + 3.4D);
c) int testValue = (octal)5;
d) int testValue = (0x0A >> 1);
e) int testValue = (0x0A >>> 1);
CORRECT ANSWER : abde
EXPLANATION :
A, B, D and E are correct. Answer A is correct, since "0x5" is the
hexadecimal representation of 5. Answer B is correct. The value of (2.1F + 3.4D)
is 5.5D (the float value is promoted to a double). However, when cast to type
"int", the value becomes 5. Answer C is incorrect, because "octal"
is not a valid keyword in Java. Answers D and E are also correct. The value
of 0x0A is decimal 10. Both operations shift right by 1 (which is the same as
dividing by 2). The >> and >>> operators yield the same result
when a number is positive.
--------------------------------------------------------------------
QUESTION NO : 57
QUESTION STATEMENT : What will be the output on compiling/running the
following code?
public class MyThread implements Runnable
{
String myString = "Yes ";
public void run()
{
this.myString = "No ";
}
public static void main(String[] args)
{
MyThread t = new MyThread();
new Thread(t).start();
for (int i=0; i < 10; i++)
System.out.print(t.myString);
}
}
CHOICES :
a) Compilation Error
b)
Prints : Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes and so on.
c) Prints : No No No No No No No No No No and so on.
d) Prints : Yes No Yes No Yes No Yes No Yes No and so on.
e) The Output cannot be determined.
CORRECT ANSWER : e
EXPLANATION :
E is correct. Please note that there will not be any compilation error when
the above code is compiled. Also note that calling start() method on a Thread
doesn't start the Thread. It only makes a Thread ready to be called. Depending
on the operating system and other running threads, the thread on which start
is called will get executed. In the above case it is not guaranteed that the
thread will be executed (i.e. run() method will be called), always before "for"
loop is executed. Thus the output cannot be determined.
--------------------------------------------------------------------
QUESTION NO : 58
QUESTION STATEMENT : What results from trying to compile and run the
following code? Assume that the argument passed represents a valid path and
file name for a file that doesn't presently exist.
import java.io.*;
class MyClass
{
public static void main(String args[])
{
MyClass myClass = new MyClass();
File myFile = myClass.createFile(args[0]);
}
File createFile(String name)
{
File myFile = new File(name);
return myFile;
}
}
CHOICES :
a) A new empty file with that name is created but not opened.
b) The current directory changes to that specified in name.
c) A new empty file with that name is created and opened.
d) None of the above.
CORRECT ANSWER : d
EXPLANATION :
D is correct. Creating a File object doesn't do anything to the file system.
Also please note that method createFile() is of class MyClass and not the "File"
class.
--------------------------------------------------------------------
QUESTION NO : 59
QUESTION STATEMENT : Which line of given program will throw FileNotFoundException,
given that the file MyFile.java doesn't exist in the local file system?
1. import java.io.*;
2. public class MyReader
3. {
4. public static void main ( String args[] )
5. {
6. try
7. {
8. FileReader fileReader = new FileReader("MyFile.java");
9. BufferedReader bufferedReader = new BufferedReader(fileReader);
10. String strString;
11. fileReader.close();
12.
13. while ( ( strString = bufferedReader.readLine()) != null )
14. {
15. System.out.println ( strString );
16. }
17. }
18. catch ( IOException ie)
19. {
20. System.out.println ( ie.getMessage() );
21. }
22.
23. }
24. }
CHOICES :
a) This program never throws FileNotFoundException
b) The line 11, fileReader.close() throws FileNotFoundException
c) At line 8, instantiation of FileReader object.
d) At line 9, while constructing the BufferedReader object
CORRECT ANSWER : c
EXPLANATION :
C is correct. While constructing the FileReader object, if the file is not found
in the file system the "FileNotFoundException" is thrown. If the input
stream is closed before reading, the stream throws IOException.
--------------------------------------------------------------------
QUESTION NO : 60
QUESTION STATEMENT : What will be the output when the following code
is compiled and run (Assuming written inside main)?
String s1 = new String("amit");
System.out.println(s1.replace('m','r'));
System.out.println(s1);
String s3 = "arit";
String s4 = "arit";
String s2 = s1.replace('m','r');
System.out.println(s2 == s3);
System.out.println(s3 == s4);
CHOICES :
a) arit
amit
false
true
b) arit
arit
false
true
c) amit
amit
false
true
d) arit
amit
true
true
CORRECT ANSWER : a
EXPLANATION :
A is correct. Since string class is immutable, s1 will remain "amit"
even after calling replace() methods on it. What actually happens is that a
new object is created on calling replace(). Comparing two strings with == operator
checks for memory address to which the object reference is referring to. Java
uses the concept of pooling. It maintains the pool of Java strings and when
a new string is created, it first checks if it already exists in memory. If
yes it picks it from the pool, that is what happening here.s2 and s4 points
to the same memory area and thus s3==s4 will return true.
--------------------------------------------------------------------
QUESTION NO : 61
QUESTION STATEMENT : What will happen if the following code is run as
a standalone application?
import java.awt.*;
public class Visual extends java.applet.Applet
{
static Button b = new Button("TEST");
public void init()
{
add(b);
}
public static void main(String args[])
{
Frame f = new Frame("Visual");
f.setSize(300,300);
f.add(b);
f.setVisible(true);
}
}
CHOICES :
a) Displays an empty frame.
b) Displays a frame with a button covering the entire frame.
c) Displays a frame with a button large enough to accommodate its label.
d) Nothing is displayed.
CORRECT ANSWER : b
EXPLANATION :
B is correct. Since its run as an application and not an applet init() method
will not be invoked. Frame by default uses Border Layout ,which by default places
the button to CENTRE (occupies whole space if no other component is present)
and ignores Button's preferred size.
--------------------------------------------------------------------
QUESTION NO : 62
QUESTION STATEMENT : What will be the result of executing the following
code?
// Filename; SuperclassX.java
package packageX;
public class SuperclassX
{
protected void superclassMethodX()
{
}
protected int superclassVarX;
}
// Filename SubclassY.java
1. package packageY;
2. import packageX.*;
3. public class SubclassY extends SuperclassX
4. {
5. SuperclassX objX = new SubclassY();
6. SubclassY objY = new SubclassY();
7. void subclassMethodY()
8. {
9. objY.superclassMethodX();
10. int i;
11. i = objX.superclassVarX;
12. }
13. }
CHOICES :
a) Compilation error at line 9
b) Compilation error at line 5
c) A runtime exception at line 11
d) None of these
CORRECT ANSWER : d
EXPLANATION :
D is correct. A subclass in another package can only access protected members
in the superclass via references of its own type or a subtype. In the question
above the class SubclassY defines two instance variables, one of its own type
(objY) and another of its superclass's type (objX). Hence there is no problem
in accessing the method superclassMethodX() at line 9 but there will be a compilation
error at line 11 as objX is not allowed to access any protected member of the
SuperclassX.
--------------------------------------------------------------------
QUESTION NO : 63
QUESTION STATEMENT : What will happen if you compile/run the following
code?
class MyClass
{
int x;
MyClass(int i)
{
x = i;
}
public static void main(String args[])
{
MyClass m1 = new MyClass(100);
MyClass m2 = new MyClass(100);
if(m1.equals(m2))
{
System.out.println("Both are equal");
}
else
{
System.out.println("Both are not equal");
}
}
}
CHOICES :
a) Compilation error: equals() method was not defined.
b) Compiles fine, runtime exception.
c) Both are equal.
d) Both are not equal.
CORRECT ANSWER : d
EXPLANATION :
D is correct. Since equals() method is not defined in MyClass, the equals()
method of Object class, the parent class will be used. The equals() method of
Object class returns true when two object references being compared, point to
the same memory area, which is same as the output of obj1 == obj2. Since m1
and m2 are two different object references, they point to different memory areas
and hence false will be returned by equals() and thus "Both are not equal"
will be printed.
--------------------------------------------------------------------
QUESTION NO : 64
QUESTION STATEMENT : What will happen if you run the following code
with: java test 1 2 3?
public class Test
{
static public void main(String[] args)
{
int counter = 0;
do
{
System.out.println(args[++counter]);
}
while (counter < args.length);
}
}
CHOICES :
a) This code causes compile time error.
b) This code compiles without errors and works fine.
c) This code always misses the last parameter passed to the program.
d) This code compiles without error but will throw a run time exception.
CORRECT ANSWER : d
EXPLANATION :
D is correct. The code will compile without error. In the System.out statement
first the value of counter is incremented before anything is printed. Thus first
thing to be printed will be the value of args[1] that will be the second command
line argument: 2. Then 3 should be printed as args[2] and finally args[3] should
be printed before the loop terminates. Since there is no fourth command line
argument args[3] will thrown ArrayOutOfBoundsException, a run time exception.
Had the args[counter++] statement be there, first args[counter] would have been
printed before counter is incremented. In that case all command line parameters
would be printed without any exception condition.
--------------------------------------------------------------------
QUESTION NO : 65
QUESTION STATEMENT : What will happen when you attempt to compile and
run the following code?
public class Test
{
int i = 0;
public static void main(String argv[])
{
Test t = new Test();
t.myMethod();
}
public void myMethod()
{
while(true)
{
try
{
wait();
}
catch (InterruptedException e)
{
}
i++;
}
}
}
CHOICES :
a) Compile time error, no matching notify within the method.
b) Compile and run but an infinite looping of the while method.
c) Compilation and run without any output.
d) Runtime Exception "IllegalMonitorStatException".
CORRECT ANSWER : d
EXPLANATION :
D is correct. The wait/notify protocol can only be used within code that is
synchronized. In this case calling code does not have a lock on the object(not
synchronized) and will thus cause an Exception at runtime.
--------------------------------------------------------------------
QUESTION NO : 66
QUESTION STATEMENT : class Parent
{
}
class Child extends Parent
{
public String getChild()
{
String name = "child";
return name;
}
public static void main(String argv[])
{
Parent p = new Child();
//Place your code here.....
}
}
What code placed after the comment //Place your code here..... will result in
calling the getChild() method resulting in the output of the string "child"?
CHOICES :
a) System.out.println(p.getChild());
b) System.out.println(p.name);
c) System.out.println((Parent)p.getChild());
d) System.out.println(((Child)p).getChild());
CORRECT ANSWER : d
EXPLANATION :
D is correct. The Parent type reference to the instance of the class Child needs
to be cast from Parent to Child to get access to its methods. The method invoked
depends on the object itself, not on the declared type. So, p.getChild() looks
for getChild() in the Parent class and there is no getChild() method in Parent
class, compile time error would be reported. But the call to ((Child)p).getChild()
will invoke the getChild() in the Child class.
--------------------------------------------------------------------
QUESTION NO : 67
QUESTION STATEMENT : In the following code, What code should be placed
after the comment //Here that will print out 5?
public class MyClass
{
public static void main(String argv[])
{
int x = 5;
//Here
}
}
CHOICES :
a) System.out.println(x++);
b) System.out.println(++x);
c) System.out.println(x);
d) System.out.println(x--);
e) System.out.println(--x);
CORRECT ANSWER : acd
EXPLANATION :
A,C and D are correct. Please note the difference between a.) x = ++i and b.)
x = i++. The statement a.) results in incrementing i first and then assigning
incremented i to x. While the b.) results in assignment of i to x first then
i will be incremented.
--------------------------------------------------------------------
QUESTION NO : 68
QUESTION STATEMENT : What will be output by the following code?
public class MyClass
{
public static void main(String argv[])
{
int i;
int j;
outer: for (i = 1; i < 3; i++)
inner: for(j = 1; j < 3; j++)
{
if (j == 2)
continue outer;
System.out.println("Value for i = " + i + " Value for j = "
+j);
}
}
}
CHOICES :
a) Value for i = 1 value for j = 1
b) Value for i = 2 value for j = 1
c) Value for i = 2 value for j = 2
d) Value for i = 3 value for j = 1
CORRECT ANSWER : ab
EXPLANATION :
A and B are correct. The statement "continue outer;" causes the code
to jump to the label outer and the "for loop" increments to the next
number.
--------------------------------------------------------------------
QUESTION NO : 69
QUESTION STATEMENT : What will be the result of executing the following
code?
1. int[] myArray[] = new int[10][10];
2. if (myArray[0][0] < 10)
3. {
4. System.out.println("good question");
5. }
CHOICES :
a) Compilation error at line 1
b) Runtime exception at line 2
c) "good question" will be printed
d) None of these
CORRECT ANSWER : c
EXPLANATION :
C is correct. While declaring a single dimension array we can either specify
the "[]" sign just after the data type or just after the array name,
but not at both the places. But if we are declaring a two dimensional array
we can do it the way shown in the question above. Now since the initialization
is complete there will be no error at compile time and no exceptions at runtime.
Hence "good question" will be printed.
--------------------------------------------------------------------
QUESTION NO : 70
QUESTION STATEMENT : Which of the following will compile correctly?
CHOICES :
a) short myshort = 99s;
b) String name = 'Good job done';
c) char c = 17c;
d) int z = 015;
CORRECT ANSWER : d
EXPLANATION :
D is correct. The short type is not declared with s as suffix. String variables
starts and ends with double quote (e.g."test").The char type is also
not suffixed with c.
--------------------------------------------------------------------
QUESTION NO : 71
QUESTION STATEMENT : Which of the following lines will print false?
1. public class MyClass
2. {
3. static String s1 = "I am unique!";
4. public static void main(String args[])
5. {
6. String s2 = "I am unique!";
7. String s3 = new String(s1);
8. System.out.println(s1 == s2);
9. System.out.println(s1.equals(s2));
10. System.out.println(s3 == s1);
11. System.out.println(s3.equals(s1));
12. }
13. }
CHOICES :
a) Line 8
b) Line 9
c) Line 10
d) Line 11
e) None of these
CORRECT ANSWER : c
EXPLANATION :
C is correct. Line 10 will print false. Strings are immutable objects. That
is, a string is read only once the string has been created and initialized,
and Java optimizes handling of string literals; only one anonymous string object
is shared by all string literals with the same contents. Hence in the above
code the strings s1 and s2 refer to the same anonymous string object, initialized
with the character string: "I am unique!". Thus s1 == s2 will return
true and obviously s1.equals(s2) will return true. But creating string objects
using the constructor String(String s) creates a new string, hence s3 == s1
will return false even though s3.equals(s1) will return true because s1 and
s3 are referring to two different string objects whose contents are same.
--------------------------------------------------------------------
QUESTION NO : 72
QUESTION STATEMENT : Which of the following statements are true in case
of Inner Classes?
CHOICES :
a) Inner classes cannot be marked private.
b) An instance of a top level nested class can be created without an instance
of its enclosing class.
c) A file containing an outer and an inner class will only produce one .class
output file.
d) To create an instance of a member class an instance of its enclosing class
is required.
CORRECT ANSWER : bd
EXPLANATION :
B and D are correct. A is incorrect as an Inner class can be private. C is incorrect
as an inner class gets put into its own .class output file, using the format
Outer$Inner.class. A top level nested class is a static class and thus does
not require an instance of the enclosing class. A member class is an ordinary
non static class and thus an instance of its enclosing class is required.
--------------------------------------------------------------------
QUESTION NO : 73
QUESTION STATEMENT : If you run the following code from the directory
c:\dir. What do you expect the output to be ?
import java.io.*;
class Path
{
public static void main(String[] args) throws Exception
{
File file = new File("Test.test");
System.out.println(file.getPath());
}
}
CHOICES :
a) Test.test
b) dir\Test.test
c) c:\dir\Test.test
d) c:\dir
e) null
CORRECT ANSWER : a
EXPLANATION :
A is correct as getPath() method returns the name of the file with extension.
Also note that file Test.test need not exist.
--------------------------------------------------------------------
QUESTION NO : 74
QUESTION STATEMENT : Which of the following will not compile without
error?
CHOICES :
a) int i = 10;
int j = 4;
System.out.println(i||j);
b) int i = 10;
int j = 4;
System.out.println(i|j);
c) boolean b1=true;
boolean b2=true;
System.out.println(b1|b2);
d) boolean b1=true;
boolean b2=true;
System.out.println(b1||b2);
CORRECT ANSWER : a
EXPLANATION :
A is correct as Option A will not compile because it is an attempt to perform
a logical OR operation on a an integral types. A logical OR can only be performed
with boolean arguments. B and C are correct as '|' is bitwise OR operator which
is applicable to integer as well as boolean types. D is also correct as '||'
is logical short-circuit OR operator which is applicable to boolean types.
--------------------------------------------------------------------
QUESTION NO : 75
QUESTION STATEMENT : A class can be abstract without an abstract method.
True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
There need not be an abstract method for a class to be abstract but if there
is an abstract method then the class has to be abstract.
--------------------------------------------------------------------
QUESTION NO : 76
QUESTION STATEMENT : char is the only unsigned integral primitive type
in Java. True/False?
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
Yes char is the only unsigned integral primitive type in Java. Others are signed.
--------------------------------------------------------------------
QUESTION NO : 77
QUESTION STATEMENT : Which of the following are not the methods of the
Runnable interface?
CHOICES :
a) run
b) start
c) yield
d) stop
CORRECT ANSWER : bcd
EXPLANATION :
B, C and D are correct as the Runnable interface has only one method run that
needs to be created in any class that implements it. The start method which
belongs to Thread class calls the run method.
--------------------------------------------------------------------
QUESTION NO : 78
QUESTION STATEMENT : Which of the following can be used to define a
constructor for this class, given the following code?
public class Test
{
...
}
CHOICES :
a) public void Test() {...}
b) public Test() {...}
c) public static Test() {...}
d) public static void Test() {...}
CORRECT ANSWER : b
EXPLANATION :
B is correct. The constructor can't have return type and also it can't be static.
Thus A,C and D are incorrect.
--------------------------------------------------------------------
QUESTION NO : 79
QUESTION STATEMENT : What will happen when you compile and run the following
code?
import java.util.*;
public abstract interface Test1
{
public void test();
}
public class Test2 implements Test1
{
public void test(){}
}
CHOICES :
a) Compilation Error
b) Runtime Exception
c) Compiles without error
d) None of these
CORRECT ANSWER : a
EXPLANATION :
A is correct as in the same Java file there can't be more than one public class/interface.
--------------------------------------------------------------------
QUESTION NO : 80
QUESTION STATEMENT : What will be the result of executing the following
main() method?
1. public static void main(String[] args)
2. {
3. String myString;
4. int x = 100;
5.
6. if (x < 100) myString = "x is less than 100";
7. if (x > 100) myString = "x is greater than 100";
8. System.out.println(myString.length());
9. }
CHOICES :
a) The code will compile with a warning that variable myString might not have
been initialized
b) The code will compile without any warnings
c) The code will not compile. But it will compile and print the length of myString
if the variable myString is initialized in an unconditional statement before
line 8
d) None of these
CORRECT ANSWER : d
EXPLANATION :
D is correct. The code will not compile raising an error that variable myString
might not have been initialized. Local variables are not initialized when they
are instantiated at method invocation. The compiler reports an error if a local
variable is being used uninitialized. If we initialize myString before line
8 the code will compile but whether it will print the length of myString or
not will depend upon the value of myString before line 8. Please observe that
myString is not getting any value in the if conditions at line 6 and line 7.
This means that at line 8 myString will have the same value as its initialization.
Now the catch is that if we initialize myString to null, the code will compile
but return a runtime exception at line 8 as myString is not referencing any
object.
--------------------------------------------------------------------
QUESTION NO : 81
QUESTION STATEMENT : What will be the result of executing the following
code?
public static void main(String args[])
{
char digit = 'a';
for (int i = 0; i < 10; i++)
{
switch (digit)
{
case 'x' :
{
int j = 0;
System.out.println(j);
}
default :
{
int j = 100;
System.out.println(j);
}
}
}
int i = j;
System.out.println(i);
}
CHOICES :
a) 100 will be printed 11 times
b) 100 will be printed 10 times and then there will be a runtime exception
c) The code will not compile because the variable i cannot be declared twice
within the main() method
d) The code will not compile because the variable j cannot be declared twice
within the switch statement
e) None of these
CORRECT ANSWER : e
EXPLANATION :
E is correct. The code will not compile. There is no problem with the declaration
of another variable i as both the variables are in disjoint blocks (first one
is inside the for loop and its scope ends with the for loop, whereas the second
is outside the for loop) and, therefore, different scopes and hence valid. The
problem is with the variable j. The two declarations of the variable j are perfectly
valid as they are in disjoint blocks and, therefore, different scopes. The error
is that both the declarations of j are not available outside the case or default
statement, whereas we are trying to assign it to the variable i. Therefore the
compiler objects and reports variable j not found.
--------------------------------------------------------------------
QUESTION NO : 82
QUESTION STATEMENT : What will be the result of executing the following
code?
Given that Test1 is a class.
1. Test1[] t1 = new Test1[10];
2. Test1[][] t2 = new Test1[5][];
3. if (t1[0] == null)
4. {
5. t2[0] = new Test1[10]
6. t2[1] = new Test1[10]
7. t2[2] = new Test1[10]
8. t2[3] = new Test1[10]
9. t2[4] = new Test1[10]
10. }
11. System.out.println(t1[0]);
12. System.out.println(t2[1][0]);
CHOICES :
a) The code will not compile because the array t2 is not initialized in an
unconditional statement before use
b) The code will compile but a runtime exception will be thrown at line 12
c) The code will compile but a runtime exception will be thrown at line 11
d) None of these
CORRECT ANSWER : d
EXPLANATION :
D is correct. Though we cannot use local variables without initializing them
(compilation error), there is an exception to it. In case of arrays initialization
is supposed to be complete when we specify the leftmost dimension of the array.
The problem occurs at runtime if we try to access an element of the array which
has not been initialized (specification of size). In the question above the
array t2 is initialized before use, therefore there will be no problem at runtime
also and the lines 11 and 12 will both print null.
--------------------------------------------------------------------
QUESTION NO : 83
QUESTION STATEMENT : Consider the following line of code:
float x[] = new float[10];
After execution, which of the following are true?
CHOICES :
a) x[9] = 0
b) x[10] = 0.0f
c) x[9] = 0.0f
d) x.length = 10
CORRECT ANSWER : cd
EXPLANATION :
C and D are correct. The compiler initializes all the elements of array x to
0.0f(notice that 0.0 is a double and not float!). One more thing to note is
that in Java array index starts from 0, hence x[9] is the last element in the
array. Here A is incorrect as x[9] = 0.0f(float) and not 0(int), B is incorrect
as x[10] is invalid.
--------------------------------------------------------------------
QUESTION NO : 84
QUESTION STATEMENT : After execution of the following code, what is
the value of a?
byte a;
byte b = 3; // binary 00000011
byte c = -3;
if (~b > c)
{
a = c;
}
else
{
a = b;
}
CHOICES :
a) -3
b) 3
c) 0
d) None of the above
CORRECT ANSWER : b
EXPLANATION :
B is correct. "~" is the bitwise inverter. Hence the binary representation
of ~b is "11111100" which is -4, thus the "else" condition
gets executed and a gets the value of b which is 3.
--------------------------------------------------------------------
QUESTION NO : 85
QUESTION STATEMENT : What results from running the code below?
int a = -5; int b = -2;
System.out.println(a % b);
CHOICES :
a) 0
b) 1
c) -1
d) A compiler error saying "%" operator is not valid for negative
numbers.
CORRECT ANSWER : c
EXPLANATION :
C is correct. To calculate a % b(a modulus b), the simplest way is, drop any
negative signs from both the operands and calculate the result. Now if the left-hand
side operand is negative negate the result, the sign of right-hand side operand
doesn't matter. In our case (-5 % -2) is equal to -(5 % 2) = -(1) = -1, hence
C is correct.
--------------------------------------------------------------------
QUESTION NO : 86
QUESTION STATEMENT : Given the code below, and making no other changes,
which access modifiers (public, protected or private) can legally be placed
before myMethod() on line 3? If line 3 is left as it is, which keywords can
legally be placed before myMethod on line 8?
1. class HumptyDumpty
2. {
3. void myMethod() {}
4. }
5.
6. class HankyPanky extends HumptyDumpty
7. {
8. void myMethod() {}
9. }
CHOICES :
a) private or nothing(i.e. leaving it as it is) on line 3. Nothing(i.e. leaving
it as it is) or protected or public on line 8.
b) public or protected on line 3. private or nothing(i.e. leaving it as it is)
on line 8.
c) nothing(i.e. leaving it as it is) or protected or public on line 3. private
or nothing(i.e. leaving it as it is) on line 8.
d) public on line 3 and private on line8.
CORRECT ANSWER : a
EXPLANATION :
A is correct. The basic principle is that a method cannot be overridden to be
more private. Since the method is being overridden to be friendly(default modifier)
it can only be private or friendly in the superclass. Secondly if the method
in superclass is left as it is(i.e. friendly access) the method in subclass
can be friendly, protected or public.
--------------------------------------------------------------------
QUESTION NO : 87
QUESTION STATEMENT : If you compile and run the following code, Which
lines would be the part of the output?
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
if (i != j)
{
continue;
}
System.out.println("i = " + i + " j = " + j);
}
}
CHOICES :
a) i = 0 j = 0
b) i = 1 j = 2
c) i = 1 j = 1
d) i = 2 j = 2
e) i = 5 j = 5
CORRECT ANSWER : acd
EXPLANATION :
A, C and D are correct. Since the inner loop executes a continue statement whenever
i and j are not equal and the value is printed after the continue statement,
only A, C and D are correct. E will never occur as it is out of bound, B will
not occur because the continue statement will skip the execution.
--------------------------------------------------------------------
QUESTION NO : 88
QUESTION STATEMENT : Which of the following lines will compile without
warning or error?
CHOICES :
a) float f = 1.3;
b) char c = "a";
c) byte b = 257;
d) boolean b = null;
e) int i = 0x10;
CORRECT ANSWER : e
EXPLANATION :
E is correct. A is incorrect as the default type for 1.3 is double hence an
explicit cast is needed to compile A. B will not compile because a string is
being assigned to a character, to compile B the character 'a' should have been
in single quotes. C will not compile because a byte can only take values from
-128 to 127, since 257 is not a valid value for a byte it will not compile.
D will not compile because a boolean can only be false or true, null is not
a valid value for a variable of type boolean. E is correct as its the hexadecimal
representation of 16.
--------------------------------------------------------------------
QUESTION NO : 89
QUESTION STATEMENT : What results from running the following code fragment?
Integer ten = new Integer(10);
Long nine = new Long (9);
System.out.println(ten + nine);
int i = 1;
System.out.println(i + ten);
CHOICES :
a) 19 followed by 20
b) 19 followed by 11
c) Error: Cant convert java.lang.Integer
d) 10 followed by 1
CORRECT ANSWER : c
EXPLANATION :
C is correct. The wrapper classes cannot be used like primitives. Wrapper classes
have similar names to primitives but all start with upper case letters. Thus
in this case we have int as a primitive and Integer as a wrapper.
--------------------------------------------------------------------
QUESTION NO : 90
QUESTION STATEMENT : Which of the following statements are valid, given
the following variable declarations? boolean a; boolean b; int c;
CHOICES :
a) (a | b)
b) (a || a)
c) (a ^ b) | c
d) (a & c)
e) (a && c)
CORRECT ANSWER : ab
EXPLANATION :
A and B are correct. C, D and E are incorrect because they require conversion
of a boolean to an int which is illegal.
--------------------------------------------------------------------
QUESTION NO : 91
QUESTION STATEMENT : Analyze the following 2 classes and select the
correct statements.
class A
{
private int x = 0;
static int y = 1;
protected int q = 2;
}
class B extends A
{
void method()
{
System.out.println(x);
System.out.println(y);
System.out.println(q);
}
}
CHOICES :
a) The code fails to compile because the variable x is not available to class
B.
b) The code compiles correctly, and the following is displayed: 0 1 2
c) The code fails to compile because you can't subclass a class with private
variables.
d) Removing the line "System.out.println(x)" will allow the code to
compile correctly.
e) The compiler will complain that the variable x in class B is undefined.
CORRECT ANSWER : ade
EXPLANATION :
A, D and E are correct. Answer A is correct, because x is declared as private
to class A and is therefore not available to any other class (even subclasses).
Answer C is totally meaningless, but sounds vaguely plausible!. Answer D is
correct, because the only problem with the code is the attempt to reference
the variable x. Answer E is correct (see answer D).
--------------------------------------------------------------------
QUESTION NO : 92
QUESTION STATEMENT : What is the valid declaration for the finalize()
method?
CHOICES :
a) protected void finalize() throws Throwable
b) final finalize()
c) public final finalize()
d) private boolean finalize()
e) private final void finalize() throws Exception
CORRECT ANSWER : a
EXPLANATION :
A is correct. Please see the declaration of finalize() method in the object
class in Java language Specification.
--------------------------------------------------------------------
QUESTION NO : 93
QUESTION STATEMENT : Consider the following piece of code and select
the correct statements.
1. Object o = new String("abcd");
2. String s = o;
3. System.out.println(s);
4. System.out.println(o);
CHOICES :
a) The following is displayed:
abcd
abcd
b) The code fails to compile at line 1.
c) The code fails to compile at line 2
d) The code fails to compile at line 4.
e) The code can be made to compile by changing line 1 to the following:
String o = new String("abcd");
CORRECT ANSWER : ce
EXPLANATION :
C and E are correct. The code fails to compile because line 2 is attempting
to assign objects "down" the hierarchy.
--------------------------------------------------------------------
QUESTION NO : 94
QUESTION STATEMENT : Which of the following is the correct way to set
the foreground color of a component, c?
CHOICES :
a) c.setForeground("red");
b) c.setColor("Color.red");
c) c.Foreground(Color.red);
d) c.setForegroundColor("red");
e) c.setForeground(Color.red);
CORRECT ANSWER : e
EXPLANATION :
E is correct. To set the foreground color of a component, setForeground method
is used. It takes color as an input. To pass the color to this method, Color
class has various static variables for different colors. In the above case red
color (the static variable of Color class) is passed as an input to the method.
--------------------------------------------------------------------
QUESTION NO : 95
QUESTION STATEMENT : Select the correct statements relating to the following
piece of code.
1. public class AnyClass
2. {
3. abstract int method();
4. void anotherMethod()
5. {
6. }
7.
8. class Box extends AnyClass
9. {
10. int method()
11. {
12. return 2;
13. }
14. }
15. }
CHOICES :
a) Changing "extends" to "implements" on line 6 will allow
the code to compile correctly.
b) The method() in class AnyClass cannot be abstract without the entire class
being declared as abstract.
c) Declaring class AnyClass to be abstract will allow the code to compile correctly.
d) The class AnyClass must have an explicit default constructor in order for
it to be subclassed correctly.
e) The code fails to compile, because class Box does not implement anotherMethod().
CORRECT ANSWER : bc
EXPLANATION :
B and C are correct. There are several things wrong with this code:
- class AnyClass must be declared as abstract, since method() is declared as
abstract
- if class Anyclass is declared as abstract, then the code will compile correctly
- if the abstract declaration of method() in class A is removed, the code will
compile (however, the entire line 2 must now read as follows:
int method(){}
In other words, a method body must now be supplied since the method is no longer
abstract.
--------------------------------------------------------------------
QUESTION NO : 96
QUESTION STATEMENT : Which layout manager is described by the following?
It aligns components vertically and horizontally, without requiring that the components be of the same size. It maintains a dynamic rectangular grid of cells, with each component occupying one or more cells, called its display area.
CHOICES :
a) GridLayout
b) FlowLayout
c) GridBagLayout
d) BoxLayout
CORRECT ANSWER : c
EXPLANATION :
C is correct. GridBagLayout manager divides its container into an array of cells,
but(unlike the cells of a GridLayout manager) different cell rows can have different
heights, and different cell columns can have different widths. A component can
occupy a single cell or it can span a number of cells.
--------------------------------------------------------------------
QUESTION NO : 97
QUESTION STATEMENT : What is the result of compiling and executing the
following code?
public class ThreadTest extends Thread
{
public void run()
{
System.out.println("In run");
yield();
System.out.println("Leaving run");
}
public static void main(String args [])
{
(new ThreadTest()).start();
}
}
CHOICES :
a) The code fails to compile in the main() method.
b) The code fails to compile in the run() method.
c) Only the text "In run" will be displayed.
d) The text "In run" followed by "Leaving run" will be displayed.
e) The code compiles correctly, but nothing is displayed.
CORRECT ANSWER : d
EXPLANATION :
D is correct. Answer A is incorrect. The main() method is defined correctly,
and the line (new ThreadTest()).start(); is a valid way to create and start
a ThreadTest thread (since the class ThreadTest is a subclass of Thread). Answer
B is incorrect, since the run() method is declared correctly. The yield() method
simply returns control back to the JVM, and unless there is a higher priority
thread ready to run, this thread will continue or resume execution. Answer C
is incorrect, since the yield() only has a temporary effect on execution. Answer
E is incorrect, since the start() method starts the thread. On doing so, it
is the run() method which is executed. Therefore, the text is displayed.
--------------------------------------------------------------------
QUESTION NO : 98
QUESTION STATEMENT : What will be the result of compiling and executing
the following code?
1 import java.awt.*;
2 public class CheckTest extends Frame
3 {
4 public CheckTest()
5 {
6 CheckboxGroup chg=new CheckboxGroup();
7 Checkbox ch1=new Checkbox("English",true,chg);
8 Checkbox ch2=new Checkbox("French",true,chg);
9 chg=null;
10 Checkbox ch3=new Checkbox("Spanish",true,chg);
11 setLayout(new FlowLayout());
12 add(ch1);
13 add(ch2);
14 add(ch3);
15 pack();
16 setVisible(true);
17 }
18 public static void main(String args[])
19 {
20 CheckTest tf = new CheckTest();
21 }
22 }
CHOICES :
a) Exception thrown in Line 10 - null value passed as CheckboxGroup to the
Checkbox constructor.
b) All the three checkboxes appear as radio buttons and only ch1 is in the "on"
state.
c) ch1 and ch2 appear as radio buttons while ch3 appears as normal checkbox,
ch2 and ch3 are in the "on" state.
d) ch1 and ch2 appear as radio buttons while ch3 appears as normal checkbox,
ch1 and ch3 are in the "on" state.
e) All the three checkboxes appear as checkboxes and only ch3 is in the "on"
state.
CORRECT ANSWER : c
EXPLANATION :
C is the correct choice. The checkboxes ch1 and ch2 appear as radio buttons
because they belong to the same CheckboxGroup and hence only one of them can
be in the "on" state. ch1 will be in the "off" state while
ch2 will be in the "on" state because whenever a radio button is turned
on, the others will be turned off. If a null value is passed as the CheckboxGroup,
there is no error, the checkbox is then considered to be not belonging to any
group. So ch3 appears as a normal checkbox, in the "on" state.
--------------------------------------------------------------------
QUESTION NO : 99
QUESTION STATEMENT : Which of the following pieces of code can be used
to create a BufferedReader, which can be used to read text lines from a file
using 8859_1 character encoding ?
CHOICES :
a) FileInputStream inFile=new FileInputStream("abc");
InputStreamReader inreader=new InputStreamReader(inFile,"8859_1");
BufferedReader br=new BufferedReader(inreader);
b) FileReader fr=new FileReader("abc");
BufferedReader br=new BufferedReader(fr);
c) FileInputStream inFile=new FileInputStream("abc");
BufferedReader br=new BufferedReader(inFile,"8859_1");
d)
BufferedReader br=new BufferedReader(new FilterReader("abc","8859_1"));
CORRECT ANSWER : a
EXPLANATION :
A is the correct choice. Here the BufferedReader constructor takes the encoding
type as the second argument. Choice B will write to the file, but uses the default
encoding only. C will not compile because the BufferedReader cannot connect
to a FileInputStream directly because BufferedReader is a character Stream while
FileInputStream is a byte stream. D will not compile because we are trying to
instantiate FilterReader which is an abstract class.
--------------------------------------------------------------------
QUESTION NO : 100
QUESTION STATEMENT : The right-hand operand of the instanceof operator
can be an interface; e.g.
a instanceof b
where b is an interface.
CHOICES :
a) True
b) False
CORRECT ANSWER : a
EXPLANATION :
A is correct. The instanceof operator results in a true value if the left-hand
object implements the interface.
------------------------------------Finish--------------------------------
![]() |
![]() |