Praveen
Praveen

Reputation: 121

Printing binary values in Java

Why the output of this java program is 8 and 9 while we try to print 010 and 011 respectively:

public class Test{
   public static void main(String str[]){ 
      System.out.println(011); 
   }
}

What is the reason?

Upvotes: 2

Views: 5874

Answers (4)

Amr Fathy
Amr Fathy

Reputation: 1

bec. when you start your number with 0 JVM convert the number from decimal to octal that's all ;)
"11 in decimal = 9 in octal" decimal 0 1 2 3 4 5 6 7 8 9 octal 0 1 2 3 4 5 6 7 10 11

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213261

010 is interpretetion of 10 in octal base which is 8. And similarly 011 is interpretetion of 11 in octal base which is 9.

Prepending an integer with 0 makes it interpreted in octal base.

Similarly, you can try printing 0x10, which is a hexadecimal representation, and will give you 16 as output.

Upvotes: 6

Ted Hopp
Ted Hopp

Reputation: 234807

In Java, the default conversion from integer to string is base 10. If you want a different radix, you have to specify it explicitly. For instance, you can convert an integer value to a binary string using:

Integer.toString(value, 2);

Similarly, you can convert it to an octal value with:

Integer.toString(value, 8);

Unless the value is 0, the string will not have a leading zero. If you want a leading 0, you'll have to prepend it. Alternatively, you can format it with String.format() and specify zero fill and a minimum width for the converted string:

String.format("%1$03o", value); // the "1$ in the format string is optional here

P.S. It's not clear from your question what the exact problem is. It sounds like it's that you are converting from an integer value to a string. However, if the problem is that you're trying to read the string "011" and it is being read as the integer value 9, this is because a leading 0 forces interpretation as an octal value. You'll have to read it as a String value and then explicitly specify the conversion from string to integer to be base 10:

int val = Integer.valueOf(stringValue, 10);

Upvotes: 6

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

- If you want to convert the integer to binary data, use toBinaryString() method.

Eg:

int i = 8;
Integer.toBinaryString(i);

Upvotes: 1

Related Questions