Groups of characters in Java are not represented by primitive types as are int or char types. Strings are objects of the String class. The String class is defined in java.lang.String, which is automatically imported for use in every program you write. We’ve used String literals, such as "Enter a value" with System.out.print statements in earlier examples. Now we can begin to explore the String class and the capabilities that it offers.
So far, our experience with Strings has been with String literals, consisting of any sequence of characters enclosed within double quotation marks. For example:
"This is a string"
"Hello World!"
"\tHello World!\n"
The characters that a String object contains can include escape sequences. This tab contains a tab (\t) and a linefeed (\n) character.
A second unique characteristic of the String class is that it supports the "+" operator to concatenate two String expressions. For example:
String sentence = "I " + "want " + "to be a " + "Java programmer.";
The "+" operator can be used to combine a String expression with any other expression of primitive type. When this occurs, the primitive expression is converted to a String representation and concatenated with the string. For example, consider the following instruction sequence:
double PI = 3.14159;
System.out.println("The value of PI is " + PI);
Run Output:
The value of PI is 3.14159
To invoke the concatenation, at least one of the items must be a String.
Last modified: December 12, 2022