Assigning Values

3 min read ·

Declaring a variable creates space in memory. Assigning a value means putting actual data inside that variable.
In Java, we use the assignment operator:
The value on the right side gets stored in the variable on the left side.

Basic Syntax

Example:
Here:
  • age is already declared.
  • 25 is assigned to age.

Complete Runnable Example

Output:
25

Declaration + Assignment Together

In real programs, we usually declare and assign in a single line.
Example:
This is the most commonly used style.

Assigning Different Data Types

1️⃣ Integer (int)

Whole numbers only.

2️⃣ Decimal (double)

Decimal values allowed.

3️⃣ Character (char)

  • Must use single quotes
  • Only one character allowed
Wrong:

4️⃣ String

  • Must use double quotes
Wrong:

Re-Assigning Values

Variables can change their value later in the program.
Output:
50 80
The old value gets replaced.

Assigning One Variable to Another

Output:
10
Here, b gets a copy of a.

Assigning Expressions

You can assign calculated values.
Output:
15
Java first calculates the expression, then assigns the result.

Multiple Assignments in One Line

Output:
100 100 100
Java assigns from right to left.

Common Mistakes Beginners Make

❌ Using == Instead of =

== is comparison operator, not assignment.
Correct:

❌ Not Matching Data Types

Because 10.5 is decimal.
Correct:

Assigning values is where variables actually become useful. Without assignment, variables are just empty containers. With assignment, they start storing real data and power your program logic.
Learn Java Assigning Values | Java Course