Logo
Section 1 / 15

Java 中的字符串理解

学习 String 类如何表示不可变文本,执行精确比较,并使用基本方法操作字符数据。

导入

Java 中的字符串理解

学习 String 类如何表示不可变文本,执行精确比较,并使用基本方法操作字符数据。

1public class StringCreation { 2 public static void main(String[] args) { 3 // Method 1: String Literal (Recommended) 4 // Stored in the String Pool 5 String s1 = "Java"; 6 String s2 = "Java"; // Reuses the same object as s1 7 8 // Method 2: Using 'new' (Avoid unless necessary) 9 // Forces a new object on the Heap, outside the Pool 10 String s3 = new String("Java"); 11 12 // Comparing references (addresses), NOT content 13 System.out.println("s1 == s2: " + (s1 == s2)); // true (Same pool object) 14 System.out.println("s1 == s3: " + (s1 == s3)); // false (Different objects) 15 } 16}
...
String literals in the Constant Pool vs. string objects in the Heap
1public class StringImmutability { 2 public static void main(String[] args) { 3 String greeting = "Hello"; 4 5 // We attempt to modify the string 6 greeting.concat(", World"); 7 System.out.println("After concat (ignored): " + greeting); 8 9 // We must reassign the variable to store the change 10 greeting = greeting.concat(", World"); 11 System.out.println("After reassignment: " + greeting); 12 } 13}
1public class StringConcat { 2 public static void main(String[] args) { 3 String firstName = "Ada"; 4 String lastName = "Lovelace"; 5 int year = 1815; 6 7 // Concatenating strings and numbers 8 String profile = firstName + " " + lastName + " (Born: " + year + ")"; 9 10 System.out.println(profile); 11 } 12}
1public class StringFormatting { 2 public static void main(String[] args) { 3 String product = "Laptop"; 4 double price = 999.9985; 5 int stock = 5; 6 7 // Using String.format (Static method) 8 String label = String.format("Item: %s | Price: $%.2f | Stock: %d", product, price, stock); 9 10 // Using .formatted (Instance method - Java 15+) 11 String modernLabel = "Item: %s | Price: $%.2f | Stock: %d".formatted(product, price, stock); 12 13 System.out.println(label); 14 System.out.println(modernLabel); 15 } 16}
1public class StringComparison { 2 public static void main(String[] args) { 3 String literal = "password"; 4 String input = new String("password"); // Simulates user input 5 6 // WRONG: Comparing memory addresses 7 if (literal == input) { 8 System.out.println("Access Granted (==)"); 9 } else { 10 System.out.println("Access Denied (==)"); // This executes 11 } 12 13 // CORRECT: Comparing text content 14 if (literal.equals(input)) { 15 System.out.println("Access Granted (.equals)"); // This executes 16 } 17 } 18}

Collections Framework

字符串操作