You all know that variables can store different values, and every value has its type, such as a number, text, or a true/false value. This type is referred to as a data type.
In Java, data types tell the computer what type of information a variable will store.
Imagine variables are containers and data types like labels on those containers. If the label is “water”, then it will contain water, not rice. Similarly, if a variable’s type is int, it will only store whole numbers.
Why we use data types in Java?
We use data types for different purposes, like:
- Memory efficiency: It’s used for memory efficiency, so the computer can easily know exactly how much memory to reserve. For example, A small number uses less memory than a long text.
- Error prevention: Java will stop you if you try to store text in a number variable.
- Faster execution: It will do the fast execution because the computer doesn’t have to guess the type of data.
Types of Data Types in Java
Java data types are categorized into two types, such as:
- Primitive Data Types
- Non-Primitive Data Types
1. Primitive Data Types
These data types store only simple values like numbers, letters, or true/false. They are predefined in Java, which means Java already has built-in keywords for these data types; you don’t need to write code to define what an int, double, or char is.
Java has 8 primitive data types, and all those have different sizes. Read the following table carefully.
Data Type | Size | Values |
---|---|---|
byte | 1 byte | It has small whole numbers (-128 to 127). |
short | 2 bytes | It has big whole numbers (-32,768 to 32,767). |
int | 4 bytes | Stores integers from -2^31 to 2^31-1. |
long | 8 bytes | very large whole numbers -2^63 to 2^63-1. |
float | 4 bytes | decimal numbers (7 decimal digits). |
double | 8 bytes | decimal numbers (15 decimal digits). |
char | 2 bytes | Stores a single character using Unicode like ‘A’ or ‘$’ |
boolean | 1 bit | Stores Boolean values (True/False) |
Example of Primitive Data Types
Learn this code carefully, and also read the comments so you can understand each line.
Example code:
public class PrimitiveExample {
public static void main(String[] args) {
int age = 21; // directly stores the number 21
double price = 99.5; // directly stores decimal value
char grade = 'A'; // directly stores single character
boolean isStudent = true; // directly stores true/false
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Grade: " + grade);
System.out.println("Is Student? " + isStudent);
}
}
Output:
Age: 21
Price: 99.5
Grade: A
Is Student? true
- In this code, each variable holds the actual value itself, not a reference to another location.
2. Non-Primitive Data Types
These are the more advanced data types that are used for object-oriented features. They don’t store the value directly; first, they store the address of the data in memory.
It is also called reference types that store references (memory addresses) of objects, not the actual value.
Examples of Non-Primitive Data Types
- String
- Array
- Class
- Interface
Example: Using a String and an Array:
public class NonPrimitiveExample {
public static void main(String[] args) {
String name = "Peter"; // stores reference to the String object
int[] marks = {85, 90, 88}; // stores reference to an array object
System.out.println("Name: " + name);
System.out.println("Uppercase Name: " + name.toUpperCase()); // calling method
System.out.print("Marks: ");
for (int m : marks) {
System.out.print(m + " "); // accessing data from array object
}
}
}
Output:
Name: Peter
Uppercase Name: PETER
Marks: 85 90 88
- In this code, name does not hold “Peter” directly, but it holds a reference pointing to where the string is stored in memory.
Type Casting in Java
In Java, type casting means changing the data type of a value into another data type.
Imagine, it’s like pouring water from one container into another. Sometimes it fits perfectly, and sometimes you have to be careful not to spill.
When we convert a value into a different data type like int to float ( 10 to 10.0), we don’t lose the data, because it’s a compatible type casting.
But, when we convert into incompatible or smaller data types like float to int (10.75 to 10), the decimal part is removed (losing the data).
There are two types of Type Casting:
- Implicit Casting
- Explicit Casting
1. Implicit Casting
- This casting happens automatically when you store a smaller data type into a larger data type.
- No data is lost because the bigger type can easily hold the smaller value.
- It’s called a widening because the container gets “wider”.
For example:
public class ImplicitCastingExample {
public static void main(String[] args) {
int num = 100; // small type: int
double result = num; // big type: double
System.out.println("Result: " + result);
}
}
Output:
Result: 100.0
In this code, an int (whole number) is stored in a double (decimal number). Java does it automatically by adding .0 to make it a decimal.
2. Explicit Casting (Narrowing Conversion)
- In this type, you manually tell Java to convert a larger data type into a smaller one.
- This can lose the data if the value doesn’t fit in the smaller container.
- It’s called a narrowing because the container gets “narrower”.
For example:
public class ExplicitCastingExample {
public static void main(String[] args) {
double price = 99.99; // big type: double
int discountedPrice = (int) price; // small type: int
System.out.println("Discounted Price: " + discountedPrice);
}
}
Output:
Discounted Price: 99
In this code, (int) tells Java to cut off the decimal part and keep only the whole number.
What is The Wrapper Classes in Java?
Primitive data types like int, char, and Boolean are not object, they are just raw values. But sometimes, Java needs everything to behave like an object.
For example, working with collections like ArrayList or using certain APIs.
Primitive data types can be converted to objects using wrapper classes, like the following table:
Primitive Type | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
For example:
public class WrapperExample {
public static void main(String[] args) {
int num = 10; // Primitive
// Wrapping (Boxing)
Integer wrappedNum = Integer.valueOf(num);
System.out.println("Primitive value: " + num);
System.out.println("Wrapped object: " + wrappedNum);
}
}
Output:
Primitive value: 10
Wrapped object: 10
Explanation of this code:
- int num = 10; Creates a primitive int.
- Integer wrappedNum = Integer.valueOf(num); manually converting the primitive “int” into wrapper class “Integer”. This process is called Boxing or Wrapping.
- Printing wrappedNum still shows 10, but now it’s stored inside an object.
Why Do We Need Wrapper Classes?
There are the few reasons available that we need this classes:
- Collections – ArrayList<int> is not allowed, but ArrayList<Integer> is allowed.
- Null values – Objects can be null values, but primitives type can’t be null.
- Utility methods – Wrapper classes have built-in methods (like parsing strings to numbers).
Exercise For Students:
Suppose your friend gave you a box that can only hold whole apples (integers), but you have a bag with cut apple pieces (decimals).
Write a program that can do the following terms:
- Stores the number of apple pieces (as a decimal) you have.
- Converts it into the number of whole apples you can put in the box.
- Prints both the original decimal number and the converted whole number.
Example Output:
You have 4.75 apple pieces.
You can put 4 whole apples in the box.
Code: Apple Box Example (Type Casting)
// Apple Box Program - Simple Type Casting Example
// Written for students in a relatable way
public class AppleBox {
public static void main(String[] args) {
// Step 1: Bag me kitne apple pieces hai (decimal me)
double applePieces = 4.75;
// Step 2: Box me sirf whole apples fit hote hain
int wholeApples = (int) applePieces; // Explicit casting
// Step 3: Output dikhana
System.out.println("You have " + applePieces + " apple pieces.");
System.out.println("You can put " + wholeApples + " whole apples in the box.");
}
}
Try to understand this code by yourself and write your logic.