String Literals

String literals are specified by enclosing a sequence of characters between a pair of double quotes.

Examples of string literals are:


public class Main {
  public static void main(String[] argv) {
    String s = "java2s.com";
    System.out.println("s is " + s);

    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:


s is java2s.com
s is two
lines
s is "quotes"

The escape sequences and octal/hexadecimal notations defined for character literals work the same way inside of string literals.

Java strings must begin and end on the same line.



public class Main {
  public static void main(String[] argv){
     String s = "line 1
                 line 2
                ";

  }
}

If you try to comiple this program, the compiler will generate the following error message.


D:\>javac Main.java
Main.java:3: unclosed string literal
     String s = "line 1
                ^
Main.java:4: not a statement
                 line 2
                 ^
Main.java:4: ';' expected
                 line 2
                     ^
Main.java:5: unclosed string literal
                ";
                ^
4 errors

In Java strings are actually object types.

java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.