Skip to main content

Variables and Data Types

Primitives and Non-Primitive Data Types

Data types in Java are divided into two types that are used to define variables include:

  1. Primitive data types
  2. Non-primitive (or reference) data types.

Sketch

The following sketch helps you understand how everything is divided based on its type.

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.

  1. Integer types - byte, short, int, and long.
  2. Floating point types - float and double.
  3. Character type - char.
  4. 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

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:

  1. Class: represents a class type, a blueprint for creating objects with common attributes and methods.
  2. Interface: represents an interface type, which defines a set of methods a class must implement.
  3. Array: represents a collection of elements of the same data type stored in contiguous memory locations.
  4. 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.