What does this print?
String a = "java";
String b = new String("java");
System.out.println((a == b) + " " + a.equals(b));new String creates a distinct heap object, so == (reference comparison) is false, while equals compares characters.
Strings, equality, inheritance, exceptions, generics and initialization order.
Pick an answer to see instantly whether you're right, with an explanation. Questions are shuffled every attempt.
String a = "java";
String b = new String("java");
System.out.println((a == b) + " " + a.equals(b));new String creates a distinct heap object, so == (reference comparison) is false, while equals compares characters.
Integer x = 127, y = 127;
Integer p = 128, q = 128;
System.out.println((x == y) + " " + (p == q));Autoboxing uses Integer.valueOf, which caches -128..127. 128 creates two separate objects, so == is false. Always use equals for boxed values.
Java is always pass-by-value. For objects the copied value is the reference, so methods can mutate the object but reassigning the parameter has no effect on the caller.
Overload resolution happens at compile time using declared types. Overriding is the one resolved at runtime.
equals but not hashCode. What is the most likely symptom?Equal objects get different identity hash codes, so hash-based collections look in the wrong bucket.
IOException extends Exception but not RuntimeException, so it must be caught or declared. The others are unchecked.
static int f() {
try { return 1; }
finally { return 2; }
}A return in finally overrides the earlier return value (and would also swallow any exception) — which is why you should never return from finally.
close() throw, what happens?The primary exception wins and close failures are available via getSuppressed().
new Child()?class Parent {
Parent() { show(); }
void show() { System.out.println("parent"); }
}
class Child extends Parent {
String name = "child";
@Override void show() { System.out.println(name); }
}The parent constructor runs before the child’s field initialisers, so the overridden show() sees name == null. Never call overridable methods from constructors.
List<Integer>, a List<Double> and a List<Number> for reading numbers?Generics are invariant, so List<Number> won’t accept List<Integer>. A producer you read from uses ? extends (PECS).
Generic methods are perfectly legal. The other three are restrictions caused by erasing type arguments at runtime.
final classes such as String and all records cannot be extended.
default method. What must it do?Unless a superclass method or a more specific interface resolves it, the compiler forces the class to override and pick an implementation.
StringBuilder instead of +=?Strings are immutable, so every concatenation copies all previous characters. StringBuilder appends in place (and is not thread-safe).
int values?Subtraction overflows for large or negative values, and option B never returns a negative number. Integer.compare is correct.
You scored 0 out of 15.