Addition Operator In Java
Addition operator in Java is used to add two lines in java.
We can use “+” operator to add two lines.
We can use the “ + ” operator to add two lines of String as well.
If we are using the “+” operator to add one String, and another numeric value then it works to add both lines, hence it is not working as a numeric value.
If we are using “ + ” operator to add two numeric values then it works as an arithmetic operator and adds both values mathematically.
Now we will see Examples -
Example -
//Online promotion House
// web designing house
// Example begins here
public class Precedence {
public static void main(String[] args) {
int x = 1, y = 2, z = 3;
int a = x + y - 2/2 + z; // (1)
int b = x + (y - 2)/(2 + z); // (2)
System.out.println("a = " + a + " b = " + b);
}
}
|
Output -
Now we will see an elaborate explanation of the above-given example, and we will see that our example justifies the above-mentioned details of the “ + ” operator.
Explanation -
These statements look roughly the same, but from the output, you can see that they have very different meanings which depend on the use of parentheses.
Notice that the System.out.println( ) statement involves the ‘+’ operator.
In this context, ‘+’ means “string concatenation” and, if necessary, “string conversion.” When the compiler sees a String followed by a ‘+’ followed by a non-String, it attempts to convert the nonString into a String.
As you can see from the output, it successfully converts from an int into String for a and b.