Java String Escape

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 SequenceDescription
\dddOctal character (ddd)
\uxxxxHexadecimal Unicode character (xxxx)
\'Single quote
\"Double quote
\\Backslash
\rCarriage return
\nNew line
\fForm feed
\tTab
\bBackspace

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 w ww .ja  v  a 2s  .  c  o  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  ww.  jav a2 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.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures