Java String Literals

Introduction

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

Examples of string literals are

"Hello World"  
"two\nlines"  
" \"This is in quotes\"" 

We can use the same escape sequences and octal/hexadecimal notations defined for character literals in string literals.

Java strings are actually object types.

We can use a string literal to create a String object.

The following code fragment creates two equivalent strings:

char chars[] = { 'a', 'b', 'c' };  
String s1 = new String(chars);  
  
String s2 = "abc"; // use string literal 

String object is created for every string literal, we can use a string literal any place you can use a String object.

System.out.println("abc".length()); //3



PreviousNext

Related