String Class (Cont.)
You can also use the concat()
method to concatenate two strings:
1 | String firstName = "John " ; |
2 | String lastName = "Doe" ; |
3 | System.out.println( firstName.concat( lastName ) ); |
|
Because strings must be written within quotes, Java will misunderstand this string, and generate an error:
1 | 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:
1 | 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 |
|
|
|