Java Primitive Data Types

tutorial and example
tutorial and example


Primitive datatypes are the simplest datatypes in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that they can store. Java defines the following eight primitive datatypes:

char, byte, short, int, long, float, double, boolean

boolean:- A boolean variable can store one of two values: true or false . It’s used in scenarios where only two states can exist.

Ex:-   boolean married = true;

double :- We can use double primitive data types to store decimal numbers. double requires more space than float.

double total = 120.1762;

float :- The float primitive data types use to store decimal numbers. float requires less space than double , but it can store a smaller range of values than double . float is less precise than double .

Ex:- float average = 10.124F;

float sum = 1765.65f;

long :-  The long primitive data types use to store large integer numbers, the range of long is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Ex:- long e = 1515l;

int :- int data type is a 32-bit signed two’s complement integer. Integer is generally used as the default data type for integral values unless there is a concern about memory.

Ex:- int d = 123;

short :- Short data type is a 16-bit signed two’s complement integer. Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer.

Ex:- short C = 11111;

byte :- Byte data type is an 8-bit signed two’s complement integer. Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.

Ex :- byte b = 127;

char :- char data type is a single 16-bit Unicode character. char data type is used to store any character

Ex :- char  a = ‘s’;

It’s helpful to categorize the primitive data types as boolean, numeric, and character data types.

The boolean data type is used to store data with only two possible values. The value may be thought of as true/false, or yes/no or any other combination. The actual values that a  boolean can store are true and false .

Numeric values are stored as integers or decimal numbers. byte , short , int , and long can be used to store integers. The byte, short, int, and long data types use 8, 16, 32, and 64 bits, respectively.  Float and Double are used to store decimal numbers. The float uses 32 bit and double use 64 bits respectively, to store their values.