JavaNoob
JavaNoob

Reputation: 11

How does this add up?

public class Main{
    public static void main(String args[]){
        char a='3';
        int b=011;
        System.out.println(a+b);
    }
}

The answer turns out to be 60 but I don't understand how. Could anyone please explain. Thanks in advance :)

Upvotes: 1

Views: 1234

Answers (2)

byhuang1998
byhuang1998

Reputation: 417

welcome to stack overflow! Hope a good trip! when you add a char and an int, it will output an int. In the situation, the char will be explained into its ASCIIhttps://www.ascii-code.com/ value, so '3' is 51. 011 is an octal number so it will be explained as 1 * 8 + 1 = 9. So, 51+9 = 60.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201437

First, char + int is an int. So you're widening the char '3' to int 51. Second, numbers with a leading 0 are in octal. So 011 is another way to write decimal 9. 51 + 9 = 60, or

System.out.printf("%d + %d = %d%n", (int) a, b, a + b);

Upvotes: 3

Related Questions