Finding The Output

Question 1 :

What will be the output of the program?

String x = new String("xyz");
String y = "abc";
x = x + y;
How many String objects have been created?


A). 2
B). 3
C). 4
D). 5
Answer : Option C

Explanation :

Line 1 creates two, one referred to by x and the lost String "xyz". Line 2 creates one (for a total of three). Line 3 creates one more (for a total of four), the concatenated String referred to by x with a value of "xyzabc".


Question 2 :

What will be the output of the program?

public class WrapTest 
{
    public static void main(String [] args) 
    {
        int result = 0;
        short s = 42;
        Long x = new Long("42");
        Long y = new Long(42);
        Short z = new Short("42");
        Short x2 = new Short(s);
        Integer y2 = new Integer("42");
        Integer z2 = new Integer(42);

        if (x == y) /* Line 13 */
            result = 1;
        if (x.equals(y) ) /* Line 15 */
            result = result + 10;
        if (x.equals(z) ) /* Line 17 */
            result = result + 100;
        if (x.equals(x2) ) /* Line 19 */
            result = result + 1000;
        if (x.equals(z2) ) /* Line 21 */
            result = result + 10000;

        System.out.println("result = " + result);
    }
}


A). result = 1
B). result = 10
C). result = 11
D). result = 11010
Answer : Option B

Explanation :

Line 13 fails because == compares reference values, not object values. Line 15 succeeds because both String and primitive wrapper constructors resolve to the same value (except for the Character wrapper). Lines 17, 19, and 21 fail because the equals() method fails if the object classes being compared are different and not in the same tree hierarchy.


Question 3 :

What will be the output of the program?

public class BoolTest 
{
    public static void main(String [] args) 
    {
        int result = 0;

        Boolean b1 = new Boolean("TRUE");
        Boolean b2 = new Boolean("true");
        Boolean b3 = new Boolean("tRuE");
        Boolean b4 = new Boolean("false");

        if (b1 == b2)  /* Line 10 */
            result = 1;
        if (b1.equals(b2) ) /* Line 12 */
            result = result + 10;
        if (b2 == b4)  /* Line 14 */
            result = result + 100;
        if (b2.equals(b4) ) /* Line 16 */
            result = result + 1000;
        if (b2.equals(b3) ) /* Line 18 */
            result = result + 10000;

        System.out.println("result = " + result);
    }
}


A). 0
B). 1
C). 10
D). 10010
Answer : Option D

Explanation :

Line 10 fails because b1 and b2 are two different objects. Lines 12 and 18 succeed because the Boolean String constructors are case insensitive. Lines 14 and 16 fail because true is not equal to false.


Question 4 :

What will be the output of the program?

public class ObjComp 
{
    public static void main(String [] args ) 
    {
        int result = 0;
        ObjComp oc = new ObjComp();
        Object o = oc;

        if (o == oc)  
            result = 1;
        if (o != oc)  
            result = result + 10;
        if (o.equals(oc) )  
            result = result + 100;
        if (oc.equals(o) )  
            result = result + 1000;

        System.out.println("result = " + result);
    }
}


A). 1
B). 10
C). 101
D). 1101
Answer : Option D

Explanation :

Even though o and oc are reference variables of different types, they are both referring to the same object. This means that == will resolve to true and that the default equals() method will also resolve to true.


Question 5 :

What will be the output of the program?

public class Example 
{
    public static void main(String [] args) 
    {
        double values[] = {-2.3, -1.0, 0.25, 4};
        int cnt = 0;
        for (int x=0; x < values.length; x++) 
        {
            if (Math.round(values[x] + .5) == Math.ceil(values[x])) 
            {
                ++cnt;
            }
        }
        System.out.println("same results " + cnt + " time(s)");
    }
}


A). same results 0 time(s)
B). same results 2 time(s)
C). same results 4 time(s)
D). Compilation fails.
Answer : Option B

Explanation :

Math.round() adds .5 to the argument then performs a floor(). Since the code adds an additional .5 before round() is called, it's as if we are adding 1 then doing a floor(). The values that start out as integer values will in effect be incremented by 1 on the round() side but not on the ceil() side, and the noninteger values will end up equal.


Question 6 :

What will be the output of the program?

public class Test178 
{ 
    public static void main(String[] args) 
    {
        String s = "foo"; 
        Object o = (Object)s; 
        if (s.equals(o)) 
        { 
            System.out.print("AAA"); 
        } 
        else 
        {
            System.out.print("BBB"); 
        } 
        if (o.equals(s)) 
        {
            System.out.print("CCC"); 
        } 
        else 
        {
            System.out.print("DDD"); 
        } 
    } 
}


A). AAACCC
B). AAADDD
C). BBBCCC
D). BBBDDD
Answer : Option A

Question 7 :

What will be the output of the program?

String x = "xyz";
x.toUpperCase(); /* Line 2 */
String y = x.replace('Y', 'y');
y = y + "abc";
System.out.println(y);


A). abcXyZ
B). abcxyz
C). xyzabc
D). XyZabc
Answer : Option C

Explanation :

Line 2 creates a new String object with the value "XYZ", but this new object is immediately lost because there is no reference to it. Line 3 creates a new String object referenced by y. This new String object has the value "xyz" because there was no "Y" in the String object referred to by x. Line 4 creates a new String object, appends "abc" to the value "xyz", and refers y to the result.


Question 8 :

What will be the output of the program?

int i = (int) Math.random();


A). i = 0
B). i = 1
C). value of i is undetermined
D). Statement causes a compile error
Answer : Option A

Explanation :

Math.random() returns a double value greater than or equal to 0 and less than 1. Its value is stored to an int but as this is a narrowing conversion, a cast is needed to tell the compiler that you are aware that there may be a loss of precision.

The value after the decimal point is lost when you cast a double to int and you are left with 0.


Question 9 :

What will be the output of the program?

class A 
{ 
    public A(int x){} 
} 
class B extends A { } 
public class test 
{ 
    public static void main (String args []) 
    {
        A a = new B(); 
        System.out.println("complete"); 
    } 
}


A). It compiles and runs printing nothing
B). Compiles but fails at runtime
C). Compile Error
D). Prints "complete"
Answer : Option C

Explanation :

No constructor has been defined for class B therefore it will make a call to the default constructor but since class B extends class A it will also call the Super() default constructor.

Since a constructor has been defined in class A java will no longer supply a default constructor for class A therefore when class B calls class A's default constructor it will result in a compile error.


Question 10 :

What will be the output of the program?

int i = 1, j = 10; 
do 
{
    if(i++ > --j) /* Line 4 */
    {
        continue; 
    } 
} while (i < 5); 
System.out.println("i = " + i + "and j = " + j); /* Line 9 */


A). i = 6 and j = 5
B). i = 5 and j = 5
C). i = 6 and j = 6
D). i = 5 and j = 6
Answer : Option D

Explanation :

This question is not testing your knowledge of the continue statement. It is testing your knowledge of the order of evaluation of operands. Basically the prefix and postfix unary operators have a higher order of evaluation than the relational operators. So on line 4 the variable i is incremented and the variable j is decremented before the greater than comparison is made. As the loop executes the comparison on line 4 will be:

if(i > j)
if(2 > 9)
if(3 > 8)
if(4 > 7)
if(5 > 6) at this point i is not less than 5, therefore the loop terminates and line 9 outputs the values of i and j as 5 and 6 respectively.

The continue statement never gets to execute because i never reaches a value that is greater than j.


Question 11 :

What will be the output of the program?

public class ExamQuestion7 
{  
    static int j; 
    static void methodA(int i)
    {
        boolean b; 
        do
        { 
            b = i<10 | methodB(4); /* Line 9 */
            b = i<10 || methodB(8);  /* Line 10 */
        }while (!b); 
    } 
    static boolean methodB(int i)
    {
        j += i; 
        return true; 
    } 
    public static void main(String[] args)
    {
        methodA(0); 
        System.out.println( "j = " + j ); 
    } 
}


A). j = 0
B). j = 4
C). j = 8
D). The code will run with no output
Answer : Option B

Explanation :

The lines to watch here are lines 9 & 10. Line 9 features the non-shortcut version of the OR operator so both of its operands will be evaluated and therefore methodB(4) is executed.

However line 10 has the shortcut version of the OR operator and if the 1st of its operands evaluates to true (which in this case is true), then the 2nd operand isn't evaluated, so methodB(8) never gets called.

The loop is only executed once, b is initialized to false and is assigned true on line 9. Thus j = 4.


Question 12 :

What will be the output of the program?

try 
{
    Float f1 = new Float("3.0");
    int x = f1.intValue();
    byte b = f1.byteValue();
    double d = f1.doubleValue();
    System.out.println(x + b + d);
}
catch (NumberFormatException e) /* Line 9 */
{
    System.out.println("bad number"); /* Line 11 */
}


A). 9.0
B). bad number
C). Compilation fails on line 9.
D). Compilation fails on line 11.
Answer : Option A

Explanation :

The xxxValue() methods convert any numeric wrapper object's value to any primitive type. When narrowing is necessary, significant bits are dropped and the results are difficult to calculate.


Question 13 :

What will be the output of the program?

class Q207 
{ 
    public static void main(String[] args) 
    {
        int i1 = 5; 
        int i2 = 6; 
        String s1 = "7"; 
        System.out.println(i1 + i2 + s1); /* Line 8 */
    } 
}


A). 18
B). 117
C). 567
D). Compiler error
Answer : Option B

Explanation :

This question is about the + (plus) operator and the overriden + (string cocatanation) operator. The rules that apply when you have a mixed expression of numbers and strings are:

If either operand is a String, the + operator concatenates the operands.

If both operands are numeric, the + operator adds the operands.

The expression on line 6 above can be read as "Add the values i1 and i2 together, then take the sum and convert it to a string and concatenate it with the String from the variable s1". In code, the compiler probably interprets the expression on line 8 above as:

System.out.println( new StringBuffer() 
.append(new Integer(i1 + i2).toString()) 
.append(s1) 
.toString() ); 


Question 14 :

What will be the output of the program?

public class SqrtExample 
{
    public static void main(String [] args) 
    {
        double value = -9.0;
        System.out.println( Math.sqrt(value));
    }
}


A). 3.0
B). -3.0
C). NaN
D). Compilation fails.
Answer : Option C

Explanation :

The sqrt() method returns NaN (not a number) when it's argument is less than zero.


Question 15 :

What will be the output of the program?

String s = "ABC"; 
s.toLowerCase(); 
s += "def"; 
System.out.println(s);


A). ABC
B). abc
C). ABCdef
D). Compile Error
Answer : Option C

Explanation :

String objects are immutable. The object s above is set to "ABC". Now ask yourself if this object is changed and if so where - remember strings are immutable.

Line 2 returns a string object but does not change the originag string object s, so after line 2 s is still "ABC".

So what's happening on line 3? Java will treat line 3 like the following:

s = new StringBuffer().append(s).append("def").toString();

This effectively creates a new String object and stores its reference in the variable s, the old String object containing "ABC" is no longer referenced by a live thread and becomes available for garbage collection.


Question 16 :

What will be the output of the program?

public class NFE 
{
    public static void main(String [] args) 
    {
    String s = "42";
        try 
        {
            s = s.concat(".5");  /* Line 8 */
            double d = Double.parseDouble(s);
            s = Double.toString(d);
            int x = (int) Math.ceil(Double.valueOf(s).doubleValue());
            System.out.println(x);
        }
        catch (NumberFormatException e) 
        {
            System.out.println("bad number");
        }
    }
}


A). 42
B). 42.5
C). 43
D). bad number
Answer : Option C

Explanation :

All of this code is legal, and line 8 creates a new String with a value of "42.5". Lines 9 and 10 convert the String to a double and then back again. Line 11 is fun— Math.ceil()'s argument expression is evaluated first. We invoke the valueOf() method that returns an anonymous Double object (with a value of 42.5). Then the doubleValue() method is called (invoked on the newly created Double object), and returns a double primitive (there and back again), with a value of (you guessed it) 42.5. The ceil() method converts this to 43.0, which is cast to an int and assigned to x.


Question 17 :

What will be the output of the program?

System.out.println(Math.sqrt(-4D));


A). -2
B). NaN
C). Compile Error
D). Runtime Exception
Answer : Option B

Explanation :

It is not possible in regular mathematics to get a value for the square-root of a negative number therefore a NaN will be returned because the code is valid.


Question 18 :

What will be the output of the program?

interface Foo141 
{ 
    int k = 0; /* Line 3 */
} 
public class Test141 implements Foo141 
{
    public static void main(String args[]) 
    {
        int i; 
        Test141 test141 = new Test141(); 
        i = test141.k; /* Line 11 */
        i = Test141.k; 
        i = Foo141.k; 
    } 
}


A). Compilation fails.
B). Compiles and runs ok.
C). Compiles but throws an Exception at runtime.
D). Compiles but throws a RuntimeException at runtime.
Answer : Option B

Explanation :

The variable k on line 3 is an interface constant, it is implicitly public, static, and final. Static variables can be referenced in two ways:
Via a reference to any instance of the class (line 11)
Via the class name (line 12).


Question 19 :

What will be the output of the program?

String a = "newspaper";
a = a.substring(5,7);
char b = a.charAt(1);
a = a + b;
System.out.println(a);


A). apa
B). app
C). apea
D). apep
Answer : Option B

Explanation :

Both substring() and charAt() methods are indexed with a zero-base, and substring() returns a String of length arg2 - arg1.


Question 20 :

What will be the output of the program?

public class StringRef 
{
    public static void main(String [] args) 
    {
        String s1 = "abc";
        String s2 = "def";
        String s3 = s2;   /* Line 7 */
        s2 = "ghi";
        System.out.println(s1 + s2 + s3);
    }
}


A). abcdefghi
B). abcdefdef
C). abcghidef
D). abcghighi
Answer : Option C

Explanation :

After line 7 executes, both s2 and s3 refer to a String object that contains the value "def". When line 8 executes, a new String object is created with the value "ghi", to which s2 refers. The reference variable s3 still refers to the (immutable) String object with the value "def".


Question 21 :

What will be the output of the program?

public class Test138 
{ 
    public static void stringReplace (String text) 
    {
        text = text.replace ('j' , 'c'); /* Line 5 */
    } 
    public static void bufferReplace (StringBuffer text) 
    { 
        text = text.append ("c");  /* Line 9 */
    } 
    public static void main (String args[]) 
    { 
        String textString = new String ("java"); 
        StringBuffer textBuffer = new StringBuffer ("java"); /* Line 14 */
        stringReplace(textString); 
        bufferReplace(textBuffer); 
        System.out.println (textString + textBuffer); 
    } 
}


A). java
B). javac
C). javajavac
D). Compile error
Answer : Option C

Explanation :

A string is immutable, it cannot be changed, that's the reason for the StringBuffer class. The stringReplace method does not change the string declared on line 14, so this remains set to "java".

Method parameters are always passed by value - a copy is passed into the method - if the copy changes, the original remains intact, line 5 changes the reference i.e. text points to a new String object, however this is lost when the method completes. The textBuffer is a StringBuffer so it can be changed.

This change is carried out on line 9, so "java" becomes "javac", the text reference on line 9 remains unchanged. This gives us the output of "javajavac"


Question 22 :

What will be the output of the program?

class Tree { } 
class Pine extends Tree { } 
class Oak extends Tree { } 
public class Forest1 
{ 
    public static void main (String [] args)
    { 
        Tree tree = new Pine(); 
        if( tree instanceof Pine ) 
            System.out.println ("Pine"); 
        else if( tree instanceof Tree ) 
            System.out.println ("Tree"); 
        else if( tree instanceof Oak ) 
            System.out.println ( "Oak" ); 
        else 
            System.out.println ("Oops "); 
    } 
}


A). Pine
B). Tree
C). Forest
D). Oops
Answer : Option A

Explanation :

The program prints "Pine".


Question 23 :

What will be the output of the program?

String d = "bookkeeper";
d.substring(1,7);
d = "w" + d;
d.append("woo");  /* Line 4 */
System.out.println(d);


A). wookkeewoo
B). wbookkeeper
C). wbookkeewoo
D). Compilation fails.
Answer : Option D

Explanation :

In line 4 the code calls a StringBuffer method, append() on a String object.


Question 24 :

What will be the output of the program?

String a = "ABCD"; 
String b = a.toLowerCase(); 
b.replace('a','d'); 
b.replace('b','c'); 
System.out.println(b);


A). abcd
B). ABCD
C). dccd
D). dcba
Answer : Option A

Explanation :

String objects are immutable, they cannot be changed, in this case we are talking about the replace method which returns a new String object resulting from replacing all occurrences of oldChar in this string with newChar.

b.replace(char oldChar, char newChar);

But since this is only a temporary String it must either be put to use straight away i.e.

System.out.println(b.replace('a','d'));
Or a new variable must be assigned its value i.e.
String c = b.replace('a','d');


Question 25 :

What will be the output of the program?

public class ExamQuestion6 
{
    static int x; 
    boolean catch()
    {
        x++; 
        return true; 
    } 
    public static void main(String[] args)
    {
        x=0; 
        if ((catch() | catch()) || catch()) 
            x++; 
        System.out.println(x); 
    } 
}


A). 1
B). 2
C). 3
D). Compilation Fails
Answer : Option D

Explanation :

Initially this looks like a question about the logical and logical shortcut operators "|" and "||" but on closer inspection it should be noticed that the name of the boolean method in this code is "catch". "catch" is a reserved keyword in the Java language and cannot be used as a method name. Hence Compilation will fail.


Question 26 :

What will be the output of the program?

public class Test 
{ 
    public static void main(String[] args) 
    {
        final StringBuffer a = new StringBuffer(); 
        final StringBuffer b = new StringBuffer(); 

        new Thread() 
        { 
            public void run() 
            {
                System.out.print(a.append("A")); 
                synchronized(b) 
                { 
                    System.out.print(b.append("B")); 
                } 
            } 
        }.start(); 
            
        new Thread() 
        {
            public void run() 
            {
                System.out.print(b.append("C")); 
                synchronized(a) 
                {
                    System.out.print(a.append("D")); 
                } 
            } 
        }.start(); 
    } 
}


A). ACCBAD
B). ABBCAD
C). CDDACB
D). Indeterminate output
Answer : Option D

Explanation :

It gives different output while executing the same compiled code at different times.

C:\>javac Test.java
C:\>java Test
ABBCAD
C:\>java Test
ACADCB
C:\>java Test
ACBCBAD
C:\>java Test
ABBCAD
C:\>java Test
ACBCBAD
C:\>java Test
ACBCBAD
C:\>java Test
ABBCAD


Question 27 :

What will be the output of the program?

String s = "hello"; 
Object o = s; 
if( o.equals(s) )
{
    System.out.println("A"); 
} 
else
{
    System.out.println("B"); 
} 
if( s.equals(o) )
{
    System.out.println("C"); 
} 
else
{ 
    System.out.println("D"); 
}
1. A
2. B
3. C
4. D


A). 1 and 3
B). 2 and 4
C). 3 and 4
D). 1 and 2
Answer : Option A

Question 28 :

What will be the output of the program (in jdk1.6 or above)?

public class BoolTest 
{
    public static void main(String [] args) 
    {
        Boolean b1 = new Boolean("false");
        boolean b2;
        b2 = b1.booleanValue();
        if (!b2) 
        {
            b2 = true;
            System.out.print("x ");
        }
        if (b1 & b2) /* Line 13 */
        {
            System.out.print("y ");
        }
        System.out.println("z");
    }
}


A). z
B). x z
C). y z
D). Compilation fails.
Answer : Option B