Java Data Types - Primitives and Binary Literals With Examples

Java is a strongly typed language, that means all the variables must first be declared before we can use it. Declaring a variable in java includes type and name with optional value assignment. If no value is assigned, the variable holds the default value. For primitive types, there are different default values but it’s always NULL for Object data types.

Java Primitive Data Types

Java programming language contains eight primitive data types. Four primitive data types are for integer values – byte, short, int and long. Two primitive data types are for floating type decimal values – float and double. One is for characters – char and one is for the condition – boolean. Java programming language also comes with Wrapper classes for all these primitive data types.

Below table shows all these primitive data types with size, range, default value and different ways to assign them.

Type Size Range Default Value Examples
boolean 1 bit NA false boolean bool = true;
char 16 bits Unicode Characters ‘u0000’ or 0, which
is nothing but a
white space
char c = ‘A’;
char c = ‘u0041’;
char c = 65;
char c = ‘t’;
byte 8 bits [-128,127] or
[-2^7 to 2^7-1]
0 byte b = 10;
byte b = 0b010;
short 16 bits [-32768,32767] 0 short s = 32;
short s = ‘A’;
int 32 bits [-2147483648,2147483647] 0 int i = 10;
int i = ‘A’;
long 64 bits [-2^63,2^63-1] 0 long l = 3200L;
long l = 3200;
float 32 bits [-3.4E38, 3.4E38] 0.0f float f = (float) 12.34;
float f = 12.34f;
double 64 bits [-1.7E308, 1.7E308] 0.0 double d = 12.34;

Below is a simple java program showing different ways to declare primitive data types – look closely for char and what happens when an int is converted to byte through explicit casting.

Using Underscore in Numeric Literals

From Java 7 onwards, we can use underscore in numeric literals such as long ccNum = 1234_5678_9101_1121L;. You can read more about them at Underscores in Numeric Literals.

Binary Literals

From Java 7 onwards, the integral types (byte, short, int, and long) can also be expressed using the binary number system. We need to prefix the number with 0b or 0B. Some of the examples are;

That’s all for primitive data types in java. Please look into the program carefully to understand what happens when we perform casting.

By admin

Leave a Reply

%d bloggers like this: