Java String Escape

In this chapter you will learn:

  1. How to escape Java String Literals
  2. Syntax for String escape
  3. List value for string escape
  4. Example - Escape string value
  5. 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 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   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:

  1. How to add strings together
  2. Example - Java String Concatenation
  3. Example - uses string concatenation to create a very long string
  4. Example - How to concatenate String with other data types
  5. Example - mix other types of operations with string concatenation
Home »
  Java Tutorial »
    Java Langauge »
      Java Data Types
Java Primitive Data Types
Java boolean type
Java char type
Java char value escape
Java byte type
Java short type
Java int type
Java long type
Java float type
Java double type
Java String type
Java String Escape
Java String Concatenation