0

I am trying to understand the reason for the output of the below program.

public class CrossAddition{
  public static void main(String[] args){
    int decimal = 267;
    int octalValue = 0413;
    int hexadecimalValue = 0X10B;
    int binValue = 0b100001011;
    System.out.println("Decimal plus octal = "+ decimal+octalValue);//267267
    System.out.println("HexaDecimal plus binary = "+ hexadecimalValue+binValue);//267267
  }
}

Here is my analysis of this problem The octalValue in the first sysout is converted to decimal, i.e.., the decimal equivalent of octalVlaue 0413 is 267. Now 267+267 should be 534. But here, the output of the first sysout is 267267.

Second sysout, hexadecimalValue 0X10B is first converted to decimal, which outputs 267. And, binValue is converted to decimal, which outputs 267. Now again 267+267 should be 534, but its not true, its displaying 267267.

Its working like string concatenation. How can I understand this?

1
  • The '+' are interpreted from left to right. In a different context, the right '+' would cause a number addition, in this case the left operand is already a string, so it just gets appended to the string. Commented Apr 30, 2014 at 6:17

2 Answers 2

4

Use as following

System.out.println("Decimal plus octal = "+ (decimal+octalValue));
System.out.println("HexaDecimal plus binary = "+ (hexadecimalValue+binValue));

"Decimal plus octal = "+ decimal+octalValue is processed as String("Decimal plus octal = ")+ String(deimal)+String(octalValue) and hence the problem.

You rather want something like String("Decimal plus octal = ")+ String(deimal + octalValue)

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

2 Comments

Correct, but it would be more helpful if you'd give more explanation
Thank Jon. Explanation added.
3

Java start operation from left to right so it will first append decimal with string which will be "Decimal plus octal = 267" and then append octalValue on it so ouput will become "Decimal plus octal = 267267"

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.