Within the programming domain, Java shines as a flexible and commonly used language appreciated for its portability (the ability to run on any machine) alongside performance. To develop a Java program that is both efficient and effective, it is necessary to have an understanding of data types. When we mention data types, we are referring to different kinds of information that a variable can hold during program execution. These have an impact on how memory is allocated and the kinds of operations that can be carried out on the data.
In this article, we will cover what data types are in Java, and various Java data types, explore their characteristics with their syntaxes, and even provide examples that would paint a picture of how they are used in practice.
What is a Data Type?
Data types as the name implies define the kind of data a variable can store. Java allows for storing data types with various sizes and values in variables that are created based on the needs and conditions to support every test case. They are essential for assigning variables memory addresses and defining the kinds of operations that can be carried out on them. Java allows two kinds of data types:
Primitive data type
Non-primitive or reference data type
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Data Types in Java
In Java, two data types are supported to create, manipulate, and store the data. These two data types include: primitive and non-primitive. Let’s understand both the types in more detail:
Primitive Data Types
Primitive data types are the predefined data types by Oracle for the Java programming languages. The primitive data types have fixed sizes and memory representations and are supported directly by the hardware. Since primitive data are simple, it is not possible to break them up into smaller parts.
They are the fundamental units that Java applications use to manipulate data. The language predefines primitive type, which is identified by a reserved keyword. Primitive values are independent of one another in terms of state. Simple values are all that primitive data have, and they lack any unique features.
In Java, 8 types of primitive data types are used to create, store, and manipulate the data.
1. boolean
The boolean data type represents a single bit of information and has just two potential values: true or false. However, its “size” isn’t precisely defined; rather, it depends on the virtual machines. Boolean data types are meant to reflect the two truth values of logic and Boolean algebra by representing a single bit of information that might be true or false.
Boolean data types are more commonly used in the control flow statements, or boolean expressions when there is a need for any logical comparison. For straightforward flags that track true or false circumstances, use this data type. There is no implicit or explicit conversion (using casts) of values of type boolean to any other type in boolean. The size of the boolean is dependent on a virtual machine (VM).
Syntax:
boolean nameOfVariable
Example: The below example demonstrates the usage of the boolean primitive data type in Java.
class Example {
public static void main(String[] args) {
boolean isCheck = true; // value of boolean is true or false
boolean isCheck2 = false; // value of boolean is true or false
System.out.println("The value of the primitive data type is: " + isCheck);
System.out.println("The value of the primitive data type is: " + isCheck2);
}
}
Output:
The value of the primitive data type is: true
The value of the primitive data type is: false
2. char
A char data type is a single character data type which can be an alphabetic letter, a number, a symbol, or a blank space. In Java, a char represents a single 16-bit Unicode character with values ranging from ‘u0000’ (or 0) to ‘uffff’ (or 65,535) inclusive.
Syntax:
char nameOfVariable
Example: The below example demonstrates the usage of the chat primitive data type in Java.
class Example {
public static void main(String[] args) {
char c = 'A'; // range of char is 0 to 65535 (Unicode)
char c2 = 'B'; // range of char is 0 to 65535 (Unicode)
char c3 = 'Z'; // range of char is 0 to 65535 (Unicode)
System.out.println("The value of the primitive data type is: " + c);
System.out.println("The value of the primitive data type is: " + c2);
System.out.println("The value of the primitive data type is: " + c3);
}
}
Output:
The value of the primitive data type is: A
The value of the primitive data type is: B
The value of the primitive data type is: Z
3. short
A short data type is a signed 16-bit integer with two’s (2’s) complement integers in Java. Its range is as follows: -32,768 is its least value, while 32,767 is its maximum (inclusive). The same rules that apply to byte also apply to short data types. A short data type is very useful in scenarios where memory savings are truly important, you can use a short to conserve memory in huge arrays. The size of short = 2 bytes = 16 bits.
Syntax:
short nameOfVariable
Example: The below example demonstrates the usage of the short primitive data type in Java.
class Example {
public static void main(String[] args) {
short ans = 32500; // range of short is -32768 to 32767
System.out.println("The value of the primitive data type is: " + ans);
}
}
Output:
The value of the primitive data type is: 32500
4. byte
An 8-bit signed two’s (2’s) complement integer is what a byte data type is— it has an inclusive range, starting from -128 up to 127. In situations where large arrays are involved and there is a need for memory conservation due to the importance of keeping it low, using the byte data type can come in handy.
The byte data type is also used in place of int when their bounds make your code more understandable. The size of 1 byte = 8 bits.
Syntax:
byte varName = 125;
Example: The below example demonstrates the usage of the byte primitive data type in Java.
class Example {
public static void main(String[] args) {
byte ans = 125; // range of byte is -128 to 127
System.out.println("The value of the primitive data type is: " + ans);
}
}
Output:
The value of the primitive data type is: 125
5. int
The int data type is a 32-bit signed two’s complement integer with a minimum value of -2^31 and a maximum value of 2^31-1 (values are default). The int data type can be used in Java SE 8 and later to represent an unsigned 32-bit integer with a maximum value of 2^32-1 and a minimum value of 0. To use the int data type as an unsigned integer, use the Integer class using wrapper classes.
It is the most widely used data type, present in practically all programs with a significant mathematical or arithmetic operation component. The Integer class now supports arithmetic operations for unsigned integers through the addition of static methods like divideUnsigned, compareUnsigned, and so on. The size of int = 4 bytes = 32 bits.
Syntax:
int nameOfVariable
Example: The below example demonstrates the usage of the int primitive data type in Java.
class Example {
public static void main(String[] args) {
int ans = 4578; // range of int is -2147483648 to 2147483647
int ans2 = 42323578; // range of int is -2147483648 to 2147483647
int ans3 = 343434378; // range of int is -2147483648 to 2147483647
System.out.println("The value of the primitive data type is: " + ans);
System.out.println("The value of the primitive data type is: " + ans2);
System.out.println("The value of the primitive data type is: " + ans3);
}
}
Output:
The value of the primitive data type is: 4578
The value of the primitive data type is: 42323578
The value of the primitive data type is: 343434378
6. long
An unsigned 64-bit integer in Java SE 8+ can be represented by the long data type with a minimum value of zero and a maximum value of 2^64-1. The two’s complement integer for the same size is what -2^63 to 2^63-1 (values are default). To use the int data type as an unsigned integer, use the Integer class using wrapper classes.
When you require a range of values larger than those offered by int, use the long data type. When an int type cannot accommodate the required value, the long data type becomes the best type to handle the situation. The size of long = 8 bytes = 64 bits.
Syntax:
long nameOfVariable
Example: The below example demonstrates the usage of the long primitive data type in Java.
class Example {
public static void main(String[] args) {
long ans = 7387398489L; // range of long is -9223372036854775808 to 9223372036854775807
long ans2 = 34823448234L; // range of long is -9223372036854775808 to 9223372036854775807
long ans3 = 92372036854775807L; // range of long is -9223372036854775808 to 9223372036854775807
System.out.println("The value of the primitive data type is: " + ans);
System.out.println("The value of the primitive data type is: " + ans2);
System.out.println("The value of the primitive data type is: " + ans3);
}
}
Output:
The value of the primitive data type is: 7387398489
The value of the primitive data type is: 34823448234
The value of the primitive data type is: 92372036854775807
7. float
The float data type is a 32-bit IEEE 754 floating point with single precision. The float data type range of values is described in the Java Language Specification’s Floating Point. If you need to save memory in large arrays of floating point integers, use a float (instead of a double), just like with the use for byte and short.
Never use this data type to calculate accurate values like currency as it may give you inaccurate values. Therefore, use the java.math for doing that task. The size float =
4 bytes = 32 bits.
Syntax:
float nameOfVariable
Example: The below example demonstrates the usage of the float primitive data type in Java.
class Example {
public static void main(String[] args) {
float ans = 45.3f; // range of float is +/ 1.4E-45 to +/ 3.4E+38
float ans2 = 3.4f; // range of float is +/ 1.4E-45 to +/3.4E+38
float ans3 = 1.4f; // range of float is +/ 1.4E-45 to +/3.4E+38
System.out.println("The value of the primitive data type is: " + ans);
System.out.println("The value of the primitive data type is: " + ans2);
System.out.println("The value of the primitive data type is: " + ans3);
}
}
Output:
The value of the primitive data type is: 45.3
The value of the primitive data type is: 3.4
The value of the primitive data type is: 1.4
8. double
The double data type is an IEEE 754 double-precision 64-bit floating point data. Its range of values is described in the Java Language Specification’s Floating-Point Types. The double data type is typically the default selection for decimal numbers. As previously stated, the float is not recommended to calculate the precise values, rather the double data type is used to get the precise values like in the case of currency.
The size of the double = 8 bytes = 64 bits.
Syntax:
double nameOfVariable
Example: The below example demonstrates the usage of the double primitive data type in Java.
class Example {
public static void main(String[] args) {
double ans = 45.253; // range of double is +/ 4.9E-324 to +/ 1.7E+308
double ans2 = 32323.44; // range of double is +/ 4.9E-324 to +/ 1.7E+308
double ans3 = 23.7; // range of double is +/ 4.9E-324 to +/ 1.7E+308
System.out.println("The value of the primitive data type is: " + ans);
System.out.println("The value of the primitive data type is: " + ans2);
System.out.println("The value of the primitive data type is: " + ans3);
}
}
Output:
The value of the primitive data type is: 45.253
The value of the primitive data type is: 32323.44
The value of the primitive data type is: 23.7
Characteristics of Primitive Data Types
The primitive data types are the most commonly used in the Java language. They come predefined in Java, forming the basis for more complex data structures and objects. There are various characteristics of a primitive data type in Java:
It is the Java language, not the programmer, that defines primitive data types.
Real values, not pointers or addresses to memory locations, are stored by primitive data types.
Primitive types are more memory efficient because the data is kept in memory directly.
The size of each primitive data type is fixed as specified by the Java language specification but varies depending on the platform.
Non-primitive types are inherently less efficient compared to primitive types in both memory consumption and speed of operation.
There are no methods connected to primitive data types. They serve only as value storage devices.
Once assigned, primitive data type’s values cannot be modified, making them immutable.
When primitive types are not explicitly initialised, they have default values.
Non-Primitive or Reference Data Types
Reference data types are constructed using defined classes and include Classes, Interfaces, Arrays, and Enumerations. These data types store references to the data rather than the actual information stored in memory. When it comes to displaying complex structures and information, they are more advanced and adaptable than primitive data types. Since the reference types won’t store the variable value directly in memory, they will instead carry a memory address of the variable values.
In Java, there are various non-primitive or reference data types including strings, classes, arrays, interfaces, and enumerations.
1. Strings
A string is a collection of characters or an array of characters that are frequently used in Java programming. Strings are known as the objects in the Java programming language.
To create and work with strings, Java offers the String class. Java stores and processes text-based data using strings. Strings in Java are immutable therefore, the users cannot change the values of strings after they are formed since they cannot be muted.
Syntax:
String str = “Hello Herovide!”
Example: The below example demonstrates the usage of the string non-primitive data type in Java.
class Example {
public static void main(String[] args) {
String myName = "Hello Herovide!";
System.out.println("The value of the non-primitive data type is: " + myName);
}
}
Output:
The value of the non-primitive data type is: Hello Herovide!
2. Classes
Classes are the blueprint of the objects in the object-oriented paradigm. Classes describe the structure, characteristics, and states of objects. A class acts as a template that users can utilise to create various objects like a real-world entity. It symbolises the collection of attributes or operations shared by every object of a certain type. Classes contain both data and methods to be performed on the data, and this concept is known as encapsulation.
Classes in Java are created by including below components:
Fields: The first item that a class includes are the variables that store an object’s state, also known as attributes or variables.
Methods: Another item class stores are functions specified inside a class that explain how an object behaves. Operations and field manipulation are capabilities of methods.
Constructors: They are a unique method for initialising an object but without a return type and with the same name as the class.
Body: The class body is the part that is between the {} curly braces.
Access Modifiers: Keywords (public, private, protected, etc.) that specify how the class, its fields, and its methods are visible.
Syntax:
public class Vehicle {
String model;
String year;
void showVehicle() {
System.out.println(“The vehicle model is ” + model + “and Year is ” + year);
}
}
Example: The below example demonstrates the usage of the class non-primitive data type in Java.
class Vehicle {
String model;
String maker;
int year;
Vehicle(String model, String maker, int year) {
this.model = model;
this.maker = maker;
this.year = year;
}
}
public class Example {
public static void main(String[] args) {
Vehicle car = new Vehicle("M5 sport", "BMW", 2022);
System.out.println("The car is" + car.maker + car.model + " built in the year" + car.year);
}
}
Output:
The car is BMWM5 sport built in the year2022
3. Interfaces
An interface in Java can have variables and methods much like a class, however by default, the methods described in an interface are abstract. They simply have a method signature without a body. The interfaces in Java allow collections to be manipulated independently of the details of their representation.
In Java, an interface is a set of linked method blueprints that a class needs to include. Java’s equivalent of a class, an interface is a reference type that can only have constants, method signatures, default methods, static methods, and nested types. Instance fields and constructors are not permitted in interfaces.
Syntax:
public interface Vehicle {
double car();
double bike();
}
Example: The below example demonstrates the usage of the Interfaces non-primitive data type in Java.
interface Driveable {
void drive();
}
class Vehicle implements Driveable {
String model;
String maker;
int year;
Vehicle(String model, String maker, int year) {
this.model = model;
this.maker = maker;
this.year = year;
}
@Override
public void drive() {
System.out.println("Driving the " + maker + " " + model + " built in " + year);
}
}
public class Example {
public static void main(String[] args) {
Vehicle car = new Vehicle("M5 Sport", "BMW", 2022);
System.out.println("The car is a " + car.maker + " " + car.model + " built in the year " + car.year);
car.drive();
}
}
Output:
The car is a BMW M5 Sport built in the year 2022
Driving the BMW M5 Sport built in 2022
4. Arrays
Arrays are the fixed-sequence contiguous elements of the same type of data structure in a programming language. Arrays are containers that hold multiple values of the same type. It may contain multiple elements, unlike a primitive data type variable. The array is referred to as empty if there are no variables in it. An array’s variables don’t have names. Instead, non-negative integer index values are used in array access expressions to refer to them. These variables are referred to as the array elements.
An array’s length (n), is determined by its number of components, which are identified by integer indices ranging from 0 to n – 1. For example, we can print the first, and last elements of the array along with its length using this example. Like, the length of the array (numbers.length), the first element (numbers[0]), and the last element (numbers[numbers.length – 1]) of the array are printed to the console, for instance, using System.out.println().
Syntax:
int[] arr = {10, 202, 34, 123, 45};
Example: The below example demonstrates the usage of the Arrays non-primitive data type in Java.
import java.util.*;
public class Example {
public static void main(String[] args) {
int[] arr = {34, 4, 42, 54, 14, 65, 87};
char[] arr2 = {'A', 'C', 'D', 'F'};
System.out.println("The elements in the array are: " + Arrays.toString(arr));
System.out.println("The elements in the array are: " + Arrays.toString(arr2));
}
}
Output:
The elements in the array are: [34, 4, 42, 54, 14, 65, 87]
The elements in the array are: [A, C, D, F]
5. Enumerations
Enumerations in Java are used when a fixed collection of named values is required, type-safe enumerations can be defined using an enum keyword. Implicitly, every enum extends java.lang.List all. Enums are special Java types used to define collections of constants. One or more enum constants, which specify particular instances of the enum type, can be found in enums. An enum declaration declares an enum type, which is very similar to a class in that it can (and usually does) have constructors, methods, fields, and other members.
Syntax:
enum Languages {
JAVA, C++, PYTHON, JAVASCRIPT, GO, HTML
}
Example: The below example demonstrates the usage of the Enumeration non-primitive data type in Java.
enum Languages {
JAVA,
JAVASCRIPT,
PYTHON,
GO,
HTML
}
public class Example {
public static void main(String[] args) {
Languages web = Languages.HTML;
Languages ds = Languages.PYTHON;
Languages oop = Languages.JAVASCRIPT;
System.out.println("The result is: " + web);
System.out.println("The result is: " + ds);
System.out.println("The result is: " + oop);
}
}
Output:
The result is: HTML
The result is: PYTHON
The result is: JAVASCRIPT
Characteristics of Non-Primitive Data Types
The non-primitive data types are complex to create but are easy to use. They are manually created by the Java programmer. There are various characteristics of a non-primitive data type in Java:
The non-primitive data types like classes, interfaces, and arrays are created manually by the programmers.
These data types can include a null value assigned to them to indicate that they do not reference any objects.
The non-primitive data types do not store the actual value, instead store the references to those values in the memory.
It is possible to conduct operations on the data using the methods and characteristics of non-primitive types.
A non-primitive data type’s size is variable and contingent upon the nature of the object and its contents.
Non-primitive data types have dynamic memory allocation, usually on the heap.
Any variable of non-primitive data type has null as its default value.
Type Conversion and Casting
In Java, type conversion is the process of converting one data type into another for a variable. Implicit conversion (data widening) and explicit conversion (data narrowing) are the two types of conversion that are used for converting a data type into another.
Note that one data type may not be compatible with another when you assign a value from one type to another. Java’s Automatic Type Conversion feature will automatically convert data types if they are compatible; otherwise, the data types must be cast or converted explicitly.
Implicit Type Conversion
Implicit as the name implies internal, means here the type of data is converted internally or automatically by Java itself. This conversion happens on its own when the range of the source type is smaller than that of the destination type. There is no need for explicit casting with this kind of conversion, which is safe.
Example: The below example demonstrates the usage of implicit type conversion in Java.
class Example {
public static void main(String[] args) {
int num1 = 500;
long num2 = num1; // int to long conversion automatically
float num3 = num2; // long to float conversion automatically
System.out.println("The value of int type is: " + num1);
System.out.println("The value of long type is: " + num2);
System.out.println("The value of float type is: " + num3);
}
}
Output:
The value of int type is: 500
The value of long type is: 500
The value of float type is: 500.0
Explicit Type Casting
Explicit as the name means clear, states that here the type of data is converted manually by assigning the type to be converted by the programmers. Since explicit conversion, often referred to as narrowing conversion, entails changing a bigger range type to a smaller range type, which may result in data loss, explicit casting is necessary.
Example: The below example demonstrates the usage of explicit type conversion in Java.
class Example {
public static void main(String[] args) {
double num1 = 10.44;
long num2 = (long) num1; // double to long conversion explicitly
int num3 = (int) num2; // long to int conversion explicitly
System.out.println("The value of double type is: " + num1);
System.out.println("The value of double to long conversion is: " + num2);
System.out.println("The value of long to int conversion is: " + num3);
}
}
Output:
The value of double type is: 10.44
The value of double to long conversion is: 10
The value of long to int conversion is: 10
Wrapper Classes
A wrapper class is a class that works by wrapping the objects of the primitive data types. Because the generic classes essentially don’t support primitives and allow only functions with objects. Therefore, to operate with them, we must use wrapper objects from primitive values. The Java Collection Framework, for instance, only uses objects.
In the past, the primitive values had to be manually transformed into matching wrapper classes before being placed in collections. One technique to use primitive data types as objects is using wrapper classes. There is a corresponding wrapper class for every primitive type.
In Java, there 8 wrapper classes for all primitive data types and these are:
Character for char
Boolean for boolean
String for string
Integer for int
Short for short
Long for long
Float for float
Double for double
In the wrapper classes, we have to manually specify the wrapper class to convert a primitive data type to an object or a corresponding wrapper class. But this task of manual conversion can be hectic. Therefore, we will use a concept known as boxing.
Syntax:
int val = 10;
Integer intVal = Integer.valueOf(val); // wrapping the object
int newVal = integerValue.intVal(); //unwrapping the object
Example: The below example demonstrates the usage of wrapper classes using the Integer class in Java.
import java.util.*;
class ExampleMy {
public static void main(String[] args) {
int myNum = 78;
Integer intValNum = Integer.valueOf(myNum); // wrapping
int ans = intValNum.intValue(); // unwrapping
System.out.println("The result of using wrapper classes is: " + ans);
}
}
Output:
The result of using wrapper classes is: 78
Autoboxing and Unboxing
Before we move on to autoboxing and unboxing, let’s learn what is Boxing. The process of translating a raw value into an equivalent wrapper object is called “boxing.”
Autoboxing
Autoboxing is the automatic conversion of primitive types to their corresponding wrapper classes.
Example: The below example demonstrates the usage of autoboxing the data types in Java.
import java.util.*;
class ExampleMy {
public static void main(String[] args) {
List<Integer> ls = new ArrayList<>();
ls.add(10); // adding the data
System.out.println("The result of List after autoboxing: " + ls);
Integer ans = 30; // autoboxing conversion
System.out.println("The result of Integer after autoboxing: " + ans);
}
}
Output:
The result of List after autoboxing: [10]
The result of Integer after autoboxing: 30
Unboxing
Unboxing is done when a wrapper object is unwrapped into a primitive value. It’s the reverse of the autoboxing method.
Example: The below example demonstrates the usage of unboxing the data types in Java.
import java.util.*;
class ExampleMy {
public static void main(String[] args) {
Integer obj = new Integer(9);
int ans1 = cubeRootOfNum(obj); //unboxing
int ans2 = obj; //unboxing
System.out.println("The result of Integer after autoboxing: " + ans1);
}
public static int cubeRootOfNum(int n) {
return n * n * n;
}
}
Output:
The result of Integer after autoboxing: 7299
Collections Framework
A collection of classes and interfaces that offer an already-built architecture is called a framework. A collection of classes and interfaces for managing and storing collections of data as a single entity are offered by the Java Collections Framework. With the Java Collection Framework, the user can store, search, sort, insert, remove, and update data on a set of elements, among other data manipulation functions. List, Set, and Map are a few important interfaces provided by the collections framework.
1. List
A list is an ordered collection that is also referred to as a sequence. Duplicate elements can be added to the list in Java. To use a List, we can create objects with various available classes including ArrayList, LinkedList, etc.
Example: The below example demonstrates the usage of the List (ArrayList) data type of collections framework in Java.
import java.util.ArrayList;
class Example {
public static void main(String[] args) {
// Create an ArrayList of String type
ArrayList<String> list = new ArrayList<>();
// Adding the data to the ArrayList
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
// Printing the ArrayList elements
System.out.println("Elements in the ArrayList are: ");
for (String element : list) {
System.out.println(element);
}
list.remove(3); // add the index (0-based)
// Printing the ArrayList elements after removal
System.out.println("Elements in the ArrayList are: ");
for (String element : list) {
System.out.println(element);
}
}
}
Output:
Elements in the ArrayList are:
One
Two
Three
Four
Elements in the ArrayList are:
One
Two
Three
2. Map
A Map interface is a data structure that supports the key-value pair needed to map the data. A map is an object that associates or maps the values with keys. A key can map to a maximum of one value in a map; multiple keys are not allowed.
Example: The below example demonstrates the usage of the Map (HashMap) data type of collections framework in Java.
import java.util.HashMap;
import java.util.Map;
class HashMapExample {
public static void main(String[] args) {
// Create a HashMap of Int and String and Key and Value pair
HashMap<Integer, String> map = new HashMap<>();
// Add the data as key and value to the map
map.put(1, "Welcome to Java!");
map.put(2, "Welcome to C++!");
map.put(3, "Welcome to JavaScript!");
map.put(4, "Welcome to Python!");
map.put(5, "Welcome to Go lang!");
// Traverse the Map to get all values from Map
for (Map.Entry<Integer, String> et : map.entrySet()) {
System.out.println("The stored data in the HashMap at Key " + et.getKey() + ": " + et.getValue());
}
}
}
Output:
The stored data in the HashMap at Key 1: Welcome to Java!
The stored data in the HashMap at Key 2: Welcome to C++!
The stored data in the HashMap at Key 3: Welcome to JavaScript!
The stored data in the HashMap at Key 4: Welcome to Python!
The stored data in the HashMap at Key 5: Welcome to Go lang!
3. Set
An unordered group of items whose duplicate values cannot be kept is called a set. It is a collection in which duplicate components are not added.
Example: The below example demonstrates the usage of the Set (HashSet) data type of collections framework in Java.
import java.util.HashSet;
class Example {
public static void main(String[] args) {
// Create a HashSet of String type
HashSet<String> set = new HashSet<>();
// Adding the data to the HashSet
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
// Printing the HashSet elements
System.out.println("Elements in the HashSet are: ");
for (String element : set) {
System.out.println(element);
}
}
}
Output:
Elements in the HashSet are:
One
Four
Two
Three
Difference Between Primitive and Non-Primitive Data Types in Java
The primitive and non-primitive data types have a few differences that differ in various aspects including storage, size, memory allocation, etc. Here are the key differences between the primitive and non-primitive data types in Java:
Parameter
Primitive
Non-Primitive
Define
The primitive data types are created automatically and are ready to use by the programmers.
The non-primitive data types are created manually by the programmers.
Storage
The primitive data types store the actual or the given value of the data.
The non-primitive data types store the references to objects of the class.
Size
The primitive data type size is fixed.
The non-primitive data type size is varied depending on the object created.
Memory allocation
Memory of the primitive data types is allocated in the stack.
The memory of the non-primitive data types is allocated in the heap.
Methods
The primitive types do not contain any methods.
The non-primitive types contain methods along with the properties.
Null values
The primitive types cannot be null.
The non-primitive types can be null.
Default
The primitive type’s default value is 0 or false.
The non-primitive type default value is null.
Mutability
The values in primitive data types are immutable.
The values in primitive data types can be mutable or immutable.
Operations
It can perform arithmetic operations.
It can perform complex as well as arithmetic operations.
Access Speed
It is faster compared to non-primitive data types in Java.
It is slower than primitive data types due to dereferencing.
Inheritance
Inheritance can’t be used in this type of data.
Inheritance can be used here.
Garbage collection
Not applicable in the case of primitive data types.
It is done by the automatic garbage collection in Java.
Examples
Examples of primitive data types are int, float, double, etc.
Examples of primitive data types are strings, arrays, interfaces, classes, etc.
Conclusion
In this article, we have covered the data types in Java in detail. Primitive and non-primitive are two types of data types in Java that are mainly used for defining the types of data in a variable. We learned detailed implementation for each type of data type whether it is char, string, int, boolean, Map, List, etc., with their syntaxes and examples. Wrapper classes with the autoboxing and unboxing methods were also covered in this article.
Beginners can develop a strong foundation in Java programming and be ready to take on more challenging subjects and projects by grasping these ideas. A solid grasp of Java data types can be helpful whether you’re working on a complex system or creating a simple application.
FAQs
What are the different types of data types in Java?
In Java, there are two types of data types. The two data types are primitive and non-primitive data types. Primitive data types are the data types that can store a single value, whereas non-primitive data types can store multiple values in Java.
What is Type conversion in Java?
Type conversion is the process of converting one data type into another for a variable. There are two types of Type conversion in Java: implicit and explicit conversion.
What are wrapper classes in Java?
Wrapper classes in Java allow the programmer a way to use primitive data types as objects. There are 8 different wrapper classes including Boolean, Byte, Short, Character, Integer, Long, Float, and Double.
What is the size of the char data type in Java?
In Java, the char data type is 2 bytes (16 bits) in size.
What occurs in Java when you go over the bounds of a primitive data type?
Basic data types in Java may exhibit different behaviours when their range is exceeded. Values of integer types, such as byte, short, and int, may wrap around due to overflow or underflow. When you increase an int data type's maximum value, it rounds down to the lowest number.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.