Java String Concatenation
In this chapter you will learn:
- How to add strings together
- How to concatenate String with other data types
- How to concatenate one string to the other with concat method
Add strings together
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);//from java 2 s . co m
}
}
The following code uses string concatenation to create a very long string.
public class Main {
public static void main(String args[]) {
/*from j a v a 2s . c o m*/
String longStr = "A demo 2s. com" +
"B d e m o 2 s . c o m " +
"C demo 2s.com" +
"D demo2s.com .";
System.out.println(longStr);
}
}
Concatenate String 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;// j a v a 2 s.com
String s = "He is " + age + " years old.";
System.out.println(s);
}
}
The output:
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);// j a v a 2 s . c om
}
}
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".
concat one string to the other with concat method
String concat(String str)
concatenates the specified string to the end of this string.
public class Main {
public static void main(String[] argv) {
String str = "demo2s.com";
//from j a va 2s . c om
str = str.concat("Demo2s.com");
System.out.println(str);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- How to create String object with String constructors
- How to create a string from byte array
- How to create a string from part of a byte array
- How to create String from char array
- How to create String from part of a char array
- How to create a String from another string
Home » Java Tutorial » String