Variables and Constants
Declare, initialize and update variables, understand types and basic scope, create `final` constants and see when `var` fits.
আপনি একটি free preview lesson দেখছেন।
Lesson Overview
While a program is running, it needs to store and use data: a student's name, a course's duration, a product's price, the result of a calculation, whether a feature is enabled. Nur's mark calculator in lesson 1.01 kept her three marks, the total and the average in exactly this way.
In Java, we use variables to store these values under meaningful names. A variable's value can change as the program runs. Some values, however, should never change once they have been assigned, and Java lets us say so with final. In this lesson, we learn how to create, change and protect variables, and where in a program each one can be used.
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. In the statement int age = 30;, int is the data type, age is the variable name and 30 is the value. The variable's value can be used later by its name:
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, we repeat the text:
System.out.println("Java and OOP Foundation");
System.out.println("Java and OOP Foundation");
Using a variable, we write it once:
String courseName = "Java and OOP Foundation";
System.out.println(courseName);
System.out.println(courseName);
If the course name changes, we now change it in one place. Variables make code more readable, let us reuse values and calculate with them, and let a program keep track of state that changes as it runs.
Declaration, Initialization, and Assignment
It is important to distinguish between these three terms. A variable declaration tells the compiler the variable's type and name. The syntax is dataType variableName;, for example:
int age;
String studentName;
double coursePrice;
boolean isAvailable;
The variables have been declared, but no initial value has been assigned yet. Giving a variable its first value is called initialization. Here, declaration and initialization happen in the same statement:
int age = 30;
String studentName = "Sakib";
double coursePrice = 4990.0;
boolean isAvailable = true;
Assignment means putting a value into a variable, as in age = 30;. A variable can be declared first and assigned a value later:
int age;
age = 30;
In short, int age; is a declaration, int age = 30; is an initialization, and age = 30; is an assignment.
Assignment and Reassignment
The value of a normal variable can be changed later. The new value replaces the old value:
int age = 30;
age = 31;
System.out.println(age);
Output:
31
Assignment Operator =
In Java, = is the assignment operator. In int total = 10 + 20;, the expression 10 + 20 is evaluated first, giving 30, and then the value is assigned to the total variable.
Assignment and Equality Are Not the Same
The assignment age = 18; means the value 18 is stored in age. For comparison, we will later use age == 18. = and == are different operators.
Using and Updating Variable Values
The stored values of variables can be used in a calculation:
int firstNumber = 10;
int secondNumber = 20;
int total = firstNumber + secondNumber;
System.out.println(total);
Output:
30
You can also 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: int age = 30; followed by int age = 31; does not compile. If you want to change the value of an existing variable, declare it once and then reassign it, as in age = 31; above.
Variable Type
Java is a statically typed language. Once a variable's type is determined, it can only store compatible values, and the type cannot be changed after the variable is declared. In int age = 30;, age is an int variable, so this is invalid:
int age = "thirty";
because "thirty" is text, while age was declared to store an integer.
Some Common Types
At this stage, we will use only a few types as examples, such as double price = 99.50; or char grade = 'A';:
| 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
As lesson 1.08 explained, a variable name should express the meaning of the value it stores: studentAge and coursePrice, not x and p. Variables follow the camelCase convention, and a boolean variable reads best as a true-or-false condition, such as isActive, hasPermission or canEnroll, rather than flag or status.
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
Local Variables
A variable declared inside a method is called a local variable. Here, studentName and age are local variables:
public class Main {
public static void main(String[] args) {
String studentName = "Sakib";
int age = 20;
System.out.println(studentName);
System.out.println(age);
}
}
Local Variables Must Be Initialized
A local variable must be assigned a value before it is read. Wrong, because the compiler will not allow it:
int age;
System.out.println(age);
javac reports variable age might not have been initialized. Either initialize the variable (int age = 30;) or assign it before the println (age = 30;).
Variable Scope
Scope determines which parts of the code can access a variable. In the Local Variables program above, studentName and age are available inside the block of the main method, from their declaration to the method's closing brace. They 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; makes javac report cannot assign a value to final variable courseDurationInWeeks.
A final Variable Can Be Assigned Later
A local final variable can be declared without a value and assigned once later. After that, it cannot be assigned again:
final int minimumAge;
minimumAge = 18;
Variable vs. Fixed Value
A changing value is a normal variable, while a fixed value is final:
int enrolledStudentCount = 75;
enrolledStudentCount = 76;
final int maximumStudentCapacity = 100;
The enrolled count changes as learners join; the capacity should not change while the program runs, and final makes the compiler enforce that.
Constant
A class-level constant is used for a reusable fixed value in an application:
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, for example MAXIMUM_STUDENT_CAPACITY, DEFAULT_LANGUAGE and MAXIMUM_LOGIN_ATTEMPTS. We will learn more about static and class members later. For now, recognize the pattern static final type NAME = value;, written inside the class but outside main.
Not Every final Variable Is a Constant
Compare a local final variable with a class-level reusable constant:
final int durationInWeeks = 8;
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. One variable per line is generally clearer:
int firstNumber = 10;
int secondNumber = 20;
var
In Java 21, var can be used to let the compiler infer the type of a local variable. The compiler determines the type from the assigned value:
var age = 30;
var courseName = "Java Foundation";
var isAvailable = true;
Conceptually, the inferred type of age in var age = 30; is int.
var Does Not Make Java Dynamically Typed
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, because the compiler cannot infer the type:
var age;
Correct:
var age = 30;
When Should You Use var?
When you are beginning to learn Java, writing explicit types such as int age = 30; is more useful, because it builds 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.
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, courseName and enrollmentOpen are normal local variables, enrolledStudentCount is reassigned from 75 to 76, and MAXIMUM_STUDENT_CAPACITY is a fixed class-level constant.
Predict the Result
Decide what each program prints, or whether it compiles, before reading the answer.
Question 1
public class Main {
public static void main(String[] args) {
int originalScore = 5;
int copiedScore = originalScore;
originalScore = 10;
System.out.println(originalScore);
System.out.println(copiedScore);
}
}
Answer
10
5
int copiedScore = originalScore; copies the value 5 into copiedScore. Reassigning originalScore later does not change the copy.
Question 2
<!-- error -->public class Main {
public static void main(String[] args) {
{
String message = "Hello";
System.out.println(message);
}
System.out.println(message);
}
}
Answer
It does not compile. javac reports cannot find symbol for the last message, because the variable's scope ended with the inner block.
Question 3
public class Main {
public static void main(String[] args) {
final int minimumAge;
minimumAge = 18;
System.out.println("Minimum age: " + minimumAge);
}
}
Answer
Minimum age: 18
A local final variable may be declared without a value and assigned exactly once later. Only a second assignment would be an error.
Question 4
<!-- error -->public class Main {
public static void main(String[] args) {
var lessonCount = 10;
lessonCount = 10.5;
System.out.println(lessonCount);
}
}
Answer
It does not compile: incompatible types: possible lossy conversion from double to int. var inferred int from 10, and the type stays int, so a decimal value cannot be stored in it.
Question 5
<!-- error -->public class Main {
public static void main(String[] args) {
int age = 20;
{
int age = 21;
System.out.println(age);
}
}
}
Answer
It does not compile: variable age is already defined in method main(String[]). The outer age is still in scope inside the inner block, so declaring another age there is a duplicate declaration.
Common Mistakes
Undeclared Variable
Wrong:
System.out.println(courseName);
If courseName has not been declared earlier, or is misspelled (coursename), the compiler does not know the name:
Main.java:4: error: cannot find symbol
System.out.println(courseName);
^
symbol: variable courseName
location: class Main
1 error
cannot find symbol is one of the most common messages you will see. Check the spelling and capitalization first, then whether the variable is declared before this line and in a scope that reaches it. Correct:
String courseName = "Java Foundation";
System.out.println(courseName);
Type Mismatch With Quotes
Wrong:
int age = "30";
"30" looks like a number, but the quotes make it a String value, so javac reports incompatible types: String cannot be converted to int. Remove the quotes: int age = 30;.
Declaring Again Instead of Reassigning
Writing int age = 31; a second time, when you meant to update age, gives variable age is already defined in method main(String[]). Drop the type to reassign: age = 31;.
Practice Exercise 1: Statement Breakdown
Solutions: lesson 1.23.
Look at the statement int studentAge = 20; and 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, using meaningful camelCase names:
- Student name
- Student age
- Course duration
- Whether the course is available
- Student grade
Practice Exercise 4: Predict the Output
Write the final output of this program before running it:
public class Main {
public static void main(String[] args) {
int score = 10;
score = score + 5;
score = score * 2;
System.out.println(score);
}
}
Practice Exercise 5: Fix the Errors
<!-- error -->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 with the value 8. Then explain why the following assignment will not compile:
courseDurationInWeeks = 10;
Practice Exercise 7: var
Rewrite the following explicit declarations using var, and write the inferred type of each variable:
int age = 30;
String courseName = "Java Foundation";
boolean isAvailable = true;
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
- A variable is a named location that stores a value, and its type decides what kind of value it can hold.
- Declaration gives a variable its type and name, initialization gives it its first value, and assignment puts a value into it.
- A normal variable can be reassigned, but its type cannot change after it is declared.
- A local variable is declared inside a method or block, must be assigned a value before it is read, and is only accessible within its scope.
finalprevents a variable from being reassigned, and class-level constants such asstatic final int MAXIMUM_STUDENT_CAPACITY = 100;useUPPER_SNAKE_CASE.varlets the compiler infer a local variable's type from its initial value, and Java remains statically typed.
আগে ভাবুন
শীঘ্রই আসছেCheckpoint প্রশ্ন, যেখানে lesson উত্তর দেখানোর আগে আপনাকে একটি উত্তর বেছে নিতে হবে।