3.1 Lesson Outcomes
After completing this lesson, learners will be able to:
- Declare variables in Java.
- Initialize variables correctly.
- Apply Java variable naming conventions.
- Assign values to variables.
- Use different variable data types.
3.2 Overview
Variables are used in Java programs to store and manage data. Every variable in Java must have a data type and a valid name. Variables can store numbers, text, decimal values, and logical values.
This lesson introduces learners to the practical use of variables in Java applications.
Variables are important in:
- software development,
- calculations,
- data processing,
- and application logic.
Understanding variables is important because they are used in almost every Java program.
PA0201 — Declare Variables
Declaring a variable tells Java what type of data will be stored.
Example Variable Declaration
Java
int age;
Java
String name;
Common Variable Types
|
Data Type |
Purpose |
|---|---|
|
int |
Whole numbers |
|
double |
Decimal numbers |
|
String |
Text |
|
boolean |
True or False |
Practical Activity
Learners must:
- declare variables,
- use correct data types,
- and apply correct Java syntax.
PA0202 — Initialise Variables
Initialization means assigning a starting value to a variable.
Example Initialization
Java
int age = 25;
Java
String name = “Alice”;
Importance of Initialization
Initialization:
- prepares variables for use,
- stores starting values,
- and prevents errors.
Practical Activity
Learners must:
- initialize variables,
- assign correct values,
- and test program output.
PA0203 — Name Variables
Java uses naming conventions for variables.
Variable Naming Rules
|
Rule |
Description |
|---|---|
|
Start with letter, _ or $ |
Valid start |
|
No spaces allowed |
Invalid syntax |
|
Cannot use keywords |
Reserved words not allowed |
|
Use camelCase |
Standard naming style |
Valid Variable Names
Java
firstName
Java
studentAge
Invalid Variable Name
Java
int 1number;
Practical Activity
Learners must:
- create valid variable names,
- identify invalid names,
- and apply Java naming conventions.
PA0204 — Assign a Value
Values can be assigned after variable declaration.
Example Value Assignment
Java
double price;
price = 99.99;
Assignment Operator
Plain text
=
is used to assign values.
Practical Activity
Learners must:
- assign values to variables,
- modify variable values,
- and display variable output.
Example Java Program
Java
public class VariablesExample {
public static void main(String[] args) {
int age = 25;
String name = “Alice”;
double price = 19.99;
boolean isStudent = true;
System.out.println(name);
System.out.println(age);
System.out.println(price);
System.out.println(isStudent);
}
}
3.5 Key Notes / Summary
- Variables store data in Java programs.
- Every variable must have a data type.
- Variables can be initialized during declaration.
- Java uses naming conventions for variables.
- The assignment operator assigns values.
- Variables are used in calculations and program logic.