String concatenation with + operator

In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the plus (+) operator, which concatenates two strings, producing a String object as the result.
Example,

package com.ibytecode.strings.operators;
public class PlusOperator {
	public static void main(String[] args) {
		String str = "the" + "open" + "tutorials" + ".com";
		System.out.println("Welcome to " + str); 
	}
}

Welcome to theopentutorials.com

Line 4 creates seven String objects in the memory which is shown in below picture

  1. “the”
  2. “open”
  3. “tutorials”
  4. “.com”
  5. “theopen”
  6. “theopentutorials”
  7. “theopentutorials.com”

Line 5 creates additional two String object “Welcome to” and “Welcome to theopentutorials.com”

String concatenation with primitive data types

You can combine primitive data types with Strings using the plus (+) operator.

package com.ibytecode.strings.operators;
public class PlusOperator {
	public static void main(String[] args) {
		int a = 10;
		int b = 20;
		int sum = a + b;
		String result = "The sum of " + a + " and " + b + " is " + sum;
		System.out.println(result);
	}
}

The sum of 10 and 20 is 30

If either of the operand is String for plus (+) operator then it becomes String concatenation. The compiler simply treats the primitive value as characters and concatenates with the String.

The above code creates eight String objects in the memory

  1. “The sum of”
  2. “and”
  3. “is”
  4. “The sum of 10 “
  5. “The sum of 10 and “
  6. “The sum of 10 and 20”
  7. “The sum of 10 and 20 is “
  8. “The sum of 10 and 20 is 30”
Left Operand Plus Operator (+) Right Operand Result
Number + Number Addition
Number + String Concatenation
String + Number Concatenation
String + String Concatenation

String concatenation using compound additive operator (+=)

It is legal to use += operator with Strings.
The above code can also be written as,

package com.ibytecode.strings.operators;
public class PlusOperator {
	public static void main(String[] args) {
		int a = 10;
		int b = 20;
		int sum = a + b;
		String result = "The sum of ";
		result += a;
		result += " and ";
		result += b; 
		result += " is " + sum;
		System.out.println(result);
	}
}

The += operator was used and always the left operand was a String, hence all the operations resulted in String concatenation.

Equality Operators (== and !=)

You can compare two String references using == and != operators to check whether two references are referring to the same String object in the memory.

package com.ibytecode.strings.operators;
public class EqualityOperator {
	public static void main(String[] args) {
		String s1 = "abc";
		String s2 = "abc";
		if(s1 == s2)
			System.out.println("s1 == s2 is True");
		String s3 = new String("abc");
		if(s1 != s3)
			System.out.println("s1 != s3 is True");
	}
}	

s1 == s2 is True
s1 != s3 is True

Leave a Comment