ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
final String a = "Ja";
String b = "Ja";
String x = a + "va";
String y = b + "va";
String z = y.intern();
System.out.print((x == "Java") + " " + (y == "Java") + " "
+ (z == "Java") + " " + y.equals(x));- A. true true true true
- B. false false true true
- C. true false true true
- D. false false false true
Correct answer: C. true false true true
Because a is a final local variable initialised with a constant, a + "va" is a compile-time constant expression; it is folded to "Java" and taken from the string pool, so x == "Java" is true. b is not final, so b + "va" is computed at run time into a new String object: false. intern() returns the pooled instance: true. equals compares contents, so y.equals(x) is true.
More OOP with C++ and Java questions
- What is printed? java class K { int id; K(int id) { this.id = id; } public boolean equals(Object o) { return o instanceof K && ((K) o).id…
- What happens when this code runs? java Integer n = null; boolean flag = true; Integer a = flag ? n : Integer.valueOf(0)…
- Which lines fail to compile? java short s = 1; s = s + 1; // L1 s += 1; // L2 char c = 'A'; c++; // L3 final int k = 10; byte b1 = k; //…
- Which of these four fragments compiles? (FileReader's constructor throws FileNotFoundException, a subclass of IOException.) java // A try…
- What is printed? java class R implements AutoCloseable { public void close() { throw new IllegalStateException("close"); } } // in main…
- What is printed? java class T { static int a = T.b + 1; static int b = 5; static int c = b + 1; } // in main: System.out.print(T.a + " " +…