Mega Code Archive

 
Categories / Java Book / 003 Essential Classes
 

0177 String type and Literals

The String class represents character strings. A quoted string constant can be assigned to a String variable. public class Main{ public static void main(String[] argv){ String str = "this is a test"; System.out.println(str); } } The output: this is a test String literals in Java are specified by enclosing a sequence of characters between a pair of double quotes. The escape sequences are used to enter impossible-to-enter-directly strings. "\"" 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 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 Examples of string literals are "Hello World" "two\nlines" "\"This is in quotes\"" Examples of string literals are: public class Main { public static void main(String[] argv) { String s = "rntsoft.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 rntsoft.com s is two lines s is "quotes"