i wrote a simple program in java. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

i wrote a simple program in java.

class Add{ public static void main(String[] args){ int x = 5, y = 3; System.out.println("The sum is:" + x + y); } } here the outpur is 53 which is added as string and not integers. but when i remove "The sum is:" + from the println in 4th line it is added as integers again. why please tell me

1st Apr 2018, 6:35 PM
stephen haokip
stephen haokip - avatar
3 Answers
+ 11
actually , each operand will be added like String ... case1) 1+2+"a" = 3a case2.1) "a"+1 = a1 //a1 whole as a String case 2.2) "a"+1+2 ="a1"+2=a12 //since "a1" is already a String case3) 1+2 = 3 //no p. in that
1st Apr 2018, 6:37 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 9
correct @TurtleShell //thats bcz precedence of () operator is greater than + operator //👉and since , associativity of + operator is from left to right ... so in case 2) there is concatination first & then again concatination rather than addition followed by concatination
1st Apr 2018, 6:46 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
To fix what Gaurav is talking about put brackets around the x and y: System.out.println("The sum is: " + (x + y));
1st Apr 2018, 6:45 PM
TurtleShell
TurtleShell - avatar