Java Variables, Data Types, Casting & Operators
Learn Java variables, data types, type casting, and operators with simple examples. Understand primitive types, casting, arithmetic, logical, and relational operators.

Introduction
Variables store values in Java.
Data types define what kind of value a variable can store.
Type casting converts a value from one data type to another.
Operators perform operations such as addition, subtraction, comparison, assignment, and logical evaluation.
For example:
int age = 25;
double salary = 50000.50;
double result = age + salary;
System.out.println(result);The important relationship is:
Variable
↓
Data Type
↓
Stored Value
↓
Operators
↓
ResultWhat Are Variables in Java?
A variable is a named location used to store a value.
You can think of a variable as a labeled container.
age → 25
name → "Java"
price → 99.99
isValid → trueIn Java, every variable has a data type.
For example:
int age = 25;
String name = "Java";
double price = 99.99;
boolean isValid = true;Here:
agestores an integer.namestores text.pricestores a decimal number.isValidstores a boolean value.
This strict relationship between variables and types is one reason Java can catch many programming mistakes before your application runs.
How to Declare a Variable in Java
The basic syntax is:
dataType variableName = value;For example:
int age = 25;There are three parts:
int age = 25
│ │ │
Type Name ValueYou can also declare a variable without assigning a value immediately:
int age;
age = 25;Both approaches are valid.
For local variables, however, Java requires you to assign a value before you try to use the variable.
Variable Initialization
Initialization means assigning the first value to a variable.
int score = 100;You can later change the value:
int score = 100;
score = 150;
System.out.println(score);Output:
150The variable remains an int. Only its stored value changes.
Java Variable Naming Rules
Java has specific rules for naming variables.
Valid:
int age;
int studentAge;
int student_age;
int age2;Invalid:
int 2age;
int student-age;
int class;A variable name:
Cannot start with a number.
Cannot contain spaces.
Cannot use Java keywords.
Is case-sensitive.
Can contain letters, digits,
_, and$.
Recommended Style
Use camelCase for variable names:
studentName
totalMarks
accountBalance
employeeSalaryAvoid unclear names such as:
x
abc
temp1
data123unless the context is obvious.
Good names make code easier to maintain.
What Are Data Types in Java?
A data type tells Java what kind of data a variable can hold.
Java data types are broadly divided into two categories:
Java Data Types
│
├── Primitive
│
└── Non-Primitive



byte
byte stores small integer values.
byte age = 25;Its range is:
-128 to 127It's useful when you're working with large amounts of raw binary or memory-sensitive data.
For normal integer calculations, int is usually the better choice.
short
short stores a 16-bit signed integer.
short temperature = 300;Its range is:
-32,768 to 32,767Like byte, it isn't commonly used for everyday calculations.
int
int is the most commonly used integer type in Java.
int age = 25;
int salary = 50000;Its range is:
-2,147,483,648
to
2,147,483,647For most whole-number calculations, start with int unless you have a reason to use another type.
long
long is used for larger integer values.
long population = 8000000000L;Notice the L at the end.
Without it, Java may treat the literal as an int and complain if the number is too large.
float
float stores single-precision decimal values.
float temperature = 36.5f;The f suffix tells Java that the literal is a float.
double
double stores double-precision floating-point values.
double price = 999.99;For general decimal calculations, double is commonly used.
For example:
double average = 85.75;char
char stores a single 16-bit Unicode character.
char grade = 'A';Notice the single quotes.
'A'is a char.
While:
"A"is a String.
That's an important distinction.
boolean
A boolean can contain only:
true
falseExample:
boolean isLoggedIn = true;
boolean hasPermission = false;Booleans are heavily used in conditions
if (isLoggedIn) {
System.out.println("Welcome!");
}Non-Primitive Data Types
Non-primitive types include things such as:
StringArrays
Classes
Interfaces
Enums
Objects
For example:
String name = "Java";String isn't one of Java's eight primitive types. It's a class provided by the Java platform.
We'll cover objects and classes in much more detail when we reach Java's object-oriented programming concepts.
What Is Type Casting in Java?
Type casting means converting a value from one data type to another.
For example:
int number = 10;
double value = number;Here, the int value is converted into a double.
There are two major forms:
Type Casting
│
├── Widening
│
└── NarrowingWidening Type Casting
Widening converts a smaller compatible numeric type into a larger one.
Java can usually perform this conversion automatically.
int number = 100;
double value = number;
System.out.println(value);Output:
100.0The conversion is:
int → doubleAnother common widening direction is:
byte → short → int → long → float → doubleFor example:
int number = 50;
long value = number;No explicit cast is necessary.
Narrowing Type Casting
Narrowing converts a larger type into a smaller compatible type.
This requires an explicit cast.
double price = 99.99;
int value = (int) price;
System.out.println(value);Output:
99The syntax is:
(targetType) valueIn this case:
(int) priceThe decimal portion is discarded.
It isn't rounded.
99.99 → 99Why Can Narrowing Be Dangerous?
Because information can be lost.
Consider:
int number = 130;
byte value = (byte) number;
System.out.println(value);byte can't represent 130, so the conversion doesn't preserve the original value.
This is why explicit casting deserves attention. Java allows the conversion because you've explicitly requested it, but that doesn't mean the result is mathematically equivalent.
What Are Operators in Java?
Operators are symbols that tell Java to perform an operation.
For example:
int result = 10 + 5;Here:
10is an operand.5is an operand.+is the operator.
Arithmetic Operators
Arithmetic operators perform mathematical calculations.
Example:
int a = 10;
int b = 3;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);Output:
13
7
30
3
1Watch Out for Integer Division
This surprises almost every Java beginner at least once:
int result = 5 / 2;
System.out.println(result);Output:
2Because both operands are integers.
If you need a decimal result:
double result = 5.0 / 2;
System.out.println(result);Output:
2.5Assignment Operators
Assignment operators assign or update values.
The basic assignment operator is:
=Example:
int score = 50;Example:
int score = 50;
score += 10;
System.out.println(score);Output:
60Relational Operators
Relational operators compare values.
They produce a boolean result:
true
falseExample:
int age = 20;
System.out.println(age >= 18);Output:
true= vs ==
Don't confuse these.
x = 10;means:
Assign 10 to x.
While:
x == 10;means:
Check whether x equals 10.
This distinction becomes critical when writing conditions.
Logical Operators
Logical operators combine boolean expressions.
Example:
int age = 25;
boolean hasId = true;
boolean allowed = age >= 18 && hasId;
System.out.println(allowed);Output:
trueWith &&, both conditions need to be true.
OR
boolean result = true || false;Result:
trueOnly one condition needs to be true.
NOT
boolean result = !true;Result:
falseIncrement and Decrement Operators
The increment operator:
++increases a value by one.
The decrement operator:
--decreases it by one.
Example:
int count = 5;
count++;
System.out.println(count);Output:
6And:
count--;changes it back to:
5You'll use these constantly when working with loops.
Prefix vs Postfix
There is a subtle difference between:
++xand:
x++For example:
int x = 5;
int a = ++x;First, x becomes 6, then a receives 6.
With:
int x = 5;
int a = x++;a receives 5, then x becomes 6.
This matters when the operator is used inside a larger expression.
Ternary Operator
The ternary operator is a compact way to choose between two values.
Syntax:
condition ? valueIfTrue : valueIfFalse;Example:
int age = 20;
String result = age >= 18 ? "Adult" : "Minor";
System.out.println(result);Output:
AdultIt's useful for simple conditions.
Don't force complicated logic into a ternary expression. If the expression becomes difficult to read, a normal if-else is usually better.
Bitwise Operators
Java also provides bitwise operators for working at the binary level.
Common operators include:
&
|
^
~
<<
>>
>>>Example:
int a = 5;
int b = 3;
System.out.println(a & b);Bitwise operations are more common in low-level programming, performance-sensitive code, binary protocols, and certain algorithms.
You don't need to master them before learning basic Java programming.
Operator Precedence
Java doesn't simply evaluate every operator from left to right.
Some operators have higher precedence than others.
For example:
int result = 10 + 5 * 2;The multiplication happens first.
So:
10 + (5 × 2)
= 20not:
(10 + 5) × 2
= 30When there's any doubt, use parentheses:
int result = (10 + 5) * 2;This isn't just about getting the answer right. Parentheses make your intention obvious to whoever reads the code later.
Real-World Java Example
Let's combine everything into a small student marks program.
public class StudentResult {
public static void main(String[] args) {
int math = 85;
int science = 90;
int english = 80;
int total = math + science + english;
double average = (double) total / 3;
boolean passed = average >= 40;
char grade = 'A';
System.out.println("Total: " + total);
System.out.println("Average: " + average);
System.out.println("Grade: " + grade);
System.out.println("Passed: " + passed);
}
}Output:
Total: 255
Average: 85.0
Grade: A
Passed: trueWhat's happening here?
math, science, english
↓
Variables
↓
int values
↓
+ arithmetic
↓
total
↓
(double) casting
↓
average
↓
>= comparison
↓
booleanThis is exactly how these four concepts work together in a real Java program.
Common Beginner Mistakes
Mistake 1: Using the Wrong Data Type
int price = 99.99;This won't compile because 99.99 is a decimal value.
Use:
double price = 99.99;Mistake 2: Forgetting L
For a large long literal:
long population = 8000000000L;The L tells Java that the literal should be treated as a long.
Mistake 3: Forgetting f
For a float literal:
float temperature = 36.5f;Without f, a decimal literal is normally treated as a double.
Mistake 4: Expecting Integer Division to Return Decimals
int result = 7 / 2;Result:
3Use:
double result = 7.0 / 2;Result:
3.5Mistake 5: Casting Without Understanding Data Loss
double value = 15.99;
int number = (int) value;Result:
15The .99 is discarded.
Mistake 6: Confusing char and String
Correct:
char grade = 'A';
String name = "Java";char uses single quotes.
String uses double quotes.
Best Practices
A few habits will save you trouble later.
Use meaningful variable names
Prefer:
int studentAge;over:
int x;Use the simplest suitable type
For most whole-number calculations:
int count;is a reasonable default.
Don't cast unnecessarily
If Java can safely widen the value automatically, there's usually no need to add a cast.
Use parentheses when expressions become unclear
Instead of:
int result = a + b * c;you might prefer:
int result = a + (b * c);when the grouping matters for readability.
Be careful with floating-point calculations
float and double are binary floating-point types. They're excellent for many scientific and general-purpose calculations, but they're not ideal for exact decimal financial arithmetic.
For money, Java's BigDecimal is often a better choice.
Variables vs Data Types vs Operators vs Casting
Think of it this way:
int age = 25;
│ │ │
│ │ └── Value
│ └───────── Variable
└───────────── Data TypeThen:
age + 5uses an operator.
And:
(double) ageuses type casting.
Interview Questions
1. What is a variable in Java?
A variable is a named storage location used to hold a value.
2. How many primitive data types does Java have?
Java has eight primitive data types: byte, short, int, long, float, double, char, and boolean.
3. What is type casting?
Type casting is converting a value from one data type to another.
4. What is widening casting?
Converting a smaller compatible type into a larger type, usually automatically.
Example:
int x = 10;
double y = x;5. What is narrowing casting?
Converting a larger type into a smaller type using an explicit cast.
double x = 10.5;
int y = (int) x;6. What is the difference between = and ==?
= assigns a value.
== compares values.
7. What does % do?
It returns the remainder of a division.
10 % 3returns:
18. What is integer division?
Division between integer operands produces an integer result with the fractional part discarded.
5 / 2returns:
29. What is the difference between char and String?
char stores one character, while String represents a sequence of characters.
10. What does ++ do?
It increases a numeric variable by one.
Frequently Asked Questions
What are variables in Java?
Variables are named storage locations that hold values. Every variable has a declared data type.
What are the 8 primitive data types in Java?
They are byte, short, int, long, float, double, char, and boolean.
What is the most commonly used integer type in Java?
int is the usual choice for general-purpose integer calculations.
What is type casting in Java?
Type casting converts a value from one data type to another.
What is widening casting?
Widening converts a value to a type that can represent a broader range of values and is generally performed automatically.
What is narrowing casting?
Narrowing explicitly converts a value to a smaller type and can result in data loss.
What are operators in Java?
Operators are symbols used to perform calculations, comparisons, assignments, logical operations, and other operations.
What is the difference between = and == in Java?
= is an assignment operator, while == is an equality comparison operator.
Why does 5 / 2 return 2 in Java?
Because both operands are integers, Java performs integer division and discards the fractional part.
Is String a primitive data type in Java?
No. String is a class, not one of Java's eight primitive data types.
Key Takeaways
Java becomes much easier once these four fundamentals are clear:
Variables hold information.
Data types define what kind of information can be stored.
Type casting converts values between compatible types.
Operators let you work with those values.
You'll use all four constantly as you move into conditions, loops, methods, arrays, and object-oriented programming.
Have a Question?
If you run into any issues while writing or running your first Java program, leave a comment below.
We'll help you troubleshoot the problem with clear explanations and practical solutions so you can continue your Java learning journey with confidence.
Happy Coding! ☕
Follow TheTechLane
Want more Java tutorials, programming tips, and developer resources?
Follow TheTechLane on LinkedIn, X, Instagram, Threads, Facebook, Medium, and Pinterest to stay updated whenever a new tutorial is published.
Learn. Build. Share.
Related reading: your first Java program, what OOP is, and install IntelliJ IDEA.