Search code examples
javaprimitive-types

What does a number like this mean in Java: 0b1000_1100_1010? (The "b" between the numbers)


I'm practicing with some tasks of a Java course and I came across this variable

int x = 0b1000_1100_1010;

I know that a "f" and a "d" beside a number means that the number is a float or a double, respectively. But what about this "b" between the number?

I saw here that this is related to bytes, but I didn't quite understand how it works.

My question also applies to the "x" between numbers that I just saw on that link.

Thanks!


Solution

  • This is the binary literal.

    It's a notation to show that the number is represented in binary.

    It's like when you use the hexadecimal notation: 0xF9. In Java, you can use 0b1111_1001 to represent the same number, which is 249 in decimal.

    It's not related to bytes, but to bits. You can clearly see which bits are set and which are not. By default a number starting with 0b is an int, but you can write a long like this 0b1010L (note the trailing L).

    The b can be lowercase or uppercase. So this is also valid: 0B1111. Note that since the 0b prefix indicates a binary representation, you're not allowed to use any character other than 0 and 1 (and _ to mark a separation).