Why doesn’t Java add up the numbers in expression?

Asked

Viewed 406 times

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 had not to be: 0 3?

2 answers

8


No, they’re different types, the operation needs to be normalized for one type, and it has to be one that all work well.

To string doesn’t work well with numbers, what number she would be to add up?

So all operands are considered as string and there’s only one concatenation and not one sum.

All Java types can be converted to string, although not always properly. Only a few strings can be converted into number and it is not the compiler’s job to check this, because most of the time he will not even know what the value is.

This is because of the association and precedence of operators (in this case the precedence does not matter because it is the same operator in all sub-expressions). That’s what it’s doing:

x + " "

whose result is

"0 "

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

"0 " + y

whose result is

"0 1"

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

"0 1" + z

whose result is

"0 12"

I put in the Github for future reference.

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

On all sums you’re using one string with a number.

  • Thank you, I can understand why

7

This is because you have a string in the middle, when there’s string he understands that this concatenating, try to do the operation before concatenating, so put the operation between 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));
  }      
}

That way the interpreter will solve first what this between parentheses and then do what this out, which in case is to concatenate.

  • 3

    What is the reason for -1?

  • thank you, I understand

  • @ramaral, I have the impression that someone is negativizing without pity the staff and without explaining the reason. I understand this in several questions and answers.

  • @ramaral and Dherik I believe that’s why the Maniero answered, there are many people who go by the score, IE, what he posted this right and what others posted this wrong.

  • 1

    In a sense his answer is even "more complete", since it indicates how to do what the AP expected: the result is 0 3.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.