Java Data Type Tutorial - Java String Type

A sequence of zero or more characters is known as a string.

In Java programs, a string is represented by an object of the java.lang.String class.

The String class is immutable. The contents of a String object cannot be modified after it has been created.

The String class has two companion classes, java.lang.StringBuilder and java.lang. StringBuffer. The companion classes are mutable. We should use them if we want to modify the contents of the string.

String Literals

A string literal consists of a sequence of zero or more characters enclosed in double quotes. All string literals are objects of the String class.

The following lists examples of string literals

""                         // An  Empty string
"Hello"                    // A  string literal  consisting of  5  characters
"Just a string literal"    

We can plus two multiple string literals to a single string literal.

"Hello" + "Hi"

A string literal cannot be broken into two lines.

llo"          // A  compiler error

To break "Hello" in two lines, break it using the string concatenation operator (+).

"He" + "llo"


+ "llo"

Escape Sequence Characters in String Literals

We can use all escape sequence characters to form a string literal.

To include a line feed and a carriage return characters in a string literal. use \n and \r, as shown:

"\n"      // A  string literal  with  a  line  feed
"\r"      // A  string literal  with  a  carriage return

Unicode Escapes in String Literals

A character can also be represented as a Unicode escape in the form \uxxxx, where an x is a hexadecimal digit (0-9 or A-F).

In a string literal, the character 'A', the first uppercase English letter, can also be written as '\u0041', for example, Apple and \u0041pple are treated the same in Java.