Java String 类


Java String Class

Java String Class is one of the most frequently used classes in the Java programming language. String is a sequence of characters. In other programming languages, it’s known as an array of characters. A String in Java is an object that represents a sequence of characters.

Creating a String in Java

A String object can be created in various ways:

Using String Literals

String str = "Hello World!";

Using the new Keyword

String str = new String("Hello World!");

Important String Methods in Java

Some of the important methods available in the String class include:

length()

The length() method of the String class returns the number of characters present in the sequence.

String str = "Hello World!";
int length = str.length(); // length is 12

concat()

The concat() method of the String class concatenates two strings.

String str1 = "Hello";
String str2 = " Java";
String str3 = str1.concat(str2); // str3 is "Hello Java"

indexOf()

The indexOf() method of the String class returns the first index of the specified character or character sequence in a string.

String str = "Hello World!";
int index = str.indexOf("o"); // index is 4

substring()

The substring() method of the String class returns the substring starting from the specified index to the end of the string.

String str = "Hello World!";
String sub = str.substring(6); // sub is "World!"

trim()

The trim() method of the String class removes leading and trailing whitespace from a string.

String str = "   Hello World!   ";
String trimmedStr = str.trim(); // trimmedStr is "Hello World!"

String Immutability

A String object is immutable, which means its value cannot be changed. Once a String object is created, it remains constant and its value cannot be changed. Any operation that appears to change the value of a String object returns a new String object with the new value.

String str = "Hello";
str.concat(" World!"); // returns "Hello World!", but does not change the value of str

String Pool

Java maintains a pool of String objects, also called the string literal pool or string intern pool. String literals are stored in this pool and can be reused whenever required. If two string literals have the same content, they are stored in the same memory location, reducing the memory usage.

String str1 = "Hello";
String str2 = "Hello";
System.out.println(str1 == str2); // prints true as both are pointing to the same memory location in the string pool

Conclusion

In Java, the String class is one of the most commonly used classes, offering a variety of methods to manipulate and extract data from strings in different ways. While being immutable, it has its advantages in terms of performance and memory usage. Understanding the workings of the String class is crucial to developing efficient and effective Java programs.