Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Boolean Data Type
3.
Byte Data Type
4.
Short Data Type
5.
Integer Data Type
6.
Long Data Type
7.
Float Data Type
8.
Double Data Type
9.
Char Data Type
10.
Why is the Size of char 2 bytes in Java?
11.
Example of Using Char in Java
11.1.
Java
12.
Frequently Asked Questions
12.1.
Why are primitive types important in Java?
12.2.
Can I use int instead of byte or short to save programming effort?
12.3.
How does Java handle numerical overflow in primitive types?
13.
Conclusion
Last Updated: Jun 1, 2024
Medium

Java Primitive Data Types

Author Rinki Deka
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Java, a widely-used programming language, is built on the foundation of various data types, among which the primitive types are the most basic and essential. These types serve as the building blocks for data manipulation in Java applications. Understanding these primitive types is crucial for anyone starting their journey in Java programming, as they underpin all operations within the code. 

Java Primitive Data Types

In this article we will learn what primitive types are, their importance, and how they are utilized in Java programming.

Boolean Data Type

In Java, the Boolean data type is quite straightforward. It can only hold two possible values: true or false. This type is particularly useful in controlling the flow of a program, such as deciding which code block to execute in if-else statements or controlling loops with while or for constructs.

For example, if a program needs to check whether a user is logged in, the Boolean value can be used directly in an if statement to decide the next steps:

boolean isLoggedIn = true; // User is logged in
if (isLoggedIn) {
    System.out.println("Welcome back, user!");
} else {
    System.out.println("Please log in.");
}


This simple use of Boolean shows how integral it is in making decisions within your code.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Byte Data Type

The byte data type in Java is used to save space in large arrays, primarily in files and streams of raw data. Unlike the more common int data type, which occupies four bytes of memory, a byte only takes one byte, making it more efficient for handling data with size constraints. It can store values from -128 to 127, covering the range of most basic data needs.

For example, consider a scenario where we need to handle a sequence of bytes from a file:

byte[] fileData = new byte[1024]; // Array to store 1024 bytes of data from a file
// Assume fileData is filled with data
for(int i = 0; i < fileData.length; i++) {
    System.out.println(fileData[i]);
}


This code snippet efficiently processes each byte of data, ideal for scenarios where memory usage is critical, such as in embedded systems or large-scale data processing.

Short Data Type

The short data type in Java is another way to store numerical values while using less memory than the typical int. A short occupies 2 bytes of memory and can hold values from -32,768 to 32,767. It's particularly useful when you have a clear understanding that the values you need to store will not exceed this range, helping optimize memory usage in large arrays or systems with limited resources.

Here's a simple example using the short data type:

short numberOfStudents = 150;
short temperature = -20;
System.out.println("Number of students: " + numberOfStudents);
System.out.println("Temperature: " + temperature);


This example shows how short can be effectively used for everyday values like counting people or measuring temperature, especially when these values are unlikely to be very high or low.

Integer Data Type

The integer (int) data type is one of the most commonly used types in Java. It is used to store whole numbers from -2,147,483,648 to 2,147,483,647. This wide range makes int a versatile choice for variables where values are expected to range beyond the short type's capacity, such as in counting operations, loops, and calculations involving larger numbers.

Consider the following example:

int population = 132000;
int salary = 50000;
int distance = 350;
System.out.println("City population: " + population);
System.out.println("Average salary: " + salary);
System.out.println("Distance covered: " + distance);


This code efficiently handles larger numbers that are common in real-world applications, such as population counts or financial transactions.

Long Data Type

When dealing with even larger numbers than what int can handle, Java provides the long data type. It can store whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, accommodating the needs of calculations that involve extensive numerical data, such as in scientific computations or when working with large databases.

For example : 

long globalPopulation = 7800000000L; // World population
long nationalDebt = 23000000000000L; // National debt in hypothetical currency
System.out.println("Global population: " + globalPopulation);
System.out.println("National debt: " + nationalDebt);


This example demonstrates how long is crucial for storing and manipulating numbers that exceed the limits of int, ensuring accuracy in large-scale numerical operations.

Float Data Type

The float data type in Java is used to represent numbers with fractional parts, commonly referred to as floating-point numbers. It is essential when precise calculations are necessary, particularly in scenarios involving decimals, like measurements or financial transactions where exactness matters. A float can typically store up to 7 decimal digits.

Here's how you might use the float data type in Java:

float highTemperature = 38.5f; // High temperature in Celsius
float price = 299.99f; // Price of an item
System.out.println("The high today is: " + highTemperature + " degrees Celsius.");
System.out.println("Total cost: " + price + " dollars.");


This example shows the practical use of float for everyday applications where small decimal values are crucial, such as temperature readings or pricing items.

Double Data Type

In Java, the double data type is another option for representing numbers with decimal points, and it offers greater precision than float. It stores floating-point numbers using double precision, which allows up to 15 decimal digits. This makes double ideal for more complex calculations that require a high degree of accuracy, such as scientific computations or financial analysis involving large numbers.

Consider this example of using double:

double pi = 3.141592653589793; // More precise value of pi
double gravitationalConstant = 6.67430e-11; // Gravitational constant in scientific notation
System.out.println("Value of Pi: " + pi);
System.out.println("Gravitational Constant: " + gravitationalConstant);


This snippet demonstrates the precision of double for critical scientific constants that require more exact figures in computations.

Char Data Type

The char data type in Java is used to store single characters, such as letters, digits, or other symbols, and it occupies 2 bytes of memory. This might seem unusual since other languages often use only 1 byte for characters. The reason Java uses 2 bytes for the char type is that it utilizes the Unicode system, which allows a wide array of characters from various languages to be represented, not just the basic ASCII set.

Here’s a simple way to use the char data type:

char letter = 'A';
char number = '1';
char symbol = '$';
System.out.println("Letter: " + letter);
System.out.println("Number: " + number);
System.out.println("Symbol: " + symbol);


This example demonstrates how char can hold not only English letters but also numbers and symbols, making it versatile for handling a variety of data in applications.

Why is the Size of char 2 bytes in Java?

In Java, each char data type occupies 2 bytes of memory, which allows it to represent a wider range of characters compared to other languages that use 1 byte. This design choice stems from Java's use of the Unicode standard, which covers a vast array of characters and symbols from multiple languages and scripts around the world.

Unicode requires more space because it aims to provide a unique code for every character, no matter the platform, program, or language. This universality ensures that Java applications can handle data internationally without encountering the common encoding issues that might arise when using simpler character sets that fit in 1 byte. This capability is especially important in our interconnected and digitally diverse world, ensuring that applications are globally versatile.

Here’s an example to visualize the difference:

char a = 'A'; // Standard ASCII character
char b = 'अ'; // Devanagari character representing a sound in several languages including Hindi and Sanskrit
System.out.println("ASCII character: " + a);
System.out.println("Unicode character: " + b);


In this example, both an ASCII character and a Unicode character are stored as char types in Java, demonstrating the need for 2 bytes to accommodate characters beyond the basic ASCII set.

Example of Using Char in Java

To understand how the char data type is utilized in Java programming, let's explore a practical example. The char type is often used in scenarios where individual characters from strings need to be processed, such as in input validation, text processing, or in creating simple user interfaces.

Consider the following Java code snippet that checks if a character entered by the user is a vowel or not:

  • Java

Java

import java.util.Scanner;

public class VowelChecker {

   public static void main(String[] args) {

       Scanner scanner = new Scanner(System.in);

       System.out.print("Enter a character: ");

       char inputChar = scanner.next().charAt(0);

       switch (inputChar) {

           case 'a':

           case 'e':

           case 'i':

           case 'o':

           case 'u':

           case 'A':

           case 'E':

           case 'I':

           case 'O':

           case 'U':

               System.out.println(inputChar + " is a vowel.");

               break;

           default:

               System.out.println(inputChar + " is not a vowel.");

               break;

       }

       scanner.close();

   }

}

Output

Enter a character: r
r is not a vowel.


This example demonstrates how a char can be read from the user, and how the program can use this character in a switch-case statement to perform specific actions based on the character's value.

Frequently Asked Questions

Why are primitive types important in Java?

Primitive types are the backbone of Java programming because they are the most basic form of data. They are efficient and fast, as operations on these types are directly handled by the CPU.

Can I use int instead of byte or short to save programming effort?

While you can use int for most scenarios due to its wide range, using byte or short can save memory, which is crucial in memory-sensitive applications like embedded systems.

How does Java handle numerical overflow in primitive types?

Java does not throw an exception for numerical overflow. Instead, it wraps around according to the maximum or minimum value the type can hold. For example, if you increment a byte valued 127 (its maximum), it wraps around to -128.

Conclusion

In this article, we have learned about the various primitive data types in Java, including boolean, byte, short, int, long, float, double, and char. Each of these types serves specific needs in Java programming, from handling simple true/false conditions with boolean to storing large numbers with long and handling decimal numbers with float and double. The char type's ability to store Unicode characters using 2 bytes allows Java programs to handle a diverse range of human languages. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Previous article
Preparedstatement Java
Next article
Optional Class in Java 8
Live masterclass