Programming and Java Fundamentals
Variables and Constants
You are viewing a free preview lesson.
Lesson Overview
While a program is running, it needs to store and use different types of data.
For example:
- Student name
- User age
- Course duration
- Product price
- Result of a calculation
- Whether a feature is enabled
In Java, we use variables to store these kinds of values.
A variable's value can be changed. However, some values should not change once they have been assigned. In those cases, final can be used.
In this lesson, we will learn:
- What a variable is
- Declaration and initialization
- Assignment and reassignment
- Variable type
- Local variables
- The basic concept of variable scope
final- Constants
var
Learning Objectives
After completing this lesson, you will be able to:
- Declare and initialize Java variables
- Assign and update variable values
- Distinguish between declaration, initialization, and assignment
- Understand the role of a variable's type
- Use local variables
- Understand basic scope
- Create
finalvariables - Recognize constant naming conventions
- Understand the basic use of
var
What Is a Variable?
A variable is a named location in a program where a value is stored.
Example:
int age = 30;
Here:
int— data typeage— variable name30— value
The variable's value can be used later:
int age = 30;
System.out.println(age);
Output:
30
Why Do We Need Variables?
Suppose the same course name needs to be used in several places.
Without a variable:
System.out.println("Java and OOP Foundation");
System.out.println("Java and OOP Foundation");
Using a variable:
String courseName = "Java and OOP Foundation";
System.out.println(courseName);
System.out.println(courseName);
Variables make code:
- More readable
- Able to reuse values
- Easier to use in calculations
- Able to track changing state
Variable Declaration
A variable declaration tells the compiler the variable's type and name.
Syntax:
dataType variableName;
Example:
int age;
More examples:
String studentName;
double coursePrice;
boolean isAvailable;
The variables have been declared, but no initial value has been assigned yet.
Variable Initialization
Giving a variable its first value is called initialization.
int age = 30;
Here, declaration and initialization happen in the same statement.
More examples:
String studentName = "Sakib";
double coursePrice = 4990.0;
boolean isAvailable = true;
Declaration and Assignment Separately
A variable can be declared first and assigned a value later.
int age;
age = 30;
Here:
int age;
is the declaration.
And:
age = 30;
is the assignment.
Declaration, Initialization, and Assignment
It is important to distinguish between these terms.
Declaration
Defining the variable's type and name:
int age;
Initialization
Giving the variable its first value:
int age = 30;
Assignment
Putting a value into a variable:
age = 30;
Reassignment
The value of a normal variable can be changed later.
int age = 30;
age = 31;
System.out.println(age);
Output:
31
The new value replaces the old value.
Assignment Operator =
In Java:
=
is the assignment operator.
int total = 10 + 20;
Here, first:
10 + 20
is evaluated.
Result:
30
Then the value is assigned to the total variable.
Assignment and Equality Are Not the Same
Assignment:
age = 18;
means the value 18 is stored in age.
For comparison, we will later use:
age == 18
= and == are different operators.
Using Variable Values
int firstNumber = 10;
int secondNumber = 20;
int total = firstNumber + secondNumber;
System.out.println(total);
Output:
30
Here, the stored values of firstNumber and secondNumber are used in the calculation.
Variable Type
Java is a statically typed language.
Once a variable's type is determined, it can only store compatible values.
int age = 30;
Here, age is an int variable.
Invalid:
int age = "thirty";
because "thirty" is text, while age was declared to store an integer.
After a variable is declared, its type cannot be changed.
Some Common Types
At this stage, we will use only a few types as examples:
int age = 30;
double price = 99.50;
boolean isAvailable = true;
char grade = 'A';
String courseName = "Java Foundation";
| Type | Example |
|---|---|
int | 30 |
double | 99.50 |
boolean | true |
char | 'A' |
String | "Java Foundation" |
We will learn Java data types in detail in the next lesson.
Meaningful Variable Names
A variable name should express the meaning of the value it stores.
Poor:
int x = 30;
Better:
int studentAge = 30;
Poor:
double p = 4990.0;
Better:
double coursePrice = 4990.0;
Variables generally follow the camelCase naming convention:
studentName
coursePrice
totalMarks
isAvailable
Boolean Variable Names
A boolean variable should preferably have a name that expresses a true or false condition.
Good:
boolean isActive;
boolean hasPermission;
boolean canEnroll;
boolean paymentCompleted;
Less clear:
boolean flag;
boolean status;
boolean value;
Using Variables in Output
public class Main {
public static void main(String[] args) {
String courseName = "Java and OOP Foundation";
int durationInWeeks = 8;
boolean isAvailable = true;
System.out.println("Course: " + courseName);
System.out.println("Duration: " + durationInWeeks);
System.out.println("Available: " + isAvailable);
}
}
Output:
Course: Java and OOP Foundation
Duration: 8
Available: true
Updating a Variable
You can use a variable's current value to assign a new value.
int score = 10;
score = score + 5;
System.out.println(score);
Output:
15
Step by step:
score = 10
score = 10 + 5
score = 15
Duplicate Declaration
The same variable cannot be declared twice in the same scope.
Wrong:
int age = 30;
int age = 31;
If you want to change the value of an existing variable:
int age = 30;
age = 31;
The first statement is the declaration.
The second statement is reassignment.
Local Variable
A variable declared inside a method is called a local variable.
public class Main {
public static void main(String[] args) {
String studentName = "Sakib";
int age = 20;
System.out.println(studentName);
System.out.println(age);
}
}
Here:
studentName
age
are local variables.
Local Variables Must Be Initialized
A local variable must be assigned a value before it is read.
Wrong:
int age;
System.out.println(age);
The compiler will not allow this.
Correct:
int age = 30;
System.out.println(age);
or:
int age;
age = 30;
System.out.println(age);
Variable Scope
Scope determines which parts of the code can access a variable.
public class Main {
public static void main(String[] args) {
int age = 30;
System.out.println(age);
}
}
The age variable is available inside the block of the main method.
This local variable cannot be used outside the main method.
Nested Block
An inner block can use accessible variables from an outer block.
public class Main {
public static void main(String[] args) {
int age = 20;
{
System.out.println(age);
}
}
}
However, a variable declared inside an inner block is no longer available after that block ends.
public class Main {
public static void main(String[] args) {
{
String message = "Hello";
System.out.println(message);
}
// message is not accessible here
}
}
At this stage, remember:
Keeping a variable within the smallest necessary scope makes code easier to understand.
The final Keyword
If you do not want a variable's value to be changed after assignment, you can use final.
final int courseDurationInWeeks = 8;
Now reassignment is invalid:
courseDurationInWeeks = 10;
This will cause a compiler error.
A final Variable Can Be Assigned Later
A local final variable can be declared without a value and assigned once later.
final int minimumAge;
minimumAge = 18;
After that, it cannot be assigned again.
Variable vs. Fixed Value
Changing value:
int enrolledStudentCount = 75;
enrolledStudentCount = 76;
Fixed value:
final int maximumStudentCapacity = 100;
Difference:
enrolledStudentCount → can change
maximumStudentCapacity → should not change
Constant
A class-level constant is used for a reusable fixed value in an application.
Example:
public class Main {
static final int MAXIMUM_STUDENT_CAPACITY = 100;
public static void main(String[] args) {
System.out.println(MAXIMUM_STUDENT_CAPACITY);
}
}
Constants generally follow:
UPPER_SNAKE_CASE
Examples:
MAXIMUM_STUDENT_CAPACITY
DEFAULT_LANGUAGE
MAXIMUM_LOGIN_ATTEMPTS
We will learn more about static and class members later.
For now, recognize this pattern:
static final int MAXIMUM_STUDENT_CAPACITY = 100;
Not Every final Variable Is a Constant
Local final variable:
final int durationInWeeks = 8;
Class-level reusable constant:
static final int COURSE_DURATION_IN_WEEKS = 8;
Neither can be reassigned, but their purpose in a codebase may be different.
Multiple Variable Declaration
Java allows multiple variables of the same type to be declared in one statement.
int firstNumber = 10, secondNumber = 20;
However, separate declarations are preferred for readability:
int firstNumber = 10;
int secondNumber = 20;
One variable per line is generally clearer.
var
In Java 21, var can be used to let the compiler infer the type of a local variable.
var age = 30;
var courseName = "Java Foundation";
var isAvailable = true;
The compiler determines the type from the assigned value.
Conceptually:
var age = 30;
Here, the inferred type of age is int.
var Does Not Make Java Dynamically Typed
var age = 30;
After its type is inferred, age is an int variable.
Therefore:
age = "thirty";
is not valid.
Java remains statically typed.
var Requires an Initial Value
Wrong:
var age;
The compiler cannot infer the type.
Correct:
var age = 30;
When Should You Use var?
When you are beginning to learn Java, using explicit types is more useful:
int age = 30;
String courseName = "Java Foundation";
boolean isAvailable = true;
This helps build an understanding of types.
Use var when the inferred type is clear from the code and readability is not reduced.
At the beginning of this course, we will use explicit types in most examples.
Common Variable Errors
Undeclared Variable
Wrong:
System.out.println(courseName);
If courseName has not been declared earlier, this will cause a compiler error.
Correct:
String courseName = "Java Foundation";
System.out.println(courseName);
Uninitialized Local Variable
Wrong:
int age;
System.out.println(age);
Correct:
int age = 30;
System.out.println(age);
Type Mismatch
Wrong:
int age = "30";
Correct:
int age = 30;
Duplicate Declaration
Wrong:
int age = 30;
int age = 31;
Correct:
int age = 30;
age = 31;
Reassigning a final Variable
Wrong:
final int durationInWeeks = 8;
durationInWeeks = 10;
A final variable cannot be reassigned.
var Without Initialization
Wrong:
var courseName;
Correct:
var courseName = "Java Foundation";
A Complete Example
public class Main {
static final int MAXIMUM_STUDENT_CAPACITY = 100;
public static void main(String[] args) {
String courseName = "Java and OOP Foundation";
int enrolledStudentCount = 75;
boolean enrollmentOpen = true;
enrolledStudentCount = 76;
System.out.println("Course: " + courseName);
System.out.println("Enrolled students: " + enrolledStudentCount);
System.out.println("Maximum capacity: " + MAXIMUM_STUDENT_CAPACITY);
System.out.println("Enrollment open: " + enrollmentOpen);
}
}
Output:
Course: Java and OOP Foundation
Enrolled students: 76
Maximum capacity: 100
Enrollment open: true
In this program:
courseNameis a normal variableenrolledStudentCountis reassignedenrollmentOpenstores a boolean valueMAXIMUM_STUDENT_CAPACITYis a fixed constant
Important Terms
Variable
A named location where a value is stored.
Data Type
Determines what kind of value a variable can store.
Declaration
Defining a variable's type and name.
int age;
Initialization
Giving a variable its first value.
int age = 30;
Assignment
Putting a value into a variable.
age = 30;
Reassignment
Replacing an existing value with a new value.
age = 31;
Local Variable
A variable declared inside a method or block.
Scope
The region of code from which a variable is accessible.
final
Prevents a variable from being reassigned.
Constant
A reusable fixed value.
var
Allows the compiler to infer the type of a local variable.
Practice Exercise 1: Statement Breakdown
Look at the following statement:
int studentAge = 20;
Identify:
- Data type
- Variable name
- Assignment operator
- Initial value
- Statement terminator
Practice Exercise 2: Declaration, Initialization, or Assignment?
Identify each statement:
int age;
int score = 80;
age = 30;
Practice Exercise 3: Create Variables
Write appropriate variables for the following information:
- Student name
- Student age
- Course duration
- Whether the course is available
- Student grade
Use meaningful camelCase names.
Practice Exercise 4: Predict the Output
public class Main {
public static void main(String[] args) {
int score = 10;
score = score + 5;
score = score * 2;
System.out.println(score);
}
}
Write the final output before running the program.
Practice Exercise 5: Fix the Errors
public class Main {
public static void main(String[] args) {
int studentAge;
studentAge = "20";
System.out.println(studentAge);
}
}
Expected output:
20
Practice Exercise 6: final
Create a final variable:
courseDurationInWeeks = 8
Then explain why the following assignment will not compile:
courseDurationInWeeks = 10;
Practice Exercise 7: var
Rewrite the following explicit declarations using var:
int age = 30;
String courseName = "Java Foundation";
boolean isAvailable = true;
Write the inferred type of each variable.
Knowledge Check
Question 1
What is a variable?
Question 2
What is the difference between declaration and initialization?
Question 3
Which operator is the assignment operator?
Question 4
What is reassignment?
Question 5
Can a variable's type be changed after it has been declared?
Question 6
What is a local variable?
Question 7
Can an uninitialized local variable be read?
Question 8
What is scope?
Question 9
What does final do?
Question 10
What is the common naming convention for constants?
Question 11
What does var do?
Question 12
Does using var make Java dynamically typed?
Knowledge Check Answers
Answer 1
A variable is a named location in a program where a value is stored.
Answer 2
Declaration defines a variable's type and name. Initialization gives the variable its first value.
Answer 3
The assignment operator is:
=
Answer 4
Reassignment means replacing an existing value with a new value.
Answer 5
No. A variable's type cannot be changed after it has been declared.
Answer 6
A variable declared inside a method or block is a local variable.
Answer 7
No. A local variable must be initialized before it is read.
Answer 8
Scope determines which parts of the code can access a variable.
Answer 9
final prevents a variable from being reassigned.
Answer 10
Constants generally follow:
UPPER_SNAKE_CASE
Answer 11
var allows the compiler to infer the type of a local variable from its assigned value.
Answer 12
No. After the inferred type is determined, the variable remains statically typed.
Lesson Summary
In this lesson, we learned:
- Variables store data in a program
- Declaration defines a variable's type and name
- Initialization gives a variable its first value
- The assignment operator
=assigns a value - Normal variables can be reassigned
- Java variables are statically typed
- Meaningful variable names make code more readable
- Variables generally follow camelCase
- Local variables are declared inside methods or blocks
- Local variables must be initialized before they are used
- Scope determines where a variable is accessible
finalprevents reassignment- Reusable constants generally follow
UPPER_SNAKE_CASE varallows local variable type inference- Java remains statically typed when
varis used