- What is a Variable?
- Real-life Example:
- Key Points:
- How to Declare a Variable in Java?
- What are Data Types?
- Key Characteristics of Data Types:
- 1. Strongly Typed Language
- 2. Compile-Time Type Checking
- 3. Memory Efficient
- Categories of Data Types in Java
- 1️⃣ Primitive Data Types
- Types of Primitive Data Types
- Java Program Primitive Data Type Example: Using int and char
- Output:
- Explanation:
- 2️⃣ Non-Primitive (Reference) Data Types
- Types of Non-Primitive Data Types
- Example 1: String (Non-Primitive Type)
- Behind the Scenes:
- Example 2: Arrays (Non-Primitive Type)
- More Array Operations:
- Example 3: Classes and Objects
- Example 4: Interfaces
- Differences Between Primitive and Non-Primitive
- Important Notes
- Variable Naming Rules in Java
- Variable Types Based on Scope
- Example with Multiple Data Types
- Why Choosing the Right Data Type Matters?
- Java is a Strongly Typed Language
- What is Type Casting?
- Practice Set for Students
- Q1: Write a Java program to declare variables of all primitive data types and print them.
- Q2: Create a program where:
- Q3: Write a Java program that uses type casting to convert:
- Summary
“Before we build a program, we need to know how to store and use data. That’s exactly what Data Types and Variables help us do in Java!”
What is a Variable?
A variable in Java is like a container that holds data during the execution of a program.
Real-life Example:
Imagine you have a cup and you pour water into it. Here:
- The cup is the variable
- The water is the data
- The type of cup (small/large) is the data type
Key Points:
- Every variable must have a name (called an identifier)
- Every variable must be declared with a type
- Variables can store, update, and retrieve values
How to Declare a Variable in Java?
int age; // declaration
age = 25; // initialization
You can also do both at once:
int age = 25; // declaration + initialization
What are Data Types?
Data types define the type of data a variable can store, such as numbers, characters, or true/false values. In Java, they are strongly typed, which means every variable must be declared with a specific type before use.
Key Characteristics of Data Types:
1. Strongly Typed Language
- Java does not allow a variable to hold multiple types of values.Once a variable is declared as a type (e.g.,
int,char), it can only store values of that type.
int number = 10; // valid
number = "Ten"; // ❌ error: incompatible types
2. Compile-Time Type Checking
The Java compiler checks data types at compile time to reduce errors.
3. Memory Efficient
Each data type has a fixed size in memory, which helps in efficient resource usage.
Categories of Data Types in Java
Java has two main types of data types:
| Category | Data Types | Example |
|---|---|---|
| 1. Primitive | byte, short, int, long, float, double, char, boolean | int x = 5; |
| 2. Non-Primitive | String, Arrays, Classes, Interfaces | String name = "John"; |
1️⃣ Primitive Data Types
These are predefined by the language. They store simple values.
Types of Primitive Data Types
| Data Type | Description | Size | Example |
|---|---|---|---|
byte | Integer (very small) | 1 byte | byte a = 100; |
short | Integer (small) | 2 bytes | short b = 20000; |
int | Integer (default) | 4 bytes | int age = 25; |
long | Big Integer | 8 bytes | long stars = 123456789L; |
float | Decimal (less precise) | 4 bytes | float pi = 3.14f; |
double | Decimal (more precise) | 8 bytes | double e = 2.71828; |
char | Single character | 2 bytes | char grade = 'A'; |
boolean | True or False | 1 bit | boolean isJavaFun = true; |
Java Program Primitive Data Type Example: Using int and char
public class PrimitiveDataTypesExample {
public static void main(String[] args) {
// int: to store age
int age = 25;
// char: to store grade
char grade = 'A';
// Display the values
System.out.println("Student Age: " + age);
System.out.println("Student Grade: " + grade);
}
}
Output:
Student Age: 25
Student Grade: A
Explanation:
int age = 25;→ Stores the whole number 25.char grade = 'A';→ Stores the character ‘A’.System.out.println(...)is used to print the values to the console.
2️⃣ Non-Primitive (Reference) Data Types
In Java, Non-Primitive Data Types (also called Reference Data Types) are used to store more complex data than primitive types like int, char, or boolean.
Unlike primitive types which store simple values directly, reference types store addresses (references) that point to objects in memory.
Types of Non-Primitive Data Types
Java provides many non-primitive types, but here are the most commonly used ones:
| Data Type | Description |
|---|---|
String | Sequence of characters (text) |
Array | Collection of similar elements |
Class | Blueprint for creating objects |
Interface | Contract for classes to follow |
Enum | Set of named constants |
Object | Base type for all Java classes |
Example 1: String (Non-Primitive Type)
A String is a sequence of characters used to represent text.
String name = "Prakash";
System.out.println(name); // Output: Prakash
Explanation:
"Prakash"is stored in memory as a String object.nameholds the reference to that memory location.
Behind the Scenes:
Internally, Java treats a String as a class (i.e., an object with methods).
You can use:
System.out.println(name.length()); // Get the length of the string
System.out.println(name.toUpperCase()); // Convert to uppercase
Example 2: Arrays (Non-Primitive Type)
An array is a collection of fixed-size similar elements (same data type), stored in contiguous memory.
int[] numbers = {1, 2, 3, 4};
System.out.println(numbers[0]); // Output: 1
Explanation:
- The array holds 4
intvalues. numbersis a reference that points to the memory location of the array.- You can access elements using indexes:
numbers[0],numbers[1], etc.
More Array Operations:
System.out.println(numbers.length); // Output: 4
System.out.println(numbers[2]); // Output: 3
Example 3: Classes and Objects
A class is a blueprint. An object is an instance of a class. Classes are user-defined non-primitive data types.
class Student {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // s1 is a reference variable
s1.name = "Ravi";
s1.age = 20;
System.out.println(s1.name + " is " + s1.age + " years old.");
}
}
Explanation:
Studentis a class (non-primitive type).s1is a variable that refers to aStudentobject in memory.
Example 4: Interfaces
An interface is like a contract that classes must follow. It doesn’t have actual code — only method declarations.
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof");
}
}
Explanation:
Animalis an interface (non-primitive type).Dogimplements the interface by providing the method body.
Differences Between Primitive and Non-Primitive
| Feature | Primitive Data Types | Non-Primitive Data Types |
|---|---|---|
| Stores | Actual value | Reference to object |
| Size | Fixed | Can vary (depends on object) |
| Can be null? | No | Yes |
| Includes methods? | No | Yes (e.g., String.length()) |
| Examples | int, char, boolean | String, Array, Class |
Important Notes
- Default values of non-primitive types (if not initialized) are
null. - You can use
.equals()to compare two non-primitive types like Strings. - Non-primitive types are stored on the heap and accessed via references.
Variable Naming Rules in Java
- Must start with a letter,
_or$ - Cannot start with a number
- Cannot use Java reserved keywords (e.g.,
int,class) - Case-sensitive (
Ageandageare different) - Should be meaningful (e.g., use
marksnotx)
✅ Good: studentAge, totalMarks, isEligible
🚫 Bad: 1age, total@marks, int
Variable Types Based on Scope
| Type | Defined inside | Accessible within |
|---|---|---|
| Local | Methods | That method only |
| Instance | Class | All methods (non-static) |
| Static/Class | Class | All static methods |
Example with Multiple Data Types
public class DataTypeExample {
public static void main(String[] args) {
int age = 24;
double weight = 72.5;
char grade = 'A';
boolean isPassed = true;
String name = "Ravi";
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
System.out.println("Grade: " + grade);
System.out.println("Passed: " + isPassed);
}
}
Output
Name: Ravi
Age: 24
Weight: 72.5
Grade: A
Passed: true
Why Choosing the Right Data Type Matters?
Choosing the correct data type:
- Optimizes memory
- Prevents errors
- Improves performance
Example:
If you just need to store a small number like 10, using int is better than long.
Java is a Strongly Typed Language
This means Java does not allow assigning a value of one type to another type without explicit conversion.
int x = 10;
double y = x; // valid (int → double is widening)
int z = y; // ❌ error (double → int needs casting)
What is Type Casting?
Widening Casting (automatically): smaller to larger data type
int a = 100;
double b = a; // OK
Narrowing Casting (manually): larger to smaller data type
double x = 123.45;
int y = (int) x; // need to cast
Practice Set for Students
Q1: Write a Java program to declare variables of all primitive data types and print them.
Q2: Create a program where:
- You declare
String name,int age,double percentage - Then print:
"My name is Ravi, I am 20 years old, and scored 85.5%"
Q3: Write a Java program that uses type casting to convert:
double value = 87.56intoint- Print both values before and after casting
Summary
✅ Variables in Java are containers to store data.
✅ Data types define what kind of data you can store.
✅ Java has primitive and non-primitive data types.
✅ Always declare variables before use with proper data type.
✅ Naming rules and scope should be followed carefully.