String Class (Cont.)
You can also use the concat()
method to concatenate two strings:
String firstName = "John ";
String lastName = "Doe";
System.out.println( firstName.concat( lastName ) ); // Output: John Doe
|
Because strings must be written within quotes, Java will misunderstand this string, and generate an error:
String txt = "We are the so-called "Vikings" from the north.";
|
The solution to avoid this problem is to use the backslash escape character.
The backslash escape character (
\
) turns special characters into string characters.
For example, the sequence
\"
inserts a double quote in a string:
String txt = "We are the so-called \"Vikings\" from the north.";
|
Other escape sequences are valid in Java:
Code |
Result |
Description |
|
Code |
Result |
Description |
|
Code |
Result |
Description |
\' |
' |
Single quote |
\" |
" |
Double quote |
\\ |
\ |
Backslash |
\n |
|
New line |
\r |
|
Carriage return |
\t |
|
Tab |
\b |
|
Backspace |
\f |
|
Form feed |
|
|
|
MyString.java (java.lang.String class)
|
|