1

Why do i get 10 2030 as the output? I can't figure out why it doesn' t output it as 10 50?

public class Testing1 {
  public static void main(String args[]) {
    int num1 = 10, num2 = 20, num3 = 30;

    System.out.println(num1 + " " + num2 + num3);

3 Answers 3

5

This is because Java evaluates expressions with a 'precedence'. In this case, it starts at the left, and it works to the right, because the operations are all + they all have the same precedence so the left-to-right order is used. In the first 'addition', you add a number and a String. Java assumes the '+' is meant to do String concatenation, and you get the result "10 ". You then add that to 20, and get the (String concatenation) result "10 20". Finally you add the 30, again adding to a String, so you get the result"10 2030"`.

Note, if you change the order of your operations to:

System.out.println(num1+num2+" "+num3);

the num1+num2 will be treated as numbers, and will do numeric addition, giving the final result: "30 30"

To get the correct value you can change the evaluation order by making a sub-expression by using parenthesis (...) (which have a higher operator precedence than '+', and get the result with:

System.out.println(num1 + " " + (num2 + num3));

The num2 + num3 is evaluated first as a numeric expression, and only then is it incorporated as part of the string expression.

Sign up to request clarification or add additional context in comments.

Comments

0

look up operator precedence and how + works when different types of operands

Comments

0

In java '+' operator operates differently for different operands.

  1. For Integers operands it operates as integer addition
  2. For strings it operates as concatenation.

Evaluation of java expression is based on precedence rule.In your case there is only '+' operator so evaluation is from left to right.

For integer and string operands java '+' operator performs string concatenation.

So num1 + " " + num2 + num3 execution is as

 (integer + String) + int + int
            (String + int)+ int
                  String  + int

Your desired out put can be achieved by forcing the precedence for (num2 + num3) using parenthesis.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.