understanding the java string with add operator

前端 未结 4 1931
轮回少年
轮回少年 2021-01-16 04:04

I am trying to understand how the compiler views the following print statements. It is simple yet a bit intriguing.

This prints the added value. Convincing enough.<

4条回答
  •  盖世英雄少女心
    2021-01-16 04:41

    Thats interesting part of string. When a String is added to any other data type, the resultant value is a String.The other variable is also converted to a String and then concatenated. However, when two integers are operated with a + sign, the + acts as an addition operator and not a concatenation operator. If the expression within the println() or print() method contains parentheses, then the value within the parentheses is evaluated first. Consider the following example:

        int a = 5;
        int b = 6;
        System.out.println(a + b); // Output will be: 11
        System.out.println("5" + "6"); // Output will be: 56
        System.out.println("" + a + b); // Output will be: 56
        System.out.println(5 + 6 + a + " " + b + a); // Output will be: 16 65
        System.out.println("Result: " + a + b); // Output will be: 56
        System.out.println("Result: " + (a + b)); // Output will be: 11
    

    You can see the difference between last two sysout statements

提交回复
热议问题