Table of contents
1.
Introduction
2.
What are Data Types in Java?
3.
Types of Programming Languages
3.1.
1. Statically-Typed Languages
3.2.
2. Dynamically-Typed Languages
3.3.
3. Strongly-Typed Languages
3.4.
4. Weakly-Typed Languages
4.
Types of Data Types in Java
4.1.
1. Primitive Data Types
4.2.
2. Reference/Object Data Types
5.
Why There are So Many Data Types in Java?
5.1.
1. Memory Optimization
5.2.
2. Performance
5.3.
3. Precision
5.4.
4. Range
5.5.
5. Readability & Maintainability
6.
Types of Primitive Data Types in Java
6.1.
Numeric Data Types
6.2.
Non-Numeric Data Types
7.
Numeric Data Types
8.
Non-Numeric Data Types
8.1.
1. char
8.2.
2. boolean
8.3.
1. Autoboxing
8.4.
2. Unboxing
9.
Frequently Asked Questions
9.1.
Can we use primitive data types in collections like ArrayList?
9.2.
What is the default value of a local variable in Java?
9.3.
Is it possible to convert a String to a primitive data type in Java?
10.
Conclusion
Last Updated: Jul 31, 2024
Easy

Range of Data Types in Java

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Data types are the basic building blocks of any programming language. They define what kind of data can be stored & processed by a computer program. In Java, data types specify the size & type of values that can be stored in a variable. Java provides a wide range of data types to handle different kinds of data efficiently. 

Range of Data Types in Java

In this article, we will talk about the different data types available in Java. We will understand their characteristics, & learn how to use them effectively in our programs.

What are Data Types in Java?

In Java, a data type defines the type of data that a variable can hold. It determines the size & layout of the variable's memory, the range of values that can be stored within that memory, & the set of operations that can be performed on the variable. Java is a statically-typed language, which means that all variables must be declared with their data type before they can be used in the program. This helps catch type-related errors at compile-time rather than at runtime, making the code more robust & easier to maintain.

Java provides two main categories of data types:

1. Primitive Data Types: These are the most basic data types available in Java. They are not objects & are used to store simple values like integers, floating-point numbers, characters, & booleans.
 

2. Reference/Object Data Types: These are used to store complex values like objects & arrays. Reference data types refer to objects & are used to access their properties & methods.

Types of Programming Languages

Before diving into the specifics of data types in Java, let's take a quick look at the different types of programming languages based on their type systems:

1. Statically-Typed Languages

In statically-typed languages like Java, C++, & C#, variables must be declared with their data type before they can be used. The type of a variable is checked at compile-time, & any type-related errors are caught early in the development process. This makes the code more reliable & easier to maintain.

2. Dynamically-Typed Languages

In dynamically-typed languages like Python, JavaScript, & Ruby, variables can be declared without specifying their data type. The type of a variable is determined at runtime based on the value assigned to it. This provides more flexibility but can also lead to type-related errors that are harder to catch.

3. Strongly-Typed Languages

In strongly-typed languages like Java, Python, & Ruby, variables have a specific data type, & implicit type conversions are not allowed. This means that you cannot perform operations on incompatible data types without explicitly converting them first.

4. Weakly-Typed Languages

In weakly-typed languages like C & C++, variables can be implicitly converted from one data type to another based on the context in which they are used. This can lead to unexpected behavior & type-related errors if not handled carefully.


Note: Java is a statically-typed & strongly-typed language, which provides a good balance between reliability & performance.

Types of Data Types in Java

Java provides a rich set of data types to handle different kinds of data efficiently. These data types can be classified into two main categories: primitive data types & reference/object data types.

1. Primitive Data Types

Primitive data types are the most basic data types available in Java. They are used to store simple values like integers, floating-point numbers, characters, & booleans. Java provides eight primitive data types:

- byte

- short

- int

- long

- float

- double

- char

- boolean


Primitive data types are not objects & are stored directly in the stack memory. They have a fixed size & are faster to access compared to reference data types.

2. Reference/Object Data Types

Reference data types are used to store complex values like objects & arrays. They refer to objects that are stored in the heap memory & are accessed through a reference variable. Some commonly used reference data types in Java include:

- String

- Arrays

- Classes

- Interfaces


Reference data types have a variable size & are slower to access compared to primitive data types. They provide more flexibility & allow for complex data structures & operations.

Let’s look at an example which shows declaration and initialization of variable : 

// Primitive data types
byte age = 25;
short score = 1000;
int totalStudents = 500;
long population = 7000000000L;
float pi = 3.14f;
double exactValue = 3.141592653589793;
char grade = 'A';
boolean isStudent = true;


// Reference data types
String name = "Ravi kumar";
int[] marks = {90, 85, 95};
Student student = new Student("Ravi Kumar", 20);

Why There are So Many Data Types in Java?

Java provides a wide range of data types to handle different kinds of data efficiently. The reason for having multiple data types is to optimize memory usage & improve performance. Each data type has a specific size & purpose, allowing developers to choose the most appropriate one for their needs.

1. Memory Optimization

Different data types occupy different amounts of memory. By using the appropriate data type for a variable, we can ensure that we are not wasting memory unnecessarily. For example, if we need to store a small integer value, we can use the `byte` data type (1 byte) instead of the `int` data type (4 bytes), saving memory.

2. Performance

Using the right data type can also improve the performance of our programs. Primitive data types are faster to access & manipulate compared to reference data types because they are stored directly in the stack memory. By using primitive data types wherever possible, we can improve the execution speed of our code.

3. Precision

Java provides data types with different levels of precision for storing floating-point numbers. The `float` data type (4 bytes) has a precision of 6-7 decimal digits, while the `double` data type (8 bytes) has a precision of 15-16 decimal digits. By choosing the appropriate data type, we can ensure that we have the required precision for our calculations.

4. Range

Each numeric data type in Java has a specific range of values that it can represent. For example, the `byte` data type can store values from -128 to 127, while the `int` data type can store values from -2,147,483,648 to 2,147,483,647. By choosing the appropriate data type based on the range of values we expect, we can avoid overflow & underflow errors.

5. Readability & Maintainability

Using specific data types for different purposes makes our code more readable & maintainable. It communicates the intent of the variable & helps other developers understand its purpose. For example, using the `boolean` data type for a flag variable clearly indicates that it can only have two possible values: `true` or `false`.


Example that shows the importance fo choosing correct data type: 

// Using byte instead of int for small values
byte age = 25;
// Using double instead of float for more precision
double pi = 3.141592653589793;
// Using boolean for flag variables
boolean isStudent = true;


Note: If we use the appropriate data types, we can write code that is memory-efficient, performant, & easy to understand.

Types of Primitive Data Types in Java

Java provides eight primitive data types that can be categorized into two main groups: numeric & non-numeric data types.

Numeric Data Types

Numeric data types are used to store numbers, including integers & floating-point values. Java provides six numeric data types:

1. byte:

- Size: 1 byte (8 bits)

- Range: -128 to 127

- Default value: 0

- Example: `byte age = 25;`
 

2. short:

- Size: 2 bytes (16 bits)

- Range: -32,768 to 32,767

- Default value: 0

- Example: `short score = 1000;`


3. int:

- Size: 4 bytes (32 bits)

- Range: -2,147,483,648 to 2,147,483,647

- Default value: 0

- Example: `int totalStudents = 500;`


4. long:

- Size: 8 bytes (64 bits)

- Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

- Default value: 0L

- Example: `long population = 7000000000L;`


5. float:

- Size: 4 bytes (32 bits)

- Range: Approximately ±3.40282347E+38F (6-7 decimal digits)

- Default value: 0.0f

- Example: `float pi = 3.14f;`
 

6. double:

- Size: 8 bytes (64 bits)

- Range: Approximately ±1.79769313486231570E+308 (15-16 decimal digits)

- Default value: 0.0d

- Example: `double exactValue = 3.141592653589793;`

Non-Numeric Data Types

Java provides two non-numeric primitive data types:

1. char:

- Size: 2 bytes (16 bits)

- Range: 0 to 65,535 (Unicode characters)

- Default value: '\u0000' (null character)

- Example: `char grade = 'A';`
 

2. boolean

- Size: Not precisely defined (usually 1 bit)

- Range: true or false

- Default value: false

- Example: `boolean isStudent = true;`

These primitive data types form the foundation for storing & manipulating data in Java programs. By understanding their characteristics & ranges, developers can choose the most appropriate data type for their variables, ensuring optimal memory usage & performance.

Numeric Data Types

Numeric data types in Java are used to store numbers, including integers & floating-point values. There are six numeric data types in Java: byte, short, int, long, float, & double. Let's discuss each of these data types in more detail.

1. byte:

The byte data type is an 8-bit signed two's complement integer. It can store values from -128 to 127. It is useful for saving memory in large arrays or for storing small integer values.

Example:

byte age = 25;
byte temperature = -10;


2. short:

The short data type is a 16-bit signed two's complement integer. It can store values from -32,768 to 32,767. It is useful for saving memory in large arrays or for storing small to medium integer values.

Example:

short score = 1000;
short distance = -5000;


3. int:

The int data type is a 32-bit signed two's complement integer. It can store values from -2,147,483,648 to 2,147,483,647. It is the most commonly used data type for storing integer values.

Example:

int totalStudents = 500;
int balance = -1000000;

4. long:

The long data type is a 64-bit signed two's complement integer. It can store values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It is useful for storing large integer values.

Example:

long population = 7000000000L;
long accountNumber = 1234567890123456L;


5. float:

The float data type is a single-precision 32-bit IEEE 754 floating-point. It can store decimal values with a precision of 6-7 digits. It is useful for storing decimal values with moderate precision.

Example:

float pi = 3.14f;
float price = 9.99f;


6. double:

The double data type is a double-precision 64-bit IEEE 754 floating-point. It can store decimal values with a precision of 15-16 digits. It is the default data type for decimal values & is useful for storing decimal values with high precision.

Example:

double exactValue = 3.141592653589793;
double scientificNotation = 1.23456e2;

Non-Numeric Data Types

In addition to numeric data types, Java provides two non-numeric primitive data types: char & boolean. These data types are used to store characters & logical values, respectively. Let's discuss each of these data types in more detail.

1. char

The char data type is a single 16-bit Unicode character. It can store a single character, such as a letter, digit, or symbol. The values of the char data type are enclosed in single quotes.

Example:

char grade = 'A';
char symbol = '$';
char newLine = '\n';


The char data type uses Unicode encoding, which allows it to represent a wide range of characters from various languages & scripts. Each character is assigned a unique Unicode value, ranging from 0 to 65,535.

In addition to standard characters, the char data type can also represent escape sequences, such as '\n' for a new line, '\t' for a tab, & '\\' for a backslash.

2. boolean

The boolean data type is used to store logical values, which can be either true or false. It is commonly used for conditional statements, flags, & logical operations.

Example

boolean isStudent = true;
boolean isPassed = false;
boolean isAvailable = true;


The boolean data type is not precisely defined in terms of size, as it depends on the Java Virtual Machine (JVM) implementation. However, it is typically represented using 1 bit, where 0 represents false & 1 represents true.

Boolean variables are often used in control flow statements, such as if-else & while loops, to make decisions based on certain conditions.

Example:

int score = 80;
boolean isPassed = score >= 60;
if (isPassed) {
    System.out.println("Congratulations! You passed the exam.");
} else {
    System.out.println("Sorry, you failed the exam. Better luck next time!");
}


Note: Non-numeric data types, char & boolean, provide a way to store & manipulate characters & logical values in Java programs. They are essential for handling text-based data & making decisions based on conditions.

Conversion of Primitive Data Types to Respective Wrapper Classes In Java, each primitive data type has a corresponding wrapper class that provides additional functionality & allows the primitive values to be treated as objects. These wrapper classes are part of the java.lang package & are used in situations where objects are required, such as in collections or when using generics.

Let’s look at a table that shows the primitive data types & their corresponding wrapper classes:

Primitive Data Type

Wrapper Class

byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

 

 

Java provides automatic conversion between primitive data types & their corresponding wrapper classes, known as autoboxing & unboxing.

1. Autoboxing

Autoboxing is the automatic conversion of a primitive value to its corresponding wrapper class object. It is performed implicitly by the Java compiler.

Example:

int num = 10;
Integer numObj = num; // Autoboxing: int to Integer


In this example, the primitive int value num is automatically converted to an Integer object numObj.

2. Unboxing

Unboxing is the automatic conversion of a wrapper class object to its corresponding primitive value. It is also performed implicitly by the Java compiler.

Example:

Integer numObj = 20;
int num = numObj; // Unboxing: Integer to int


In this example, the Integer object numObj is automatically converted to a primitive int value num.

Autoboxing & unboxing provide a convenient way to work with primitive values as objects & vice versa. They allow seamless integration between primitive data types & their wrapper classes, making it easier to use them interchangeably in different contexts.

However, it's important to note that excessive use of autoboxing & unboxing can have a slight performance overhead compared to using primitive data types directly. Therefore, in performance-critical scenarios, it's recommended to use primitive data types whenever possible.

Let’s look at an example that shows the use of wrapper classes:

List<Integer> numbers = new ArrayList<>();
numbers.add(10); // Autoboxing: int to Integer
numbers.add(20);
numbers.add(30);
int sum = 0;
for (Integer num : numbers) {
    sum += num; // Unboxing: Integer to int
}
System.out.println("Sum: " + sum);


In this example, the ArrayList numbers stores Integer objects. The primitive int values are autoboxed when added to the list. During the sum calculation, the Integer objects are unboxed to primitive int values.

Frequently Asked Questions

Can we use primitive data types in collections like ArrayList?

No, collections in Java only work with objects. To store primitive values in collections, we need to use their corresponding wrapper classes, such as Integer for int, Double for double, etc.

What is the default value of a local variable in Java?

Local variables in Java do not have a default value. They must be explicitly initialized before they can be used, otherwise, the compiler will throw an error.

Is it possible to convert a String to a primitive data type in Java?

Yes, Java provides methods in the wrapper classes to parse a String & convert it to the corresponding primitive data type. For example, Integer.parseInt("10") converts the String "10" to the int value 10.

Conclusion

In this article, we have learned about the various data types available in Java. We explained the differences between primitive & reference data types, & how they are used to store different kinds of data. We also discussed the numeric & non-numeric primitive data types in detail, along with their ranges & default values. Finally, we learned about the wrapper classes & how they allow us to convert between primitive data types & objects using autoboxing & unboxing. 

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass