String Concatenation
You can use + operator to concatenate strings together.
For example, the following fragment concatenates three strings:
public class Main {
public static void main(String[] argv) {
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
}
}
He is 9 years old.
Use string concatenation to create a very long string.
public class Main {
public static void main(String args[]) {
String longStr = "A java 2s. com" +
"B j a v a 2 s . c o m " +
"C java 2s.com" +
"D java2s.com .";
System.out.println(longStr);
}
}
A java 2s. comB j a v a 2 s . c o m C java 2s.comD java2s.com .
String Concatenation with Other Data Types
You can concatenate strings with other types of data.
public class Main {
public static void main(String[] argv) {
int age = 1;
String s = "He is " + age + " years old.";
System.out.println(s);
}
}
The output:
He is 1 years old.
Be careful when you mix other types of operations with string concatenation. Consider the following:
public class Main {
public static void main(String[] argv) {
String s = "four: " + 2 + 2;
System.out.println(s);
}
}
This fragment displays
four: 22
rather than the
four: 4
To complete the integer addition first, you must use parentheses, like this:
String s = "four: " + (2 + 2);
Now s contains the string "four: 4".
Home
Java Book
Essential Classes
Java Book
Essential Classes
String:
- String type and Literals
- String Concatenation
- String.CASE_INSENSITIVE_ORDER
- String Constructor
- charAt(int index):Get a single char by index
- String: compareTo(String stringValue)
- concat(String str)
- equals():Compare two string value for equality
- equals( ) vs ==
- contains(CharSequence s)
- copyValueOf(char[] data)
- endsWith(String suffix)
- format():Format a string
- getBytes():Get byte array from string
- getChars()
- indexOf
- intern a string
- isEmpty:if string is empty
- lastIndexOf()
- length() Returns the length of this string
- startsWith( )
- toLowerCase() and toUpperCase(): convert string case with locale
- substring:Get sub string from a string
- toCharArray():Get char array from string
- toString( )
- trim()
- valueOf():Convert boolean, char, double, float,int,long,object to String