Object-oriented programming · interview question
What does this program print?
What does this code output?Medium
public class Main {
public static void main(String[] args) {
String a = "hello";
String b = "hel" + "lo";
String c = new String("hello");
System.out.println((a == b) + " " + (a == c) + " " + a.equals(c));
}
}Answer and explanation
Correct answer
A. true false true
Why
String literals and compile-time constant expressions are interned, so a and b reference the same object. new String forces a new object. equals compares characters.
Test yourself on Object-oriented programming
A free test with instant, explained results. No account needed.
More Object-oriented programming questions
- In modern Java (8+), when would you choose an abstract class over an interface? Compare the two.
- What issue might arise if a constructor directly assigns a mutable object without copying it?
- What happens if a subclass does not implement all abstract methods from its abstract superclass?
- What does the 'this' keyword refer to within an instance method of a class?
- Which Java keyword would you use to declare an abstract class in Java?
- Which statement correctly creates an instance of the 'Product' class?