Variables & Data Types
java variables data types primitive int double boolean char long float byte short string var type inference widening conversion
Introduction
Every application works with data.
A banking system stores account balances.
An e-commerce website stores product prices.
A school management system stores student information.
A social media application stores usernames, posts, and comments.
But where does Java store all this information while a program is running?
The answer is variables.
A variable is a named memory location that stores data. Every variable has a data type, which tells Java what kind of data it can store and how much memory should be allocated.
Choosing the correct data type improves:
- Performance
- Memory usage
- Code readability
- Program reliability
In this lesson, you'll learn how variables work, how Java stores different kinds of data, and how to choose the right data type for real-world applications.
What is a Variable?
A variable is a named container that holds a value.
Think of a variable as a labeled storage box.
For example:
Name → RahulAge → 25Salary → 50000
Here:
NameAgeSalary
are variables.
Their values can change while the program is running.
Declaring a Variable
Before using a variable, Java requires you to declare it.
Syntax:
dataType variableName;
Example:
int age;
Here:
intis the data type.ageis the variable name.
At this point, the variable exists but has not been assigned a value.
Initializing a Variable
Initialization means assigning a value to a variable.
Example:
int age = 25;
Now:
- Data Type →
int - Variable Name →
age - Value →
25
Declaring Multiple Variables
You can declare multiple variables of the same type in one statement.
int width = 10, height = 20, length = 30;
Although valid, avoid declaring too many variables on one line if it reduces readability.
Variable Naming Rules
A variable name:
- Can contain letters, digits,
_, and$ - Cannot begin with a number
- Cannot contain spaces
- Cannot use Java keywords
- Is case-sensitive
Valid:
studentNameemployeeIdtotalMarks
Invalid:
2namestudent nameclass
Java Data Types
Java data types are divided into two main categories.
Data Types├── Primitive└── Non-Primitive
Let's understand both.
Primitive Data Types
Primitive data types store simple values directly.
Java provides 8 primitive data types.
| Data Type | Size | Example | Default Value* |
|---|---|---|---|
byte | 1 byte | 100 | 0 |
short | 2 bytes | 2000 | 0 |
int | 4 bytes | 50000 | 0 |
long | 8 bytes | 9000000000L | 0L |
float | 4 bytes | 12.5F | 0.0f |
double | 8 bytes | 99.99 | 0.0d |
char | 2 bytes | 'A' | '\u0000' |
boolean | JVM-dependent | true | false |
*These default values apply to instance and static fields, not local variables.
Integer Types
byte
Range:
-128 to 127
Example:
byte age = 25;
Useful when memory is limited.
short
Example:
short year = 2026;
Less commonly used in everyday applications.
int
The most commonly used integer type.
Example:
int salary = 75000;
Use int unless you have a specific reason to choose another integer type.
long
Used for very large numbers.
Example:
long population = 1400000000L;
Notice the L suffix.
Without it, Java treats the number as an int.
Floating-Point Types
float
Example:
float temperature = 36.5F;
The F suffix is required.
double
More precise than float.
Example:
double price = 1999.99;
Most Java applications use double for decimal values unless a different precision requirement exists.
Note: For financial calculations involving currency, double can introduce rounding errors because of binary floating-point representation. Professional applications often use BigDecimal for precise monetary calculations. You'll learn about this later in the course.
Character Type
A char stores a single Unicode character.
Example:
char grade = 'A';
Notice: Characters use single quotes.
Boolean Type
A boolean stores only two values:
truefalse
Example:
boolean isLoggedIn = true;
Booleans are commonly used in decision-making.
Non-Primitive Data Types
Non-primitive data types store references to objects.
Examples include:
- String
- Arrays
- Classes
- Interfaces
- Enums
- Records
- Collections
Example:
String name = "Rahul";
Unlike primitive types, String is an object.
Primitive vs Non-Primitive
| Primitive | Non-Primitive |
|---|---|
| Stores value directly | Stores a reference to an object |
| Fixed size | Size depends on the object |
| Lowercase keywords | Usually class names (PascalCase) |
| Faster for simple values | Can provide methods and behavior |
Type Inference with `var`
Starting with Java 10, you can use var for local variables.
Example:
var name = "Rahul";var age = 25;
The compiler infers the type.
Equivalent to:
String name = "Rahul";int age = 25;
When to Use `var`
Use var when the type is obvious and improves readability.
Avoid it if it makes the code harder to understand.
Variable Assignment
Variables can change.
Example:
int score = 80;score = 90;System.out.println(score);
Output:
90
The old value is replaced by the new one.
Real-World Example
Imagine an employee management system.
String employeeName = "Rahul";int employeeId = 101;double salary = 65000.50;boolean active = true;
Each variable stores a different type of information.
Choosing the correct data type makes the application efficient and easier to understand.
Memory Representation
When you write:
int age = 25;
Conceptually:
Variableage↓Value25
For a reference type:
String name = "Rahul";
Conceptually:
Reference Variablename↓String Object"Rahul"
The reference points to the object rather than storing the object itself.
Type Conversion
Java can automatically convert smaller numeric types to larger ones.
Example:
int age = 25;double value = age;
Output:
25.0
This is called widening conversion.
Converting larger types to smaller ones requires explicit casting, which you'll learn in a later lesson.
Best Practices
Choose the Correct Data Type
Use the smallest appropriate type only when it genuinely improves your design.
In most applications:
intis the standard integer type.doubleis commonly used for decimal values.booleanis used for conditions.Stringstores text.
Use Meaningful Variable Names
Bad:
int x;
Better:
int employeeAge;
Descriptive names improve readability.
Initialize Variables Before Use
Local variables must be assigned a value before they are read.
Example:
int total;total = 100;
Use Constants for Fixed Values
If a value never changes, use a constant instead of a regular variable.
You'll learn constants in an upcoming lesson.
Avoid Overusing `var`
var is convenient, but clarity should always come first.
If the inferred type isn't obvious, declare the type explicitly.
Common Mistakes
Forgetting the L Suffix
Incorrect:
long population = 1400000000;
If the literal exceeds the int range, append L:
long population = 5000000000L;
Forgetting the F Suffix
Incorrect:
float price = 12.5;
Correct:
float price = 12.5F;
Using Double Quotes for Characters
Incorrect:
char grade = "A";
Correct:
char grade = 'A';
Using Variables Before Initialization
int total;System.out.println(total);
Local variables must be initialized before use.
Choosing the Wrong Data Type
Using double for financial calculations can lead to precision issues.
For money, prefer dedicated types such as BigDecimal in professional applications.
Hands-on Exercise
Create a Java program that:
- Declares variables for:
- Student name
- Student age
- Student ID
- Percentage
- Grade
- IsPassed
- Prints all values.
- Updates the percentage and prints the new value.
- Uses
varfor a local variable where appropriate. - Demonstrates automatic widening conversion from
inttodouble.
Try completing the exercise without copying the examples directly.
Summary
Variables allow Java programs to store and manipulate data during execution.
Primitive data types store simple values directly, while non-primitive types store references to objects.
Choosing appropriate data types, following naming conventions, and writing readable code are essential habits for every Java developer.
As you continue learning Java, variables and data types will form the foundation for classes, methods, collections, databases, and enterprise applications.
Key Takeaways
- Variables store data in memory.
- Every variable must have a data type.
- Java provides eight primitive data types.
- Non-primitive types include
String, arrays, classes, and more. - Use meaningful variable names.
- Initialize local variables before using them.
- Use
varthoughtfully for local variables when it improves readability. - Select data types based on the nature of the data, not habit.
Professional Interview Questions
1What is the difference between primitive and non-primitive data types?
Professional Answer
Primitive data types store values directly and have a fixed size. Non-primitive data types store references to objects and can contain both data and methods. Examples of primitive types include int and boolean, while String and arrays are non-primitive types.
Follow-up Questions
- Why is String not a primitive type?
- Where are primitive values and object references stored?
Interview Tip: Explain both the storage concept and provide examples to demonstrate a complete understanding.
2What is the difference between float and double?
Professional Answer
Both represent floating-point numbers, but double provides greater precision and is the default choice for decimal values in Java. float uses less memory but requires the F suffix when assigning literals.
Follow-up Questions
- Why does float require the F suffix?
- When would you choose float instead of double?
Interview Tip: Mention that financial calculations often use BigDecimal instead of either type to avoid precision issues.
3What is var in Java?
Professional Answer
var enables local variable type inference. The compiler determines the variable's type based on the assigned value. It can only be used for local variables that are initialized during declaration.
Follow-up Questions
- Can var be used for fields?
- Can var be initialized with null?
Interview Tip: Emphasize that var does not make Java dynamically typed—the inferred type is fixed at compile time.