Reputation: 51
I would like to know why there are 2 different outputs from:
double a = 88.0;
System.out.println(a + 10); // 98.0
double result = 88.0;
System.out.println("The result is " + result + 10); // The result is 88.010
Upvotes: 1
Views: 45
Reputation: 7
If you use System.out.println()
the items you put inside are automaticly casted into String
. The plus is used to add the seperate Strings together.
If you want to do a math operation use the variables inside parenthesises.
So your code shold look like this:
System.out.println("the result is " + (result + 10));
Upvotes: -2
Reputation: 59112
When you evaluate "the result is " + result + 10
you are evaluating String + double + int
.
When this is executed, the double
is first added to the string, creating another string, and then the int
is added to that string, giving another string.
So you get:
"the result is " + result + 10
"the result is 88.0" + 10
"the result is 88.010"
This is different from
"the result is " + (result+10)
which would give
"the result is 98.0"
Upvotes: 5