Why my program is giving wrong output; | SoloLearn: Learn to code for FREE!

+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

7/7/2020 3:49:30 AM

Akash

8 Answers

New Answer

+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

+12

Using order of operations you could get it to work using parentheses.

+12

The parentheses will ensure that 30 is computed both times, as opposed to adding strings together the second time.

+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

+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!

+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

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

-3

maybe because u r doing it wrong?