In addition to literals for all the primitive data types, Java also supports String literals. String literals are objects of Java’s String class.
A String literal is a sequence of characters enclosed by double quotes. One set of quotes “opens” the String literal and the second set of quotes “closes” the literal. For example, these are all String literals:
In a previous episode, We used String literals in output statements to label the data We printed. Something like this:
The + operator is the String concatenation operator. Among other uses, the concatenation operator allows us to print the values of variables along with String literals. The characters in the String literal are output exactly as typed, whereas the variables are replaced by their current value.
String literals cannot extend over more than one line. If the compiler finds a newline character in the middle of your String literal, it will generate a compiler error. In other words, don’t press the enter key when writing out a String. For example, the following statement is not valid:
My IDE, Eclipse, doesn’t even allow me to place an independent end quote at the end of the statement because it detects a newline character in the middle of the String.
In fact, Eclipse, automatically fixes this issue. So if you are using this IDE, then you can get away with pressing enter in the middle of a String. But I mention it because I am not familiar with all other IDE’s. Some, like BlueJ, do not automatically resolve this.
If you have a long String to print, break it into several strings and use the concatenation operator. This statement is a correction of the previous invalid statement:
Another common programming error is omitting the closing quotes. Be sure that all open quotes have matching closing quotes on the same line. Now that we know that quotes open and close String literals, how can we define a literal that includes quotes?
is obviously in error.
Apoptosis of two independent quotes is necessary. Or mitosis into two separate String literals concatenated by a “+” operator.
And since String literals can’t extend over two lines, how can we create a String literal that includes a newline character? Java solves these problems by providing a set of escape sequences that can be used to include a special character within String and char literals. The escape sequences \n, \t, \b, \r, and \f are nonprintable characters. The table below lists the Java escape sequences.
Here, We see how escape sequences can be used in Strings:
And here is the result: