So I am quite new to Java and motivated to learn. This question might seem simple but I genuinely don't understand and have searched Google for answers (no luck).
I am converting a decimal into Binary in Java. However, I thought representations of numbers are supposed to be given in data types int, double, and etc.
The code is as follows :
int decimal = 99;
String binary = Integer.toBinaryString(decimal);
System.out.println(binary);
Why is it String binary, should it not be any of the numerical data types?
Internally, all values are stored as binary values. Because it's easier to read, integers are converted into digits for display. Displaying a value as a binary is thus purely a representation issue.
So 99 is internally stored as 01100011. You can display it as a hexadecimal (0x63), a decimal (99), or a binary. But because the numerical value is the same in each case, the only difference is the symbols used to display it, and this symbolic representation is as a String.
The following ints are all equal:
int i = 99;
int j = 0o143;
int k = 0x63;
int l = 0b1100011;
If you want to print them, you have to convert them to a String using a utility method of Integer, or you use number formatting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With