Java Data Types
Data types in Java are divided into two types
Primitive Data Types
A primitive data type specifies the size and type of variable values. There are eight primitive data types in Java:
Data
Type |
Size |
Description |
byte |
1 byte |
Stores whole numbers from -127 to
128 |
short |
2 bytes |
Stores whole numbers from -32,768
to 32,767 |
int |
4 bytes |
Stores whole numbers from -2,147,483,648
to 2,147,483,647 |
long |
8 bytes |
Stores whole numbers from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float |
4 bytes |
Stores fractional numbers.
Sufficient for storing 6 to 7 decimal digits |
double |
8 bytes |
Stores fractional numbers. Sufficient
for storing 15 decimal digits |
boolean |
1 bit |
Stores true or false values |
char |
2 bytes |
Stores a single character / letter
or ASCII values |
Numbers
The primitive data types for numbers are divided into
Note: Though there are many numeric data types in Java, the most commonly used are int ( for whole numbers ) and double ( for floating numbers )
Primitive Data type Examples
byte numByte = 100; short numShort = 5000; int numInt = 100000; long numLong = 15000000000000L; float numFloat = 6.85F; double numDouble = 1.9999999999d; boolean isTrue = true; boolean isFalse = false; char a = 65, b = 66; //ASCII values String value = "SparkDatabox"; System.out.println("byte:" +numByte); System.out.println("short:" +numShort); System.out.println("int:" +numInt); System.out.println("long:" +numLong); System.out.println("float:" +numFloat); System.out.println("double:" +numDouble); System.out.println("boolean:" +isTrue); System.out.println("boolean:" +isFalse); System.out.println("ASCII value of'65':" +a); System.out.println("ASCII value of'66':" +b); System.out.println("String:" +value)
Output
byte:100 short:5000 int:100000 long:15000000000000 float:6.85 double:1.9999999999 boolean:true boolean:false ASCII value of'65':A ASCII value of'66':B String:SparkDatabox
Non-Primitive Data Types
These are called reference types because they refer to objects. The main difference between primitive and non-primitive data types are:
Non-Primitive Data types examples – Strings, Arrays, Classes, Interfaces, etc.