+ 2
Java Print
Hi all! I've found this code on Challenge questions but I have no clue what is happening. int a = 10; int b = 20; System.out.print(a + b + “ “ + a + b); Why is the output 30 1020 and not 30 30 ? What does double quote make to the print so that no addition is made? Thx in advance :)
4 Antworten
+ 1
Nice one. Well indeed it's due to the + operator.
When it evaluates what's inside the parentheses, it sees :
- a + b : the addition of two int (let's call it c)
- c + " " : an int and a String -> convert the int into a String and add the String's (let's call the result s)
- s + a : a String and an int -> same as before : converts the int into a String and add them together
- the last one (+b) works exactly the same way as the previous ones.
A way to obtains 30 30 is to write :
System.out.println(a + b + " " + (a + b));
By putting the second "a+b" in parentheses, we change the order of evaluation and this leads to adding them together before adding them to a String
+ 3
The " " is of string type, rather than int. Because math deals with numbers, rather than strings, the string is causing it to implicitly typecast the rest of it as a string rather than keeping them as an int. So now the " " + a + b are all strings, it's simply concatenating it, which is why you get 1020 for that portion of it.
Hope that helps!
0
Thank you both! rly appreciate it
0
You're welcome !