GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||
GeezerVison is showing jenkov.com — Java String Java Language
Java String
The Java String data type can contain a sequence (string) of characters, like pearls on a string. Strings are how you work with text in Java. Once a Java String is created you can search inside it, create substrings from it, create new strings based on the first but with some parts replaced, plus many other things. Internal String Representation
A Java String (before Java 9) is represented internally in the Java VM using bytes, encoded as UTF-16. UTF-16 uses 2 bytes to
represent a single character. Thus, the characters of a Java String are represented using a UTF is a character encoding that can represent characters from a lot of different languages (alphabets). That is why it is necessary to use 2 bytes per character - to be able to represent all these different characters within a single string. Compact Strings
From Java 9 and forward, The Java VM can optimize strings using a new Java feature called compact strings.
The compact strings feature lets the Java VM detect if a string only contains ISO-8859-1/Latin-1 characters. If it does, the
String will only use 1 byte per character internally. The characters of a compact Java String can thus be
represented by a Whether a String can be represented as a compact string or not is detected when the string is created. A String is immutable once created - so this is safe to do. Creating a String
Strings in Java are objects. Therefore you need to use the String myString = new String("Hello World");
The text inside the quotes is the text the String object will contain. Java String LiteralsJava has a shorter way of creating a new String: String myString = "Hello World"; Instead of passing the text "Hello World" as a parameter to the String constructor, you can just write the text itself inside the double quote characters. This is called a String literal. The Java compiler will internally figure out how to create a new Java String representing the given text. Escape CharactersJava Strings literals accepts a set of escape characters which are translated into special characters in the created String. These escape characters are:
Here is an example of creating a Java String using escape characters: String text = "\tThis text is one tab in.\r\n"; This String literal will result in a String that starts with a tab character and ends with a carriage return and a new line character. String Literals as Constants or Singletons
If you use the same string (e.g. String myString1 = "Hello World"; String myString2 = "Hello World";
In this case the Java virtual machine will make both More precisely, objects representing Java String literals are obtained from a constant String pool which the Java virtual machine keeps internally. That means, that even classes from different projects compiled separately, but which are used in the same application may share constant String objects. The sharing happens at runtime. It is not a compile time feature.
If you want to be sure that two String variables point to separate String objects, use the String myString1 = new String("Hello World");
String myString2 = new String("Hello World");
Even though the value (text) of the two Java Strings created is the same, the Java virtual machine will create two different objects in memory to represent them. Java Text BlocksJava text blocks, also known as Java multi line strings, is a feature that was added in Java 13 (in preview) which enables you to more easily declare String literals that span multiple lines in your Java code. To explain the Java text block syntax, look at this Java text block example: String textblock = """
This is a text inside a
text block
""";
Notice the two sets of delimiters ( Both sets of quote characters should be located on their own lines - above and below the actual text to be included in the text block. Only the text on the lines between the lines with the delimiter characters is being included in the resulting Java String. In between the quote delimiters you can write a multi line String without the need to escape new line and quote characters. Here is a Java text block example illustrating the use of quote characters inside the text part of the text block declaration: String textblock = """
This is a text inside a
text block.
You can use "quotes" in here
without escaping them.
""";
Notice the quote characters around the word "quotes". In a normal Java String literal you would have had to escape these characters, but this is not necessary inside of a Java text block. Not unless you want to include 3 consecutive quote characters as part of the text in the text block. Then you need to escape at least one of the quote characters, to enable the Java compiler to tell these characters apart from an end-of-text-block delimiter. Java Text Block IndentationIn the Java text block examples shown earlier, the text between the two lines with the 3 quote delimiters was indented to be located at the same place horizontally as the delimiters. In other words, the text between the delimiters start at the same horizontal position as the delimiters do. This done purely for code formatting reasons! We may not actually want all those indentation characters (spaces or tabs) to be part of the actual String created from this text block! What actually happens is, that the Java compiler strips all of the indentation characters out of the String produced by the Java text block declaration. The way the Java compiler knows how many indentation characters to strip out is by looking at the last line of the text block - the line that contains the last 3 delimiter quote characters. The indentation of the quote characters on this last line determines how many indentation characters the Java compiler strips out of the text inside the text block. Here are 3 Java text block examples using different levels of indentation - controlled by the indentation of the last 3 delimiter quote characters: String textblock1 = """
This is a Java text block
""";
String textblock2 = """
This is a Java text block
""";
String textblock3 = """
This is a Java text block
""";
System.out.println(textblock1);
System.out.println(textblock2);
System.out.println(textblock3);
Notice the different locations of the last 3 quote delimiter characters. In the first Java text block declared the end quote delimiter characters are located at the same indentation position as the text itself. This will result in all indentation characters being stripped out of the resulting Java String. In the second example the last 3 quote delimiter characters are located 2 characters earlier (horizontally) than the text. This means that the Java compiler will leave 2 characters of indentation in the resulting Java String. The rest of the indentation characters will be stripped out. In the last example the last 3 quote delimiter characters are located 4 characters earlier (horizontally) than the text inside the text block declaration. This will the Java compiler leave in 4 characters of indentation in the resulting Java String. Here is the output printed from this Java text block indentation example: This is a Java text block
This is a Java text block
This is a Java text block
As you can see, the resulting strings have different levels of indentation included. As you have probably figured out by now - the difference in the start location of the last 3 delimiter characters and the leftmost character of the text inside the text block determines how much indentation is left inside the Java String produced by the Java text block declaration. In other words, the Java compiler will at the indentation of the text compared to the last 3 delimiter quote characters of the text block to determine the indentation to include. Concatenating StringsConcatenating Strings means appending one string to another. Strings in Java are immutable meaning they cannot be changed once created. Therefore, when concatenating two Java String objects to each other, the result is actually put into a third String object. Here is a Java String concatenation example: String one = "Hello"; String two = "World"; String three = one + " " + two;
The content of the String referenced by the variable String Concatenation PerformanceWhen concatenating Strings you have to watch out for possible performance problems. Concatenating two Strings in Java will be translated by the Java compiler to something like this: String one = "Hello";
String two = " World";
String three = new StringBuilder(one)
As you can see, a new When executed by itself as a single statement, this extra object creation overhead is insignificant. When executed inside a loop, however, it is a different story. Here is a loop containing the above type of String concatenation: String[] strings =
This code will be compiled into something similar to this: String[] strings =
Now, for every iteration in this loop a new
Every time the
The fastest way of concatenating Strings is to create a String[] strings =
This code avoids both the String Length
You can obtain the length of a String using the String string = "Hello World"; int length = string.length(); Substrings
You can extract a part of a String. This is called a substring. You do so using the String string1 = "Hello World"; String substring = string1.substring(0,5);
After this code is executed the
The
The first character in a String has index 0, the second character has index 1 etc. The last character
in the string has has the index Searching in Strings With indexOf()
You can search for substrings in Strings using the String string1 = "Hello World";
int index = string1.indexOf("World");
The
If the substring is not found within the string, the
There is a version of the String theString = "is this good or is this bad?";
String substring = "is";
int index = theString.indexOf(substring);
while(index != -1) {
System.out.println(index);
index = theString.indexOf(substring, index + 1);
}
This code searches through the string " The output printed from this code would be: 0 5 16 21
The substring "
The Java String class also has a String theString = "is this good or is this bad?"; String substring = "is"; int index = theString.lastIndexOf(substring); System.out.println(index);
The output printed from this code would be Matching a String Against a Regular Expression With matches()
The Java String
Here is a String text = "one two three two one";
boolean matches = text.matches(".*two.*");
Comparing StringsJava Strings also have a set of methods used to compare Strings. These methods are:
equals()
The String one = "abc"; String two = "def"; String three = "abc"; String four = "ABC"; System.out.println( one.equals(two) ); System.out.println( one.equals(three) ); System.out.println( one.equals(four) );
The two strings The output printed from the code above would be: false true false equalsIgnoreCase()
The String class also has a method called startsWith() and endsWith()
The String one = "This is a good day to code";
System.out.println( one.startsWith("This") );
System.out.println( one.startsWith("This", 5) );
System.out.println( one.endsWith ("code") );
System.out.println( one.endsWith ("shower") );
This example creates a String and checks if it starts and ends with various substrings.
The first line (after the String declaration) checks if the String starts with the substring "
The second line checks if the String starts with the substring "
The third line checks if the String ends with the substring "
The fourth line checks if the String ends with the substring " compareTo()
The Here is an example: String one = "abc"; String two = "def"; String three = "abd"; System.out.println( one.compareTo(two) ); System.out.println( one.compareTo(three) );
This example compares the -3 -1
The numbers are negative because the
The
You should be aware that the Trimming Strings With trim()
The Java String class contains a method called String text = " And he ran across the field "; String trimmed = text.trim();
After executing this code the "And he ran across the field" The white space characters at the beginning and end of the String object have been removed. The white space character inside the String have not been touched. By inside is meant between the first and last non-white-space character.
The
The Replacing Characters in Strings With replace()
The Java String class contains a method named String source = "123abc";
String replaced = source.replace('a', '@');
After executing this code the 123@bc
The replaceFirst()
The Java String
Here is a String text = "one two three two one";
String s = text.replaceFirst("two", "five");
This example will return the string "one five three two one". replaceAll()
The Java String
Here is a String text = "one two three two one";
String t = text.replaceAll("two", "five");
This example will return the string "one five three five one". Splitting Strings With split()
The Java String class contains a String source = "A man drove with a car.";
String[] occurrences = source.split("a");
After executing this Java code the "A m" "n drove with " " c" "r."
The source String has been split on the
The parameter passed to the
The String String source = "A man drove with a car.";
int limit = 2;
String[] occurrences = source.split("a", limit);
The "A m" "n drove with a car."
The first String is a match of the
Running the example with a limit of "A m" "n drove with " " car."
Notice how the last String still contains the
Running the example above with a limit of 4 or higher would result in only the Split strings being returned, since
there are only 4 matches of the regular expression Converting Numbers to Strings With valueOf()
The Java String class contains a set of overloaded static methods named String intStr = String.valueOf(10);
System.out.println("intStr = " + intStr);
String flStr = String.valueOf(9.99);
System.out.println("flStr = " + flStr);
The output printed from this code would be: intStr = 10 flStr = 9.99 Converting Objects to Strings
The Object class contains a method named Integer integer = new Integer(123); String intStr = integer.toString();
Note: For the Getting Characters and Bytes
It is possible to get a character at a certain index in a String using the String theString = "This is a good day to code"; System.out.println( theString.charAt(0) ); System.out.println( theString.charAt(3) ); This code will print out: T s since these are the characters located at index 0 and 3 in the String.
You can also get the byte representation of the String method using the String theString = "This is a good day to code";
byte[] bytes1 = theString.getBytes();
byte[] bytes2 = theString
The first
The second Converting to Uppercase and Lowercase
You can convert Strings to uppercase and lowercase using the methods
String theString =
String Formatting
From Java 13 the Java String class got a new method named String input = "Hello %s";
String output1 = input.formatted("World");
System.out.println(output1);
String output2 = input.formatted("Jakob");
System.out.println(output2);
This example will first print out "Hello World" and then "Hello Jakob". The parameter values passed to
Strip Indentation
From Java 13 the Java String class got a new method named String input = " Hey \n This \n is \n indented."; String output = input1.stripIndent(); System.out.println(output); The output printed from this example will be: Hey This is indented. Notice how the first 3 characters of indentation on each line have been stripped out. If the indentation is different on each line, the shortest indentation will be stripped out from each line. If, e.g. the last line in the input String was only indented 1 character, only 1 character would be strippe from the indentation of the other lines. Translate Escape Codes
From Java 13 the Java String class got a new method called String input = "Hey, \\n This is not normally a line break."; System.out.println(input); String output = input.translateEscapes(); System.out.println(output);
The escape character
When calling the The output printed from the above code will be: Hey, \n This is not normally a line break. Hey, This is not normally a line break.
Notice how the first line printed shows the Additional MethodsThe String class has several other useful methods than the ones described in this tutorial. You can find them all in the String JavaDoc. Next: Java Operations
Close TOC
All Trails Trail TOC Page TOC Previous Next | ||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. | ||||||||||||||||