+ 1

How is the compiler interpreting the variables when placed differently? I am not getting the output I want.

In string output, if i write (age + score + group) the compiler gives error saying incompatible variables. When I put name at the end (age + score + group + name) the compiler gives a weird result of 147.9 I get correct result only when I write (name + age + score + group) why does the compiler not print the result as I define the string in the first two cases? here is the code -- class MyClass { public static void main(String[ ] args) { String name ="David"; int age = 42; double score =15.9; char group = 'Z'; String output = age + score + group + name; System.out.println(output); } }

11th Aug 2018, 6:29 PM
Sid Verma
Sid Verma - avatar
5 Answers
+ 2
It's because age and score are numbers. The compiler sum them first and then concatenate into a string. Try to use Integer object and toString() method, or force the compiler to concatenate first. String output = age + "" + score + group + name; 147,9 is: 42 (age) + 15,9 (score) + 90 (ASCII value for 'Z')
11th Aug 2018, 8:31 PM
Eikos
Eikos - avatar
+ 1
For output in a single line: String output = "Name: " + name + " Age: " + age + " Score: " + score + " Group: " + group; System.out.println(output); For output in multiple line: String outputMultiLine = "Name: " + name + "\nAge: " + age + "\nScore: " + score + "\nGroup: " + group; System.out.println(outputMultiLine);
12th Aug 2018, 6:06 AM
Ipang
0
Thank you Eikos
11th Aug 2018, 9:47 PM
Sid Verma
Sid Verma - avatar
0
please i do not entender
12th Aug 2018, 3:42 AM
Luibmar Guerrero
Luibmar Guerrero - avatar
0
In the example this code do not ejecut
12th Aug 2018, 3:43 AM
Luibmar Guerrero
Luibmar Guerrero - avatar