Consider the following Java code snippet:
String s1 = "hello";
String s2 = new String("hello");
System.out.println(s1 == s2);What will be printed?
String s1 = "hello"; String s2 = new String("hello"); System.out.println(s1 == s2);
Remember that == compares references, not content.
The == operator checks if both variables point to the same object. Here, s1 points to a string literal in the string pool, while s2 points to a new String object. So, the result is false.
Look at this code:
StringBuilder sb = new StringBuilder("abc");
sb.append("def");
System.out.println(sb.toString());What will be printed?
StringBuilder sb = new StringBuilder("abc"); sb.append("def"); System.out.println(sb.toString());
Think about what append does to the StringBuilder.
The append method adds the given string to the end of the current content. So, sb becomes "abcdef".
Examine this Java code snippet:
String s = null; int length = s.length(); System.out.println(length);
What error will this code cause when run?
String s = null; int length = s.length(); System.out.println(length);
Think about calling a method on a null reference.
Calling length() on a null String causes a NullPointerException at runtime.
Consider this Java code:
String s1 = new String("test");
String s2 = s1.intern();
String s3 = "test";
System.out.println(s2 == s3);What will be printed?
String s1 = new String("test"); String s2 = s1.intern(); String s3 = "test"; System.out.println(s2 == s3);
Remember what intern() does to a String.
The intern() method returns a reference to the string pool object. Since s3 is the literal "test" in the pool, s2 == s3 is true.
Analyze this Java code snippet:
String s = "a" + "b" + new String("c");How many distinct String objects are created at runtime?
Consider compile-time constants and new String() usage.
The literals "a" and "b" are combined at compile time into "ab" (one object in the pool). The new String("c") creates a new object at runtime. The concatenation creates a new String object at runtime. So total runtime objects created are 2: the new String("c") and the concatenation result.
