The String class represents character strings. All string literals in Java programs, such as “abc”, are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. To create a string variable For example:
more examples of how strings can be used:
System.out.println(“abc”);
There are methods that exist within the String class used to work on strings. Since String variables are immutable, we can use the substring() method to work with a string at the character level to extract characters from the string. The substring method takes two arguments, the first is the starting point and the second is location of character to be extracted. For example, the example below is using substring method to extract a character at location 3.
String c = “abc”.substring(2, 3);
String d = “change”.substring(1, 2);
You can also concatenate strings or characters using the + operator
String concat = “abc” + “123”;
You can check a string to determine if it is empty
“abc”.isEmpty();
This will be false. The isEmpty method returns a value of data type boolean, which is either true or false.
There are many other String methods outside the scope of this discussion used for various situations.
Text Blocks
Text block is a feature introduced in Java 15 to declare multi-line strings most efficiently. With Java 13 and 14, we needed to enable it as a preview feature.
The data type of a text block is still a String.
Text blocks begins with “”” (three double-quote marks) followed by optional whitespaces and a newline and ends with “”” and a semi-colon. A example is shown below:
String textBlock = “””
Example of a text block.
Use it for multi-line strings.”””;
The data type of a text block is still a String.
java.text package
This package contain classes and interfaces for handling text, dates, numbers, and messages in a way that is language independent. This allows the flexibility of adding localizations at any time.
These classes are capable of formatting dates, numbers, and messages, parsing; searching and sorting strings; and iterating over characters, words, sentences, and line breaks. This package contains three main groups of classes and interfaces:
- Classes for iteration over text
- Classes for formatting and parsing
- Classes for string collation
For a complete knowlege of Java see the book preview below: