Java Primitive data Types


In Java, data types are divided into two groups.
primitive data types
None - primitive data types
Before we learn about data types, let's understand how to declare a variable in Java. This will help you see why we need data types.
How to declare a variable in java
A primitive data type specifies the type of a variable and the kind of values it can hold. as an example we can write a simple integer like below
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int number = 100;
}
}
In the code above, number
is the variable. Before writing the variable, we must declare the type of data it stores. For example, I used int
. The value is assigned using the =
symbol.
few examples
int number = 100;
boolean open = false;
double number=100.50;
Summary of Primitive Data Types
Data Type | Description | Example |
byte | stores whole numbers from -128 to +127 | byte number = 100; |
short | stores whole numbers from -32768 to 32767 | short number = 32000; |
int | store whole numbers from -9 223 372 036 854 775 808 to -9 223 372 036 854 775 807 | int number =1000; |
float | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits (if you are adding decimal you have to put f end of the number) | float number = 25.63f; |
double | Stores fractional numbers. Sufficient for storing 15 to 16 decimal digits | double number = 25.63; |
boolean | store true or false values | boolean open = false; |
char | Stores a single character/letter or ASCII values | double letter = 'A'; |
Use cases of each Primitive Data Type
byte
The byte
data type in Java is an 8-bit signed integer that stores values from -128 to 127. It is mainly used in situations where memory efficiency is important, as it consumes only 1 byte (8 bits) of storage compared to larger data types like int
(4 bytes) or long
(8 bytes).
One of the primary use cases of byte
is in memory-sensitive applications, such as large arrays, IoT devices, and embedded systems, where minimizing memory usage is crucial. It is also commonly used in file handling and networking, as Java’s InputStream
and OutputStream
classes work with byte
arrays to efficiently read and write binary data (e.g., images, audio files, and network packets).
Another important use case is in cryptography and data compression, where encryption algorithms process data in bytes. Additionally, byte
is widely used in serial communication, such as sending commands to microcontrollers like Arduino and Raspberry Pi, making it essential in robotics and hardware programming.
Something to watch out for when using byte
public class Main {
public static void main(String[] args) {
byte a = 120; // Close to max limit
byte b = 10; // A small number
byte result = (byte) (a + b); // Overflow occurs here silently
System.out.println("Result: " + result); // Unexpected negative number -126
}
}
/Result of : 120 +10 = -126 (!! Important Note)
In above program, we have two
byte
variables:a = 120
andb = 10
. When we add them (a + b
), the sum is130
, which exceeds the maximum limit of a byte (127). Since Java stores bytes using two's complement representation, the value wraps around and results in-126
instead of130
. This happens silently because Java does not give an error when abyte
overflows; it just adjusts the value within the valid range.
short
The short
data type in Java is a 16-bit signed integer with a range from -32,768 to 32,767. It is used when memory optimization is needed, such as in large arrays or embedded systems, where using an int
(which takes 4 bytes) would be unnecessary. However, in most modern applications, int
is preferred because processors handle 32-bit integers more efficiently. While short
can save memory also the short
data type is commonly used in scenarios where memory efficiency is important, but the range of values required exceeds that of a byte
.
Popular Use Cases of short
in Java
Memory Optimization in Large Arrays
In applications that handle large datasets like images, sensor readings, or big data processing,short
helps save memory compared toint
. as an example, grayscale images store pixel values between 0 and 32,767, makingshort
an ideal choice.Embedded Systems & IoT Devices
Devices like microcontrollers, smart sensors, and IoT gadgets often have limited memory. Usingshort
for temperature readings, sensor data, or device IDs helps optimize performance while reducing memory usage.Audio & Game Development
Many audio processing systems store sound samples inshort
because 16-bit audio is a common format. In game development,short
is used for storing coordinates, physics calculations, and object IDs, especially on mobile devices where performance matters.
Example of Silent Overflow in Arithmetic
public class ShortSilentOverflow {
public static void main(String[] args) {
short a = 30_000;
short b = 10_000;
short result = (short) (a + b); // Overflow happens here silently
System.out.println("Result: " + result); // Unexpected negative value
}
}
Result: -25536
When adding
30,000
and10,000
in ashort
data type, the result exceeds the maximum limit of32,767
. Sinceshort
can only store values between-32,768
and32,767
, an overflow occurs. In Java, when overflow happens, the extra value wraps around from the negative range. Internally, the sum40,000
gets converted into its 16-bit equivalent, which results in-25,536
. This happens because Java follows two’s complement representation, where numbers beyond the maximum limit roll over into the negative range, causing unexpected results.
int
The int
(integer) data type in Java is a 32-bit signed data type that stores whole numbers. It has a value range from -2,147,483,648 to 2,147,483,647. It is the most commonly used data type for numeric operations, as it provides a good balance between memory efficiency and numerical range.
Use cases of int
1. Counting and Looping
The int
data type is commonly used for counting elements and controlling loops in programming. as an example, in web applications, it tracks the number of users, page visits, or product stock in an inventory system. In loops, int
helps iterate over arrays, lists, or database records efficiently.
2. Financial and Business Calculations
Businesses use int
for handling calculations like revenue, expenses, and product prices when decimals are not required. For example, e-commerce platforms store product quantities and track order numbers using int
, ensuring fast and accurate computations. Banking applications also use int
for storing customer account numbers and transaction counts.
3. Date and Time Handling
Many applications use int
to store time-related values. For instance, timestamps are often stored as the number of seconds or milliseconds since a fixed date (Epoch time). This is useful in logging events, scheduling tasks, and tracking the duration of user activity in mobile apps and websites.
Real-World Scenarios of Integer Overflow
Banking & Financial Systems
If an account balance is stored as anint
and grows beyond2,147,483,647
, an overflow can result in a negative balance, causing major financial errors.Gaming Score Calculation
In video games, player scores are often stored asint
. If a player earns too many points, an overflow could cause their score to reset to a negative value or zero.Time and Date Calculations
Some systems store time in seconds or milliseconds usingint
. If a system runs long enough, it might exceed the max value, leading to incorrect timestamps or system crashes.
Example - The Year 2038 bug for 32-bit systems.
The Year 2038 Problem is a potential issue in computer systems that use 32-bit signed integers to store time. Many operating systems and applications represent time as the number of seconds elapsed since January 1, 1970 (Unix Epoch Time). This is commonly stored as a 32-bit int
.
Why Does the Problem Happen?
A 32-bit signed integer can store values from -2,147,483,648 to 2,147,483,647. In the context of time
January 1, 1970, 00:00:00 UTC → 0 seconds
January 19, 2038, 03:14:07 UTC → 2,147,483,647 seconds (Max
int
value)January 19, 2038, 03:14:08 UTC → -2,147,483,648 seconds (Overflow occurs, wraps to a negative number)
Once the time reaches January 19, 2038, at 03:14:07 UTC, adding one more second causes an integer overflow, making the time jump back to December 13, 1901, breaking time-dependent applications
float
A float
in Java is a 32-bit floating-point data type used for storing decimal numbers with approximately 6-7 digits of precision. It is based on the IEEE 754 standard and is suitable for applications where memory efficiency is more important than high precision. Since Java treats decimal numbers as double
by default, a float value must be explicitly defined using the f
or F
suffix (e.g., float num = 3.14f;
). Commonly used in graphics, scientific calculations, and embedded systems, float
is ideal for handling approximate values but may introduce small rounding errors due to its limited precision.
Use cases of float
Real-World Use Cases of float
in Java
Game Development & Graphics Rendering
In video games and animations,float
is used to store positions, speed, rotation, and physics calculations because these values often include decimals and need to be updated frequently.float
is preferred overdouble
in gaming engines because it consumes less memory (4 bytes instead of 8 bytes), making rendering faster and improving performance.example - In a racing game, a car's position and velocity are stored as
float
to allow smooth motion without excessive memory usage.float carSpeed = 78.5f; // Car speed in km/h float playerX = 320.45f; // Player's X-coordinate on screen
GPS & Sensor Data Processing
Devices like smartphones, fitness trackers, and IoT sensors usefloat
to store real-world values such as latitude, longitude, altitude, and temperature. Since sensor data doesn’t require high precision like scientific calculations, usingfloat
instead ofdouble
helps save memory and improve processing speed.example - a weather sensor records temperature as a
float
since precise decimal values beyond a certain point are unnecessary.float latitude = 40.7128f; // GPS latitude float longitude = -74.0060f; // GPS longitude float temperature = 25.4f; // Temperature in Celsius
Scientific & Engineering Calculations
In scientific applications like weather forecasting, physics simulations, and robotics,float
is used for calculations that require moderate precision but high computational efficiency. In these fields, exact precision isn't always necessary, but fast processing and reduced memory usage are crucial.example - A robotic arm’s movement angles or a wave frequency in sound processing can be stored as
float
, ensuring accurate yet efficient computation.float robotArmAngle = 45.75f; // Angle of a robotic arm float soundFrequency = 440.12f; // Frequency in Hz for audio processing
Why Use float
Instead of double
?
float
uses less memory (4 bytes vs. 8 bytes fordouble
), making it ideal for memory-constrained environments.It provides faster calculations, making it suitable for gaming, mobile apps, and real-time systems.
It’s sufficiently accurate for applications that don’t require extreme precision.
float overflow scenarios
Sensor Data in High-Precision Equipment
Some scientific instruments record very high values (e.g., radiation levels, electrical signals). If a float
is used and the value gets too high, it can overflow.
💡 Example:
javaCopyEditfloat radiationLevel = 3.0e38f; // Near max float value
radiationLevel *= 5; // Overflow occurs
System.out.println("Radiation Level: " + radiationLevel); // Prints "Infinity"
👉Why? The multiplication pushes the value beyond float's maximum range, leading to an overflow issue.
double
In Java, double
is a data type used to store decimal numbers with high precision. It is a 64-bit floating-point type, meaning it can handle very large and very small numbers accurately. Unlike float
, which holds about 6–7 decimal places, double
can store up to 15–17 decimal places, making it ideal for scientific calculations, financial applications, and 3D graphics. Since double
provides more precision, it is the default choice for decimal values in Java.
Real-World Use Cases of double
in Java
1. Financial Calculations (Banking & Stock Markets) 💰
Banks and stock markets require precise decimal calculations for interest rates, stock prices, and currency exchange rates. Since double
provides higher precision than float, it helps avoid rounding errors in complex financial transactions.
💡 Example:
javaCopyEditdouble interestRate = 4.75; // Interest rate in percentage
double principal = 10000.50; // Loan amount
double interest = (principal * interestRate) / 100;
System.out.println("Interest: $" + interest);
👉 Output:
bashCopyEditInterest: $475.02375
✅ Ensures accurate financial calculations.
Mathematical Overflow of double
(Exceeding Max Value)
If you try to assign a number greater than Double.MAX_VALUE
, it results in positive infinity (Infinity
).
💡 Example:
javaCopyEditpublic class DoubleOverflowExample {
public static void main(String[] args) {
double maxValue = Double.MAX_VALUE;
System.out.println("Max Double Value: " + maxValue);
double overflowedValue = maxValue * 2; // Exceeds max limit
System.out.println("Overflowed Value: " + overflowedValue);
}
}
👉 Output:
yamlCopyEditMax Double Value: 1.7976931348623157E308
Overflowed Value: Infinity
✅ Java prevents crashes by returning Infinity
instead of throwing an error.
boolean
The boolean
data type in Java is used to store true or false values. It is commonly used for decision-making and logical operations. Since it only takes 1 bit of memory, it is the simplest data type in Java.
The boolean data type in Java cannot overflow because it only has two possible values: true
(1) and false
(0). Unlike numeric data types (int
, float
, double
), booleans do not have a range of values that can exceed a limit. If you try to increment or overflow a boolean, Java will not allow it and will throw a compilation error.
Example: Invalid Boolean Overflow
javaCopyEditpublic class BooleanOverflowExample {
public static void main(String[] args) {
boolean flag = true;
// This will cause a compilation error
flag++;
System.out.println(flag);
}
}
Error Output:
vbnetCopyEditError: bad operand types for unary operator '++'
🔹 Why?
Booleans are not numbers, so you cannot increment, decrement, or perform arithmetic operations on them. They are strictly used for true/false logic operations.
char
In Java, the char
data type is used to store a single character. It is a 16-bit data type (2 bytes) that follows the Unicode standard, allowing it to store characters from multiple languages, symbols, and special characters.
Unlike languages like C or C++, where char
is 1 byte and based on ASCII, Java’s char
uses Unicode (UTF-16), making it capable of representing over 65,000 different characters.
Key Features of char
1. Stores a single character.
2. Uses Unicode (UTF-16) for international support.
3. Takes 2 bytes of memory.
4. Enclosed in single quotes ('A'
).
Real-World Use Cases of char
in Java
Representing Gender, Status, or Short Codes in Databases
In databases, char
is used to store short codes like gender ('M'
or 'F'
), marital status ('S'
, 'M'
), or grades ('A'
, 'B'
, 'C'
). This saves space compared to using full words.
📌 Example: Storing Gender in a System
javaCopyEditpublic class CharDatabaseExample {
public static void main(String[] args) {
char gender = 'M'; // 'M' for Male, 'F' for Female
System.out.println("Gender: " + gender);
}
}
🔹 Used in: Databases for schools, hospitals, and government records.
You can store numbers in char
, but they are interpreted as Unicode characters. why is this mean ?
In Java, when you store a number in a char
, it is not treated as a regular number but as a Unicode character that corresponds to that number. Unicode is a system that assigns a unique number to every character (like letters, symbols, and digits).
For example:
public class CharExample {
public static void main(String[] args) {
char letter = 65; // 65 is the Unicode value for 'A'
System.out.println(letter); // Output: A
}
}
Here, 65
is stored in char
, but instead of printing 65
, it prints 'A' because 65 in Unicode represents 'A'.
This means that char
stores numbers, but when printed, it shows the corresponding character from the Unicode table.
The maximum number that can be assigned to a char
in Java is 65,535 because char
is a 16-bit unsigned data type (it does not support negative values). It follows the Unicode standard, which can represent characters from 0
to 65,535
.
more comprehensive explanation - https://www.smashingmagazine.com/2012/06/all-about-unicode-utf8-character-sets/
Subscribe to my newsletter
Read articles from Lahiru Shiran directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
