Why does not Java add the numbers into expression? [duplicate]

7
public class Teste {      
  public static void main(String[] args) {
    int x = 0;
    int y = 1;
    int z = 2;
    System.out.print(x + y + z);
  }      
}

This returns: 3

public class Teste {      
  public static void main(String[] args) {
    int x = 0;
    int y = 1;
    int z = 2;
    System.out.print(x + " " + y + z);
  }      
}

This return: 0 12, why? It did not have to be: 0 3?

    
asked by anonymous 20.04.2018 / 19:20

2 answers

8

No, they are different types, the operation must be normalized to one type only, and it has to be one that all works well.

The string does not work well with numbers, what number would it be to add?

Then all the operands are considered as string and there is only a concatenation and not a sum.

All Java types can be converted to string , although not always properly. Only a few strings can be converted to number and it is not the function of the compiler to check this, because in most cases it will not even know what the value is.

This is because of the associativity and precedence of operators (in this case, precedence does not matter because it is the same operator in all subexpressions). This is doing so:

x + " "

The result is

"0 "

Then he takes this result as left operator and makes a new "sum" with the right operand:

"0 " + y

The result is

"0 1"

Then he takes this result and finally makes the last sum:

"0 1" + z

The result is

"0 12"

Associativity is always from left to right in this operator (there are operators that are inverted)

In all sums you are using a string with a number.

    
20.04.2018 / 19:23
7

This is because it has a string in the middle, when it has string it understands that it is concatenating, try doing the operation before concatenating, so put the operation in parentheses:

public class Teste {      
  public static void main(String[] args) {
    int x = 0;
    int y = 1;
    int z = 2;
    System.out.print(x + " " + (y + z));
  }      
}

In this way the interpreter will first solve what is in parentheses and then do what is outside, which in the case is concatenate.

    
20.04.2018 / 19:24