In diesem Tutorial lernen wir anhand von Beispielen Java-Strings, deren Erstellung und verschiedene String-Methoden kennen.
In Java ist eine Zeichenfolge eine Folge von Zeichen. Zum Beispiel ist "Hallo" eine Zeichenfolge, die eine Folge von Zeichen 'h', 'e', 'l', 'l' und 'o' enthält.
Wir verwenden doppelte Anführungszeichen , um eine Zeichenfolge in Java darzustellen. Beispielsweise,
// create a string String type = "Java programming";
Hier haben wir eine Zeichenfolgenvariable mit dem Namen type erstellt. Die Variable wird mit der Zeichenfolge initialisiert Java Programming
.
Hinweis : Strings in Java sind nicht primitive Typen (wie int
, char
usw.). Stattdessen sind alle Zeichenfolgen Objekte einer vordefinierten Klasse mit dem Namen String
.
Alle Zeichenfolgenvariablen sind Instanzen der String
Klasse.
Beispiel: Erstellen Sie einen String in Java
class Main ( public static void main(String() args) ( // create strings String first = "Java"; String second = "Python"; String third = "JavaScript"; // print strings System.out.println(first); // print Java System.out.println(second); // print Python System.out.println(third); // print JavaScript ) )
Im obigen Beispiel haben wir drei Zeichenfolgen erstellt, die als erste, zweite und dritte bezeichnet werden. Hier erstellen wir direkt Zeichenfolgen wie primitive Typen.
Es gibt jedoch eine andere Möglichkeit, Java-Zeichenfolgen zu erstellen (mithilfe des new
Schlüsselworts). Wir werden später in diesem Tutorial mehr darüber erfahren.
Java-String-Operationen
Java String bietet verschiedene Methoden, um verschiedene Operationen an Strings auszuführen. Wir werden uns einige der häufig verwendeten String-Operationen ansehen.
1. Holen Sie sich die Länge eines Strings
Um die Länge eines Strings zu ermitteln, verwenden wir die length()
Methode des Strings . Beispielsweise,
class Main ( public static void main(String() args) ( // create a string String greet = "Hello! World"; System.out.println("String: " + greet); // get the length of greet int length = greet.length(); System.out.println("Length: " + length); ) )
Ausgabe
String: Hallo! Weltlänge: 12
Im obigen Beispiel length()
berechnet die Methode die Gesamtzahl der Zeichen in der Zeichenfolge und gibt sie zurück. Weitere Informationen finden Sie unter Java String length ().
2. Verbinden Sie zwei Saiten
Mit der concat()
Methode können wir zwei Zeichenfolgen in Java verbinden . Beispielsweise,
class Main ( public static void main(String() args) ( // create first string String first = "Java "; System.out.println("First String: " + first); // create second String second = "Programming"; System.out.println("Second String: " + second); // join two strings String joinedString = first.concat(second); System.out.println("Joined String: " + joinedString); ) )
Ausgabe
Erster String: Java Zweiter String: Programmieren Verbundener String: Java-Programmierung
Im obigen Beispiel haben wir zwei Zeichenfolgen mit den Namen first und second erstellt. Beachten Sie die Aussage,
String joinedString = first.concat(second);
Hier verbindet sich die concat()
Methode zuerst und zweitens und weist sie der Variablen joinString zu.
Wir können auch zwei Zeichenfolgen mit dem +
Operator in Java verbinden. Weitere Informationen finden Sie unter Java String concat ().
3. Vergleichen Sie zwei Saiten
In Java können wir mit der equals()
Methode Vergleiche zwischen zwei Zeichenfolgen durchführen . Beispielsweise,
class Main ( public static void main(String() args) ( // create 3 strings String first = "java programming"; String second = "java programming"; String third = "python programming"; // compare first and second strings boolean result1 = first.equals(second); System.out.println("Strings first and second are equal: " + result1); // compare first and third strings boolean result2 = first.equals(third); System.out.println("Strings first and third are equal: " + result2); ) )
Ausgabe
Die ersten und zweiten Zeichenfolgen sind gleich: true Die ersten und dritten Zeichenfolgen sind gleich: false
Im obigen Beispiel haben wir drei Zeichenfolgen erstellt, die als erste, zweite und dritte bezeichnet werden. Hier verwenden wir die equal()
Methode, um zu überprüfen, ob eine Zeichenfolge einer anderen entspricht.
Die equals()
Methode überprüft den Inhalt von Zeichenfolgen, während sie verglichen werden. Weitere Informationen finden Sie unter Java String equals ().
Hinweis : Wir können auch zwei Zeichenfolgen mit dem ==
Operator in Java vergleichen. Dieser Ansatz unterscheidet sich jedoch von der equals()
Methode. Weitere Informationen finden Sie unter Java String == vs equals ().
Methoden von Java String
Neben den oben genannten gibt es in Java verschiedene Zeichenfolgenmethoden. Hier sind einige dieser Methoden:
Methoden | Beschreibung |
---|---|
Teilzeichenfolge () | Gibt den Teilstring des Strings zurück |
ersetzen() | replaces the specified old character with the specified new character |
charAt() | returns the character present in the specified location |
getBytes() | converts the string to an array of bytes |
indexOf() | returns the position of the specified character in the string |
compareTo() | compares two strings in the dictionary order |
trim() | removes any leading and trailing whitespaces |
format() | returns a formatted string |
split() | breaks the string into an array of strings |
toLowerCase() | converts the string to lowercase |
toUpperCase() | converts the string to uppercase |
valueOf() | returns the string representation of the specified argument |
toCharArray() | converts the string to a char array |
Escape character in Java Strings
The escape character is used to escape some of the characters present inside a string.
Suppose we need to include double quotes inside a string.
// include double quote String example = "This is the "String" class";
Since strings are represented by double quotes, the compiler will treat "This is the " as the string. Hence, the above code will cause an error.
To solve this issue, we use the escape character in Java. For example,
// use the escape character String example = "This is the "String " class.";
Now escape characters tell the compiler to escape double quotes and read the whole text.
Java Strings are Immutable
In Java, strings are immutable. This means, once we create a string, we cannot change that string.
To understand it more deeply, consider an example:
// create a string String example = "Hello! ";
Here, we have created a string variable named example. The variable holds the string "Hello! ".
Now suppose we want to change the string.
// add another string "World" // to the previous tring example example = example.concat(" World");
Here, we are using the concat()
method to add another string World to the previous string.
It looks like we are able to change the value of the previous string. However, this is not true
.
Let's see what has happened here,
- JVM takes the first string "Hello! "
- creates a new string by adding "World" to the first string
- assign the new string "Hello! World" to the example variable
- the first string "Hello! " remains unchanged
Creating strings using the new keyword
So far we have created strings like primitive types in Java.
Since strings in Java are objects, we can create strings using the new
keyword as well. For example,
// create a string using the new keyword String name = new String("Java String");
In the above example, we have created a string name using the new
keyword.
Here, when we create a string object, the String()
constructor is invoked. To learn more about constructor, visit Java Constructor.
Note: The String
class provides various other constructors to create strings. To learn more, visit Java String (official Java documentation).
Example: Create Java Strings using the new keyword
class Main ( public static void main(String() args) ( // create a string using new String name = new String("Java String"); System.out.println(name); // print Java String ) )
Create String using literals vs new keyword
Now that we know how strings are created using string literals and the new
keyword, let's see what is the major difference between them.
In Java, the JVM maintains a string pool to store all of its strings inside the memory. The string pool helps in reusing the strings.
While creating strings using string literals, the value of the string is directly provided. Hence, the compiler first checks the string pool to see if the string already exists.
- Wenn die Zeichenfolge bereits vorhanden ist , wird die neue Zeichenfolge nicht erstellt. Stattdessen verweist die neue Referenz auf die vorhandene Zeichenfolge.
- Wenn die Zeichenfolge nicht vorhanden ist , wird die neue Zeichenfolge erstellt.
Doch während Strings Erstellen das neue Schlüsselwort , wird der Wert des Strings nicht direkt zur Verfügung gestellt. Daher wird die neue Zeichenfolge ständig erstellt.