Chapter: missed questions Flashcards

1
Q

True or False:

If a Thread’s priority is not specified explicitly then it gets a priority of Thread.NORM_PRIORITY

A

In such a case, the Thread gets the same priority as the thread that has created it.
So if a thread t1 having a priority Thread.MAX_PRIORITY creates a thread t2, t2 will also get a priority of Thread.MAX_PRIORITY.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Considering the following code what is the result:
class Person {
String name;
public Person(String name) { this.name = name; }
}

class MyClass {
   TreeSet set = new TreeSet();
   public static void main(String... args) {
      set.add(new Person("Math"));
      System.out.println("added Math");
      set.add(new Person("Peter"));
      System.out.println(set);
   }
}
A

It will first print added math.

Then it will throw a ClassCastException as Person does not implement the Comparable interface. The TreeSet is a sortedset so it needs to use the compareTo method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which of these group of statements are valid?

  1. { { } }
  2. { continue ; }
  3. block : { break block ; }
  4. block : { continue block ; }
  5. The break keyword can only be used if there exists an enclosing loop construct ( i.e. while, do-while or for ).
A

1 and 3 are valid

Continue can only be used in loops.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the result?

class Game
{
  public void play() throws Exception
  {
    System.out.println("Playing...");
  }
}
public class Soccer extends Game
{
   public void play()
   {
      System.out.println("Playing Soccer...");      
   }
   public static void main(String[] args)
   {
       Game g = new Soccer();
       g.play();
   }
}
A

It will not compile.

It does not override play() properly, missing throws clause.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
What is the result?
class Test
{
   public static void main(String[] args)
   {
      int i = 4;
      int ia[][][] = new int[i][i = 3][i];
      System.out.println( ia.length + ", " + ia[0].length+", "+ ia[0][0].length);
   }
}
A

4,3,3

In an array creation expression, there may be one or more dimension expressions, each within brackets. Each dimension expression is fully evaluated before any part of any dimension expression to its right. The first dimension is calculated as 4 before the second dimension expression sets ‘i’ to 3.
Note that if evaluation of a dimension expression completes abruptly, no part of any dimension expression to its right will appear to have been evaluated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Which of these are not part of the StringBuffer class?

trim()
ensureCapacity(int )
append(boolean )
reverse( )
setLength(int)
A

trim();

It’s part of the String class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Consider the following code:

public class FinalizeTest {
    private String value;
    public FinalizeTest(String text) {
        this.value = text;
    }
    public static void main(String[] args) {
        FinalizeTest f1 = new FinalizeTest("Hello");
        FinalizeTest f2 = new FinalizeTest("World");
        f1 = null;
        f2 = null;
    }
    public void finalize(){
        System.out.println(this.value);
        super.finalize();
    }
}

Which of the following statements correctly describe the behavior this class when it is run?

1.
hello
world 
is a possible output.
2. It will never produce any output.  
3. It will not compile.
4. It will throw an exception at run time.
A

super.finalize() throws a Throwable, so should either be try-catched or added to the throws clause.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the result?

public class TestClass
{
	public static int getSwitch(String str)
	{
	    return (int) Math.round( Double.parseDouble(str.substring(1, str.length()-1)) );
	}
	public static void main(String args [])
	{
		switch(getSwitch(args[0]))
		{
			case 0 : System.out.print("Hello ");
			case 1 : System.out.print("World"); break;
			default : System.out.print(" Good Bye");
		}
	}
}
A

Hello World

str.substring(1, str.length()-1) => “–0.50”.substring(1, (6-1) ) => -0.5
Math.round(-0.5) = 0.0
so getSwitch(…) returns 0 if passed an argument of “–0.50”.
Now, there is no “break” in case 0 of switch. so the control falls through to the next case ( ie. case 1) after printing Hello. At case 1, it prints World. And since there is a break. default is not executed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What should be the return type of the following method?

public RETURNTYPE methodX( byte by)
{
    double d = 10.0;
    return (long) by/d*3;
}
A

double

Note that the cast (long) applies to ‘by’ not to the whole expression.
( (long) by ) / d * 3;
Now, division operation on long gives you a double. So the return type should be double.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Consider the following class…

class TestClass
{
   static int x;
   public static void main(String[] args)
   {
      System.out.println(this.x);
   }
}
A

main method is a static method, so it has no reference to this.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Consider the following code:

class Super { static String ID = "QBANK"; }
class Sub extends Super
{
   static { System.out.print("In Sub"); }
}
class Test
{
   public static void main(String[] args)
   {
      System.out.println(Sub.ID);
   }
}

What will be the output when class Test is run ?

A

It will print ‘In Sub’ and ‘QBANK’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What will be the result of attempting to compile and run the following program?

public class TestClass
{
   public static void main(String args[ ] )
   {
      StringBuffer sb = new StringBuffer("12345678");
      sb.setLength(5);
      sb.setLength(10);
      System.out.println(sb.length());
   }
}
A

It will print 10.

Although it truncates the string to length 5 but setLength(10) will append 5 spaces (actually null chars ie. \u0000).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What can be returned by the return statement of methodX()?
publicbyte methodX() {
return INSERT_CODE_HERE; }

  1. 1000
  2. 10
  3. new Integer(10);
  4. new Byte(10);
A
  1. 10

Since the return type is byte, the return value must fit into a byte (A byte has a range of -128 to 127). Therefore 1000 cannot be a valid value. Further, an Integer object cannot be unboxed to a byte. But new Byte((byte)10);, would be valid. Had the return type been int, return new Integer(0); would have been valid.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What happens when a thread executes wait() method on an object without owning the object’s lock?

A

If the thread does not own the lock, it throws an IllegalMonitorStateException upon calling wait().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Given:
enum Season { SUMMER, WINTER, SPRING, FALL }

What will the following code print?

    Season s = Season.SPRING;
    switch(s)
    {
        case SUMMER : System.out.println("SUMMER");
        case default : System.out.println("SEASON");
        case WINTER :  System.out.println("WINTER");
    }
A

case default : System.out.println(“SEASON”); is syntactically wrong. It should just be:
default : System.out.println(“SEASON”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Given the following declarations:
int a = 5, b = 7, k = 0;
Integer m = null;

Identify the correct statements.

  1. k = new Integer(a) + new Integer(b); will not compile.
  2. k = new Integer(a) + b; will throw an exception at runtime.
  3. k = b + new Integer(a); will not compile.
  4. m = new Integer(a) + new Integer(b); will not compile.
  5. m = new Integer(a) + new Integer(b); will assign 12 wrapped in Integer object to m.
  6. k = b + new Integer(a); will assign 12 to k.
A

5 & 6

In all of these cases, auto-unboxing of Integer objects will occur. For m = new Integer(a) + new Integer(b);, after unboxing a and b, the value 12 will be boxed into an Integer object.

17
Q

Consider the following code:

public class Varargs
{
   public void test()
   {
        test1(10, 20);  //1
   }

public void test1(int i, int… j){ System.out.println(“1”); }
public void test1(int… i ){ System.out.println(“2”); }
public void test1(int i, int j){ System.out.println(“3”); }

   public static void main(String[] args)
   {
     new Varargs().test();
   }

}

What will the program print?

A

3

In cases where multiple methods are applicable, the compiler always calls the most specific one. In this case, the third one is the most specific one.

If no method is more specific than the other, then the compilation fails. For example, if the class did not have the third method test1(int i, int j), then the remaining two methods would have been equally applicable and equally specific. In that case, it would not compile.

18
Q

The following code snippet will print true.

String str1 = “one”;
String str2 = “two”;
System.out.println( str1.equals(str1=str2) );

True or false?

A

False

First the value of ‘str1’ is evaluated (i.e. one). Now, before the method is called the operands are evaluated, so str1 becomes “two”. so “one”.equals(“two”) is false.

19
Q

Consider the following code:

class OuterWorld
{
  public InnerPeace i = new InnerPeace();
  private class InnerPeace
  {  
   private String reason = "none";
  }
}

What can be the class of an object ‘x’ that can access ‘reason’?

  1. Any subclass of OuterWorld.
  2. OuterWorld
  3. Only InnerPeace.
  4. Any class.
  5. Any class in the same package.
A
  1. OuterWorld

The wordings of this question are difficult to understand. However, expect similar questions on the exam. The question is essentially asking where all is the ‘reason’ field accessible. Obviously, it is accessible within InnerPeace class. But it is also accessible in OuterWorld as shown in option 2.

20
Q

Consider the following method:

    static int mx(int s)
    {
        for(int i=0; i<3; i++)
        {
            s = s + i;
        }
        return s;
    }

and the following code snippet:

   int s = 5;
    s += s + mx(s) + ++s;
    System.out.println(s); 

What will it print?

A

24

s += (expression) will be converted to s =  s + expression. So the given expression will become:
s = s + s + mx(s) + ++s;
s = 5 + 5 + mx(5) + 6;
s = 5 + 5+ 8 + 6;
s = 24;
21
Q
class InitTest
{
   public static void main(String[] args)
   {
      int a = 10;
      int b = 20;
      a += (a = 4);
      b = b + (b = 5);
      System.out.println(a+ "  "+b);
   }
}
A

It will print 14, 25

a += (a =4) is same as a = a + (a=4).
First, a’s value of 10 is kept aside and (a=4) is evaluated. The statement (a=4) assigns 4 to a and the whole statement returns the value 4. Thus, 10 and 4 are added and assigned back to a.

Same logic applies to b = b + (b = 5); as well.

22
Q

What can be called to ask the JVM to do a garbage collection run?

A

System.gc();

Runtime.getRuntime().gc();

23
Q

How many times will the line marked //1 be called in the following code?

	int x = 10;
	do
	{
	  x--;
	  System.out.println(x);  // 1
	}while(x<10);
  1. 0
  2. 1
  3. 9
  4. 10
  5. None of these
A
  1. None of these

As you can see, x keeps on decreasing by one in each iteration and every time the condition x<10 returns true. However, after x reaches -2147483648, which is its MIN_VALUE, it cannot decrease any further and at this time when x– is executed, the value rolls over to 2147483647, which is Integer.MAX_VALUE. At this time, the condition x<10 fails and the loop terminates.

24
Q

What will the following program print when run using the command line:
java TestClass

public class TestClass {

    public static void methodX() throws Exception { 
	throw new AssertionError();
    }  
    public static void main(String[] args) {
	try{ 
	    methodX(); 
	} 
	catch(Exception e) {
	    System.out.println("EXCEPTION");
	}
     }
}
A

It will throw AssertionError out of the main method.

25
Q

Assuming that the value of Math.PI is 3.1415930000 and Math.E is2.7182828282, what will the following line of code print?
System.out.printf(“%f %b”, Math.PI, Math.E);

A

3.141593true

The default number of decimals that %f prints is 6, so for Math.PI, 3.141593 is printed. The rule for %b is : If the argument is null, then the result is “false”. If argument is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is “true”. So for Math.E, true is printed.