Creating Strings
1. What Is a String? (beginner)
String = sequence of chars (object, not primitive!). Lives in java.lang (no import). Immutable (can't change — new object each edit!). Two ways to create.
2. Two Ways (exam must-know!)
String s1 = "hello"; // literal (goes to String Pool — reused!)
String s2 = new String("hello"); // new object on Heap (fresh copy!)
String s3 = "hel" + "lo"; // + joins at compile time → "hello"
char[] ch = {'h','i'};
String s4 = new String(ch); // from char array → "hi"
String s5 = ""; // empty (length 0, NOT null!)
String s6 = null; // no object! (s6.length() → crash!)
Pool diagram: s1 and "hello" literal share ONE pooled object; s2 is a separate Heap copy.
3. Beginner Code — Pool Proof
String a = "hi";
String b = "hi";
String c = new String("hi");
System.out.println(a == b); // true (same pooled object!)
System.out.println(a == c); // false (different objects!)
System.out.println(a.equals(c)); // true (same CONTENT — use this!)
4. Traps
==compares addresses (pool accident!),.equals()compares content (always use!).nullString + method →NullPointerException. Empty""is safe (length 0).+in loop creates garbage (many objects!) — useStringBuilder(later topic).
5. Exam Points
- Two ways + pool diagram — 5-7 marks, very frequent.
==vs.equals()proof — 5 marks, all-time favourite.