3

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!

hsugui
  • 51
  • 5

3 Answers3

7

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).

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
  • Source: [JLS 3.10.1](https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1): "A binary numeral consists of the leading ASCII characters 0b or 0B followed by one or more of the ASCII digits 0 or 1 interspersed with underscores". It's new in Java 7. – that other guy May 19 '20 at 19:06
2

Java allows you to use _ in int values as shown below:

public class Main {
    public static void main(String[] args) {
        int x = 1_2_3;
        System.out.println(x + 100);
    }
}

Output:

223
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
-2

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Chana
  • 358
  • 4
  • 10