Java - String Concatenation Operator +

What is String Concatenation Operator

The + operator is overloaded for String value.

Two strings, such as "abc" and "xyz", can be concatenated using the + operator as "abc" + "xyz" to produce new string "abcxyz".

String str1 = "abc"; 
String str2 = "xyz"; 
String str3 = str1 + str2; 

Demo

public class Main {
  public static void main(String[] args) {
    String str1 = "abc"; 
    String str2 = "xyz"; 
    String str3 = str1 + str2; /* www. j  av a 2 s .  c  om*/

    System.out.println(str3);
  }
}

Result

String concatenation operator on non String types

The String concatenation operator can concatenate a primitive and a reference data type value to a string.

When either operand of the + operator is a string, it performs string concatenation.

When both operands of + are numeric, it performs number addition.

int num = 123; 
String str1 = "abc"; 
String str2 = num + str1; 

Demo

public class Main {
  public static void main(String[] args) {
    int num = 123; 
    String str1 = "abc"; 
    String str2 = num + str1; /*from www.  j a  va 2s.co  m*/
    System.out.println(str2);
  }
}

Result

In the code above, when num + str1 is executed, the + operator acts as a string concatenation operator since str1 is a String.

Before num and str1 are concatenated, num is converted to its string representation.

Related Topics

Quiz