In this chapter we will be learning Concatenating two strings in java programming. Concatenating two strings means combining two objects in java.
Joining two Strings [Concatenate Strings] in Java :
Consider the following example -
public class ConcatenateString { public static void main(String[] args) { String Str1 = "I love"; String Str2 = "my country"; String Str3 = "India"; String myString; myString = Str1 + Str2 + Str3; System.out.println("Complete Statement : " + myString); myString = Str3 + 10 + 10; System.out.println("Complete Statement : " + myString); myString = 10 + 10 + Str3; System.out.println("Complete Statement : " + myString); } }
Output :
Complete Statement : I love my country India Complete Statement : India1010 Complete Statement : 20India
Explanation of the Program :
In Java Programming when two strings will be combined together then it will create another object of string. Below are some thumb rules while adding or combining two strings.
Operand 1 | Operand 2 | Result of Concatenation |
---|---|---|
Integer | String | String |
String | String | String |
Integer | Integer | Integer |
- ‘+’ operator has associtivity from left to right.
- Each time + operator will check the type of operands and then decide which operation to perform.
- If any of the operand is of type String then another type will converted to String using respective wrapper classes.
First Concatenation :
myString = Str1 + Str2 + Str3;
= "I love " + "my country " + "India"
= "I love my country " + "India"
= "I love my country India"
Second Concatenation :
myString = Str3 + 10 + 10;
= "India" + 10 + 10
= "India10" + 10
= "India1010"
Third Concatenation :
myString = 10 + 10 + Str3;
= 10 + 10 + "India"
= 20 + "India"
= "20India"
The post Java Concatenate Strings : [String Operations] appeared first on Learn Java Programming.