Module lessons (3/3)
Strings, String Pool and Arrays
String Memory and Contiguous Arrays
Avoid incorrect comparisons with == and quadratic allocations by looking at String Pool and Heap live.
Unlike int or boolean, in Java a String is an immutable object: once created on the Heap or in the String Pool, its characters can never change.
1. String Internal Pool: why == cheats on String
When you write a literal like "Java", the JVM saves it in a special area called String Pool to share it among identical variables. By using new String("Java") instead, you force the allocation of a distinct object on the General Heap:
public class Main {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java"; // Riusa lo stesso riferimento nello String Pool!
String s3 = new String("Java"); // Crea un secondo oggetto nello Heap
System.out.println(s1 == s2); // true (stesso indirizzo nel Pool)
System.out.println(s1 == s3); // false (indirizzi diversi!)
System.out.println(s1.equals(s3)); // true (confronta i caratteri!)
}
}2. Interactive Simulator: String Pool vs Heap and StringBuilder
Step through the String Pool (== vs .equals) scenario and then move on to Immutability String vs StringBuilder to see why + in loops creates temporary objects while StringBuilder mutates the same buffer.
3. Common Operations on String and StringBuilder
All methods of String (toUpperCase(), trim(), replace(), substring()) return a new string leaving the original intact:
String raw = " Java 21 ";
String clean = raw.trim().toUpperCase(); // raw vale ancora " Java 21 "
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
sb.append("item").append(i);
if (i < 3) sb.append(",");
}
String csv = sb.toString(); // "item1,item2,item3"4. Static Arrays and the Utility Class Arrays
An array (int[], String[]) has a fixed length chosen upon creation, accessible via the field .length (without brackets!):
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] scores = { 90, 70, 85 };
Arrays.sort(scores);
int[] copy = Arrays.copyOf(scores, scores.length);
System.out.println(scores.length); // 3
System.out.println(Arrays.toString(copy)); // [70, 85, 90]
}
}To fill an array with a predefined value or quickly search a sorted array, Arrays.fill and Arrays.binarySearch offer ready and readable operations:
int[] zeros = new int[4];
Arrays.fill(zeros, -1); // [-1, -1, -1, -1]
int[] ordered = { 10, 20, 30, 40 };
int index = Arrays.binarySearch(ordered, 30); // indice 2Try it yourself
Complete the comparison between expected and actual using .equals() null-safely (expected.equals(actual)), saving it to sameText, and printing it.
Show hint
Use boolean sameText = expected.equals(actual); and print it with System.out.println(sameText);.
Solution available after 3 attempts
Use StringBuilder to hang "Hi" and "!" in the same buffer and print the final result via .toString().
Show hint
Instantiate StringBuilder sb = new StringBuilder();, call .append("Hi").append("!"), and print sb.toString().
Solution available after 3 attempts
Sort the nums array with Arrays.sort(nums) and print its elements formatted with Arrays.toString(nums).
Show hint
Call Arrays.sort(nums); and then System.out.println(Arrays.toString(nums));.
Solution available after 3 attempts
What does this fragment print about the immutability of String?
String greeting = "java";
greeting.toUpperCase();
System.out.println(greeting);What is the value printed for a == b and a.equals(b)?
String a = "OK";
String b = new String("OK");
System.out.println((a == b) + " " + a.equals(b));