Java String Concatenation
In this chapter you will learn:
- How to add strings together
- Example - Java String Concatenation
- Example - uses string concatenation to create a very long string
- Example - How to concatenate String with other data types
- Example - mix other types of operations with string concatenation
Description
You can use +
operator to concatenate strings together.
Example 1
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);// w w w . j a v a 2s. c o m
}
}
Example 2
The following code uses string concatenation to create a very long string.
public class Main {
public static void main(String args[]) {
/*from w ww . java2 s .co m*/
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);
}
}
Example 3
You can concatenate strings with other types of data.
public class Main {
public static void main(String[] argv) {
int age = 1;/* w ww. ja va 2 s . co m*/
String s = "He is " + age + " years old.";
System.out.println(s);
}
}
The output:
Example 4
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);/*from ww w .j a v a2s . co m*/
}
}
This fragment displays
rather than the
To complete the integer addition first, you must use parentheses, like this:
String s = "four: " + (2 + 2);
Now s contains the string "four: 4".
Next chapter...
What you will learn in the next chapter:
- What are Java Arithmetic Operators
- Use Java Arithmetic Operators to do calculation
- Example - How to use basic arithmetic operators to do calculation