Addition And Concatenation

Addition And Concatenation in Java

In this article we will be discussing about Addition and Concatenation in Java.

Addition and Concatenation is an example of polymorphism in Java. “+” operator is used to add or concat two Integers or Strings.

Addition and concatentaion in Java

Addition

An Addition (‘+’) operator in Java is a binary operator and takes two operands. When the operands that are passed to the ‘+’ operator are numbers, an addition operation that returns the sum of two numbers is performed.

Example:

Run
import java.util.*;
public class Main{
    public static void main(String[] args){
        int a = 10,b = 20;
        System.out.println(a+b);
    }
}
30

Concatenation

When operands change to String type, the ‘+’ operator does not add the String objects but concatenates or joins the contents of the string to form a resultant third string.

Example:

Run
import java.util.*;
public class Main{
    public static void main(String[] args){
        String str1 = "Prep";
        String str2 = "Insta";
        System.out.println(str1+str2);
    }
}
PrepInsta

Addition and Concatenation

When two operands changes to String type and in integer type as well i.e. of of the operand is number and other of the operand is String or a character, the ‘+’ operator does not add the String objects and integer objects but concatenates or joins the contents of the string and integer to form a resultant third string.

Example:

Run
import java.util.*;
public class Main{
    public static void main(String[] args){
        int a = 100;
        String str2 = "Insta";
        System.out.println(a+str2);
    }
}
100Insta
Concatenation

Output Explanation: This unpredictable output is caused by the compiler evaluating the given expression from left to right because the operators have equal precedence. Once it encounters a string, it treats the rest of the expression as a string (again based on the order of precedence of the expression).