Is it a bug or featuere
-
In this code int i =2; System.out.print(" Run " + i+1 + " "); It prints Run 21 Where I would have expected to print Run 3 Amara 'Now I understand how stupid I am, thanks for everybody's contribution.
The plus operator is left associative so I'd expect 21 as the result. 22 does not make any sense whatsoever. What happens when you put i + 1 in parenthesis like this: (i + 1). Try that and think about associativity of operators and what it means to the process of evaluation/compilation. Cheers!
"With sufficient thrust, pigs fly just fine."
Ross Callon, The Twelve Networking Truths, RFC1925
-
In this code int i =2; System.out.print(" Run " + i+1 + " "); It prints Run 21 Where I would have expected to print Run 3 Amara 'Now I understand how stupid I am, thanks for everybody's contribution.
The reason you are not getting 'Run 3' is because Java is thinking about string concatination. As it is processing from left to right you would see: "Run 2" + 1 + "" But this is where it gets a bit strange, I would expect to see the number 1 printed next giving you: "Run 21" If you want to add two numbers you must use brackets to indicate priority: System.out.print("Run "+ (i+1));
-
In this code int i =2; System.out.print(" Run " + i+1 + " "); It prints Run 21 Where I would have expected to print Run 3 Amara 'Now I understand how stupid I am, thanks for everybody's contribution.
-
In this code int i =2; System.out.print(" Run " + i+1 + " "); It prints Run 21 Where I would have expected to print Run 3 Amara 'Now I understand how stupid I am, thanks for everybody's contribution.
The others have already explained why it is so. I would like to add into, that the + is an operator and is overloaded in the String class and also used different in the System.out. Operators in Java[^]
regards Torsten When I'm not working
-
In this code int i =2; System.out.print(" Run " + i+1 + " "); It prints Run 21 Where I would have expected to print Run 3 Amara 'Now I understand how stupid I am, thanks for everybody's contribution.
int i =2; System.out.print(" Run " +(i+1)+ " "); This is the code. Keep the brackets.
Gowtham Gutha (Java-Demos.Blogspot.Com)