Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaAddition and Concatenation Using + Operator in Java

Addition and Concatenation Using + Operator in Java

Till now in Java, we were playing with the integral part where we witnessed that the + operator behaves the same way as it was supposed to because the decimal system was getting added up deep down at binary level and the resultant binary number is thrown up at console in the generic decimal system. But geeks even wondered what if we play this + operator between integer and string.

Example

Java




// Java Program to Illustrate Addition and Concatenation
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Print statements to illustrate
        // addition and Concatenation 
        // using + operators over string and integer
        // combination
        System.out.println(2 + 0 + 1 + 6 + "Lazyroar");
        System.out.println("Lazyroar" + 2 + 0 + 1 + 6);
        System.out.println(2 + 0 + 1 + 5 + "Lazyroar" + 2 + 0 + 1 + 6);
        System.out.println(2 + 0 + 1 + 5 + "Lazyroar" + (2 + 0 + 1 + 6));
    }
}


Output

9Lazyroar
Lazyroar2016
8Lazyroar2016
8Lazyroar9

Output Explanation: This unpredictable output is due to the fact that the compiler evaluates the given expression from left to right given that the operators have the same precedence. Once it encounters the String, it considers the rest of the expression as of a String (again based on the precedence order of the expression).

System.out.println(2 + 0 + 1 + 6 + "Lazyroar");  

It prints the addition of 2,0,1 and 6 which is equal to 9

System.out.println("Lazyroar" + 2 + 0 + 1 + 6); 

It prints the concatenation of 2,0,1 and 6 which is 2016  since it encounters the string initially. Basically, Strings take precedence because they have a higher casting priority than integers do.

System.out.println(2 + 0 + 1 + 5 + "Lazyroar" + 2 + 0 + 1 + 6); 

It prints the addition of 2,0,1 and 5 while the concatenation of 2,0,1 and 6 is based on the above-given examples.

System.out.println(2 + 0 + 1 + 5 + "Lazyroar" + (2 + 0 + 1 + 6)); 

It prints the addition of both 2,0,1 and 5  and 2,0,1 and 6 based due to the precedence of ( ) over +. Hence expression in ( ) is calculated first and then further evaluation takes place.

This article is contributed by Pranjal Mathur. If you like Lazyroar and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.

RELATED ARTICLES

Most Popular

Recent Comments