Java Quiz (1)

There is a small Java quiz:

Q1.
public class InitTest {
  static
 {
  System.out.println(“VALUE1 = ” + VALUE);
  VALUE += 200;
  System.out.println(“VALUE2 = ” + VALUE);
 }
 

public static int VALUE = 100;
 

 public InitTest() {
  System.out.println(“VALUE3 = ” + VALUE);
  VALUE += 300;
  System.out.println(“VALUE4 = ” + VALUE);
 }
 
 public static void main(String args[]) {
  new InitTest();
  new InitTest();
 }
}
Output: Compile Error as VALUE is not defined.

Q2.
public class InitTest {
 public static int VALUE = 100;
 
 static
 {
  System.out.println(“VALUE1 = ” + VALUE);
  VALUE += 200;
  System.out.println(“VALUE2 = ” + VALUE);
 }
 
 public InitTest() {
  System.out.println(“VALUE3 = ” + VALUE);
  VALUE += 300;
  System.out.println(“VALUE4 = ” + VALUE);
 }
 
 public static void main(String args[]) {
  new InitTest();
  new InitTest();
 }
}

Output:
VALUE1 = 100
VALUE2 = 300
VALUE3 = 300
VALUE4 = 600
VALUE3 = 600
VALUE4 = 900
Q3.
String a = “abc”;
String b = new String(“abc”);
String c = “abc”;
System.out.println(a==b);
System.out.println(a==c);
System.out.println(a.equals(b));

Output:
false
true
true

Q4.
String a=null;
if (a!=null && a.length()>10) {
   System.out.println(“pass”);
} else {
   System.out.println(“fail”);
}

Output:
fail

Q5.
String a=null;
if (a!=null & a.length()>10) {
   System.out.println(“pass”);
}

Output:
NullpointException

Q6.
int i = -1;
System.out.println(i>>31);
i = -1;
System.out.println(i>>>31);

output:
-1
1

Q7.
try {
  System.out.println(“Pass 1″);
  System.exit(0);
  System.out.println(“Pass 2″);
}finally {
  System.out.println(“Pass 3″);
}

Output:
Pass 1

Q8.
try {
  System.out.println(“Pass 1″);
  return;
  System.out.println(“Pass 2″);
}finally {
  System.out.println(“Pass 3″);
}

Output:
Pass 1
Pass 3

Q9.
byte a = 100;
a = a + 20;
System.out.println(a);

Output:
Compile Error while convert int to byte in line 2

Q10.
try {
  RandomAccessFile raf = new RandomAccessFile(“c:\\file.txt”, “r”);
  System.out.println(“Open”);
  raf.read();
  System.out.println(“Read”);
} catch (IOException ex) {
  ex.printStackTrace();
} catch (FileNotFoundException ex) {
  ex.printStackTrace();
} catch (Exception ex) {
  ex.printStackTrace();
} finally {
  System.out.println(“Finally”);
}

Output:
Compile error because FileNotFoundException should be caught before IOException as it is subclass of IOEXception.

Comments are closed.