杰瑞科技汇

String是Java中的基本类型吗?

Of course! java.lang.String is one of the most fundamental and widely used classes in the Java programming language. Let's break it down comprehensively.


What is java.lang.String?

In simple terms, a String in Java is a sequence of characters. It's used to represent text.

Key Characteristics:

  • Immutability: This is the single most important feature of java.lang.String. Once a String object is created, its contents cannot be changed.

    • Any operation that appears to modify a string (like toUpperCase(), replace(), or concat()) actually returns a new String object with the modified content. The original string remains unchanged.
    • This makes String objects thread-safe and allows the Java Virtual Machine (JVM) to optimize memory usage, for example, by using a "String Pool" (see below).
  • Final Class: The String class is declared as final. This means:

    • You cannot create a subclass of String.
    • You cannot override its methods, ensuring its behavior is consistent and cannot be altered by other code.
  • char Array Internally: A String is internally implemented as a final array of characters (private final char[] value). This final modifier is the reason for its immutability—you can't change the reference to the character array after it's created.


How to Create a String

There are two main ways to create a String object: using a string literal and using the new keyword.

a) Using String Literals (Recommended)

This is the most common and efficient way. String literals are stored in a special memory area in the JVM called the String Pool.

String s1 = "Hello, World!";
String s2 = "Hello, World!";

In this case, both s1 and s2 will refer to the same object in the String Pool, saving memory. The JVM checks the pool first to see if the literal already exists.

b) Using the new Keyword

This creates a new String object in the heap memory, regardless of whether an identical string already exists in the pool.

String s3 = new String("Hello, World!");
String s4 = new String("Hello, World!");

Here, s3 and s4 will refer to two different objects in the heap. This is generally less efficient than using literals.


Immutability in Action

Let's see what happens when you try to "modify" a string.

String original = "Java";
System.out.println("Original: " + original); // Output: Original: Java
System.out.println("Hash Code: " + original.hashCode()); // e.g., 2306637
// The toUpperCase() method does NOT change 'original'
String modified = original.toUpperCase();
System.out.println("Modified: " + modified);   // Output: Modified: JAVA
System.out.println("Original (unchanged): " + original); // Output: Original (unchanged): Java
System.out.println("Original Hash Code: " + original.hashCode()); // Hash code is the same

As you can see, original remains "Java". The toUpperCase() method created a brand new string "JAVA" and assigned it to the modified variable.


Common Methods

String provides a rich set of methods for manipulation and inspection.

Category Method Description Example
Length & Index length() Returns the number of characters. "Java".length() -> 4
charAt(int index) Returns the character at a specific index. "Java".charAt(1) -> 'a'
indexOf(String s) Returns the first index of a substring. "Java".indexOf("av") -> 1
Comparison equals(Object obj) Compares content for equality. "Java".equals("java") -> false
equalsIgnoreCase(String s) Compares content, ignoring case. "Java".equalsIgnoreCase("java") -> true
compareTo(String s) Lexicographically compares two strings. "apple".compareTo("banana") -> -1 (apple comes before banana)
contains(CharSequence s) Checks if the string contains a sequence. "Hello".contains("ell") -> true
Modification substring(int beginIndex) Returns a substring. "Hello".substring(1) -> "ello"
replace(char old, char new) Replaces all occurrences of a character. "Hello".replace('l', 'p') -> "Heppo"
toUpperCase() / toLowerCase() Converts case. "Java".toUpperCase() -> "JAVA"
trim() Removes leading/trailing whitespace. " Java ".trim() -> "Java"
Splitting & Joining split(String regex) Splits the string into an array based on a regular expression. "a,b,c".split(",") -> ["a", "b", "c"]
join(CharSequence delimiter, CharSequence... elements) Joins elements with a delimiter. String.join("-", "2025", "10", "27") -> "2025-10-27"

The StringBuilder and StringBuffer (When Immutability is a Problem)

Because String is immutable, operations like repeated concatenation are very inefficient. Each concatenation () creates a new String object in memory.

// Inefficient for loops
String text = "";
for (int i = 0; i < 1000; i++) {
    text = text + "a"; // Creates a new String object in each iteration
}

For these scenarios, Java provides mutable alternatives:

StringBuilder

  • Mutable: Its content can be modified after creation.
  • Not Thread-Safe: Not synchronized. Use it when you are sure that only one thread will be modifying the string (e.g., inside a method).
  • Faster: Faster than StringBuffer because it has no overhead from synchronization.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append("a"); // Modifies the same StringBuilder object
}
String result = sb.toString(); // Converts to a String when done

StringBuffer

  • Mutable: Its content can be modified after creation.
  • Thread-Safe: All its public methods are synchronized. Use it in multi-threaded environments where multiple threads might modify the same string.
  • Slower: Slower than StringBuilder due to synchronization overhead.

The String Pool (Intern Pool)

The String Pool is a special storage area in the heap memory that helps Java save memory by reusing String literals.

// Using literals
String s1 = "hello";
String s2 = "hello";
// s1 and s2 point to the SAME object in the pool
System.out.println(s1 == s2); // Output: true
// Using 'new'
String s3 = new String("hello");
String s4 = new String("hello");
// s3 and s4 are DIFFERENT objects in the heap
System.out.println(s3 == s4); // Output: false
// s1 and s3 point to different objects (one in pool, one in heap)
System.out.println(s1 == s3); // Output: false

You can explicitly add a string to the pool using the intern() method.

String s5 = new String("hello").intern();
System.out.println(s1 == s5); // Output: true (now s5 points to the pooled object)

Summary

Feature Description
Purpose To represent and manipulate sequences of characters.
Immutability A core feature. Once created, a String object cannot be changed. Operations return new String objects.
Creation Via literals (efficient, pooled) or new keyword (less efficient, on the heap).
Performance Good for static text. Poor for frequent modifications in loops.
Alternatives Use StringBuilder for single-threaded performance and StringBuffer for thread-safe operations.
Class Type A final class, meaning it cannot be extended.
分享:
扫描分享到社交APP
上一篇
下一篇