1

I successfully managed to solve a math problem using Java code. However, in doing so, I've also stumbled upon something weird.

In one of my calculations, I had to add 4 numbers: 13, 132, 320, and 201. I declared an int variable sum, and initialized it to 13 + 132 + 320 + 201.

int sum = 13 + 132 + 320 + 201;

When I printed the variable sum out, it returned a value of 666. Which makes sense, since adding those numbers on a calculator returns that value. However, I decided to then set the variable sum equal to something a little different. I decided to set sum equal to 013 + 132 + 320 + 201.

sum = 013 + 132 + 320 + 201;

However, when I printed this value out, I got 664. I decided to add one more zero to the left of 013.

sum = 0013 + 132 + 320 + 201;

And sum returned the same value, 664.

So basically, whenever I add the numbers just like that without any unnecessary zeroes, sum returns the correct value. But when I add those unecessary zeroes, sum returns a slightly different answer. Is there a reason as to why putting zeroes before a number causes a slightly different result?

2 Answers2

3

In math only base is not decimal .So to define numbers in base 16(Hexa-decimal),8(Octal),2(Binary) and 10(Decimal) there must be a way.So in java you can define those like below.

Adding the prefix of 0b or 0B you can define binary numbers (base 2)

byte b1 = 0b101;

Adding the prefix of 0 you can define octal numbers(base 8)

int octal = 013;

Adding the prefix of 0x you can define hexa decimal numbers(base 16)

int hexaDecimal =0x13;

You can define decimal numbers without using any prefix

int decimal = 13;

Hasindu Dahanayake
  • 1,344
  • 2
  • 14
  • 37
1

Your question is basically this:

// Java interprets this as octal number
int octal = 013;
// Java interprets this as hexadecimal number
int hexa = 0x13
// Java interprets this as decimal number
int decimal = 13
papaya
  • 1,505
  • 1
  • 13
  • 26
  • So basically, adding zeroes before a number, while they mean the same thing in math, actually changes the base of the number? So 013 is 13 with a base of 8? And 0013 is 0x13 which is 13 with a base of 6? – Andy Kochhar Oct 21 '20 at 01:30