+ 6

Why my program is giving wrong output;

Why my program is giving output of : 30 1020 I want output of 30 30 https://code.sololearn.com/c07GC5S26A0t/?ref=app

7th Jul 2020, 3:49 AM
Akash Sharma
Akash Sharma - avatar
8 Antworten
+ 9
That is because in the first a+b, 10 and 20 are added to get 30, but when you add " ", it becomes a string("30 "). And when you add 10, 20 they are added like strings. You could put brackets on the second a+b. System.out.println(a+b+" "+(a+b)) Output: 30 30
7th Jul 2020, 3:59 AM
Arnesh
Arnesh - avatar
+ 12
Using order of operations you could get it to work using parentheses.
7th Jul 2020, 4:00 AM
Uri Easter
Uri Easter - avatar
+ 12
The parentheses will ensure that 30 is computed both times, as opposed to adding strings together the second time.
7th Jul 2020, 4:01 AM
Uri Easter
Uri Easter - avatar
+ 4
You could change line 7 to : System.out.print(a+b+" "); And add another line of code: System.out.print(a+b); The reason i think is because after the space ,which is a string, the numbers get converted to the same data type to perform the concitation
7th Jul 2020, 4:04 AM
Bot
Bot - avatar
+ 1
Before the string concatenation, compiler treats a and b as integers thus giving right computation! But from the concatenation and the rests are treated as strings thus giving wrong results! You should put computation inside parenthesis to prevent this kind of unexpected results!
8th Jul 2020, 9:42 AM
S. M. JAHANGIR
S. M. JAHANGIR - avatar
+ 1
That is because in the first a+b, 10 and 20 are added to get 30, but when you add " ", it becomes a string("30 "). And when you add 10, 20 they are added like strings. You could put brackets on the second a+b. System.out.println(a+b+" "+(a+b)) Output: 30 30
29th Jul 2020, 2:26 PM
Amitabh Pandey
Amitabh Pandey - avatar
0
That is because in the first a+b, 10 and 20 are added to get 30, but when you add " ", it becomes a string("30 "). And when you add 10, 20 they are added like strings. You could put brackets on the second a+b. System.out.println(a+b+" "+(a+b)) Output: 30 30
7th Jul 2020, 9:59 PM
Amitabh Pandey
Amitabh Pandey - avatar
- 3
maybe because u r doing it wrong?
7th Jul 2020, 5:57 PM
Manzana Dulce
Manzana Dulce - avatar