Java String type
In this chapter you will learn:
- How to declare Java String type
- How to escape Java String Literals
- Java strings must begin and end on the same line
- How to declare string arrays
String type
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);/* j a v a 2s. c om*/
}
}
The output:
String literals in Java are specified by enclosing a sequence of characters between a pair of double quotes. In Java strings are actually object types.
Escape String Literals
The escape sequences are used to enter impossible-to-enter-directly strings.
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.
The following table summarizes the Java String escape sequence.
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 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 = "demo2s.com";
System.out.println("s is " + s);
/*from j a v a 2 s . com*/
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:
String must be in the same line
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.
public class Main {
public static void main(String[] argv){
String s = "line 1//from j a va 2s .co m
line 2
";
}
}
If you try to compile this program, the compiler will generate the following error message.
Arrays of strings
You can define String array as you define the int array. For example:
public class Main {
public static void main(String args[]) {
String str[] = {"one", "two", "three","demo2s.com"};
/*from j av a 2 s . c o m*/
for (int i = 0; i < str.length; i++)
System.out.println("str[" + i + "]: " + str[i]);
}
}
Here is the output from this program:
Next chapter...
What you will learn in the next chapter:
- How to add strings together
- How to concatenate String with other data types
- How to concatenate one string to the other with concat method