2

Please note the print statements, in the code segments below. My question is how come If I try to add two doubles in the print statement it prints incorrectly, but if I add them outside the print statement and store the result in a variable than I am able to print it correctly.

Why does this work and print out the correct result?

public static void main(String argsp[]){ Scanner input = new Scanner(System.in); double first, second, answer; System.out.println("Enter the first number: "); first = input.nextDouble(); System.out.println("Enter the second number: "); second = input.nextDouble(); answer = first + second; System.out.println("the answer is " + answer); } 

Why does this print out the wrong result?

public static void main(String argsp[]){ Scanner input = new Scanner(System.in); double first, second; System.out.println("Enter the first number: "); first = input.nextDouble(); System.out.println("Enter the second number: "); second = input.nextDouble(); System.out.println("the answer is " + first+second); } 
3
  • 1
    what are the results..?? Commented May 24, 2012 at 13:13
  • 1
    works fine for me. Enter the first number: 2 Enter the first number: 2 the answer is 2.02.0 Commented May 24, 2012 at 13:15
  • @owengerig OP is trying to make the compiler group operands by proximity. See how those two are cuddling together? :) Commented May 24, 2012 at 13:18

3 Answers 3

5

It's because what you're basically doing in that second part is:

System.out.println("the answer is " + String.valueOf(first) + String.valueOf(second)); 

That's how the compiler interprets it. Because the + operator when you are giving a String to a method is not a calculation but a concatenation.

If you want it done in one line, do it like this:

System.out.println("the answer is " + (first + second)); //Note the () around the calculation. 
Sign up to request clarification or add additional context in comments.

Comments

3

In case of doubt with the precedence of operators, just use parens. It is also clearer to read.

System.out.println("the answer is " + (first+second)); 

Comments

2

In the second case, the doubles are converted to Strings because the + is considered String concatenation. To work around this, use parentheses to group expressions that should perform numeric calculations:

 System.out.println("the answer is " + (first + second)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.