Java String Escape
In this chapter you will learn:
- How to escape Java String Literals
- Syntax for String escape
- List value for string escape
- Example - Escape string value
- Example - Java strings must begin and end on the same line
Description
The escape sequences are used to enter impossible-to-enter-directly strings.
Syntax
For example, "\"
" is for the double-quote character.
"\n
" for the newline string.
For octal notation, use the backslash followed by the three-digit number.
For example, "\141
" is the letter "a".
For hexadecimal, you enter a backslash-u (\u
), then exactly four hexadecimal digits.
For example, "\u0061
" is the ISO-Latin-1
"a
" because the top byte is zero.
"\ua432
" is a Japanese Katakana character.
Escape List
The following table summarizes the Java String escape sequence.
Escape Sequence | Description |
---|---|
\ddd | Octal character (ddd) |
\uxxxx | Hexadecimal Unicode character (xxxx) |
\' | Single quote |
\" | Double quote |
\\ | Backslash |
\r | Carriage return |
\n | New line |
\f | Form feed |
\t | Tab |
\b | Backspace |
Example
Examples of string literals with escape are
"Hello World"
"two\nlines"
"\"This is in quotes\""
The following example escapes the new line string and double quotation string.
public class Main {
public static void main(String[] argv) {
String s = "java2s.com";
System.out.println("s is " + s);
//from ww w.j a va 2s . co m
s = "two\nlines";
System.out.println("s is " + s);
s = "\"quotes\"";
System.out.println("s is " + s);
}
}
The output generated by this program is shown here:
Example 2
Java String literials must be begin and end on the same line. If your string is across several lines, the Java compiler will complain about it.
/*from w w w . ja v a 2 s . c o m*/
public class Main {
public static void main(String[] argv){
String s = "line 1
line 2
";
}
}
If you try to compile this program, the compiler will generate the following error message.
Next chapter...
What you will learn in the next chapter:
- How to add strings together
- Example - Java String Concatenation
- Example - uses string concatenation to create a very long string
- Example - How to concatenate String with other data types
- Example - mix other types of operations with string concatenation