String s = "hello";
s = s.toUpperCase();
System.out.println(s);The toUpperCase() method returns a new String with all uppercase letters. Since s is reassigned, the printed value is HELLO.
String a = "test"; String b = new String("test"); System.out.println(a == b); System.out.println(a.equals(b));
The == operator checks if both variables point to the same object, which is false here. The equals() method checks if the contents are the same, which is true.
String result = ""; for (int i = 0; i < 1000; i++) { result += i; } System.out.println(result.length());
Strings in Java cannot be changed once created. Each concatenation creates a new String object, which is slow and uses more memory.
String objects cannot be changed after creation. StringBuilder allows changing the content without creating new objects, making it faster for many modifications.
String s1 = "code"; String s2 = new String("code"); String s3 = s2.intern(); System.out.println(s1 == s2); System.out.println(s1 == s3);
s1 points to the string pool object. s2 is a new object. s3 is the interned version of s2, which points to the string pool object. So s1 == s2 is false, s1 == s3 is true.
