Primitives and Non-Primitive Data Types
Data types in Java are divided into two types that are used to define variables include:
- Primitive data types
- Non-primitive (or reference) data types.
Sketch
The following sketch helps you understand how everything is divided based on its type.
![](https://www.ggorantala.dev/content/images/2023/04/data-types-detail.png)
Primitive data types
In Java, most of the work is done by primitives. These primitive data types are the foundation of all other types.
- They are used to store simple values such as numbers and characters.
- They are stored directly in memory and are accessed faster than non-primitive data types.
There are eight primitive data types in Java: byte
, short
, int
, long
, float
, double
, char
and boolean
.
The size and range of values that can be stored in a primitive data type depending on the type itself. For example, a boolean
can only hold the values true
or false
, while a long
can hold values from -263 to 263-1.
Hence, the 8 primitive data types in Java are categorized into 4 types.
- Integer types -
byte
,short
,int
, andlong
. - Floating point types -
float
anddouble
. - Character type -
char
. - Boolean type -
boolean
.
Table
Let us see the bytes size, default value, min and max and ranges of all the primitive data types.
![upload in progress, 0](https://www.ggorantala.dev/content/images/2023/04/image.png)
We will discuss more on each of these primitives in detail in the next lessons.
Non-primitive data types
Non-primitive data types are also known as reference types or object types, and they are used to define variables that hold complex data structures such as objects and arrays.
Non-primitive data types do not store the variable's actual value but instead, store a reference to the memory location where the data is stored.
Some examples of non-primitive data types in Java include:
Class
: represents a class type, a blueprint for creating objects with common attributes and methods.Interface
: represents an interface type, which defines a set of methods a class must implement.Array
: represents a collection of elements of the same data type stored in contiguous memory locations.String
: represents a sequence of characters, which can be treated as a single data type.
Non-primitive data types are created using class
or interface
definitions, and they can contain methods, constructors, and instance variables that define the behavior and properties of the data. They can also be passed by reference, meaning that when they are passed as arguments to a method or assigned to a variable, a reference to the memory location of the data is passed/assigned, and any changes made to the data affect the original value.