srk
srk

Reputation: 5126

Addition of hexadecimal with binary number

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?

Upvotes: 0

Views: 312

Answers (2)

Vikas Singh
Vikas Singh

Reputation: 3018

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"

Upvotes: 3

Mohit Jain
Mohit Jain

Reputation: 30489

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)

Upvotes: 4

Related Questions