Declare and use variables and constants
Declare and Use Variables and Constants
What are Variables and Constants? 🧮
Variable – a named storage location that can hold a value that may change during the program. Think of it as a labelled jar that you can fill with different candies at different times.
Constant – a named storage location whose value is set once and never changes. It’s like a permanent note on a whiteboard: once you write it, you can’t erase it.
In Java, you declare a variable with a type and a name:
int age = 15;
A constant is declared with the final keyword:
final double PI = 3.14159;
Why Use Variables? 📚
Variables let your program store information that can change, such as user input, loop counters, or results of calculations.
Example:
- Ask the user for their age.
- Store the answer in
age. - Use
ageto decide what content to show.
Declaring Variables – The Syntax
Syntax: type variableName = value;
Common Types:
int– whole numbersdouble– numbers with decimalschar– single charactersString– sequences of characters (text)
Using Variables – The Flow
1️⃣ Declare – tell the computer what type and name it will use.
2️⃣ Assign – give it an initial value.
3️⃣ Use – read or modify the value in expressions or statements.
Example in a loop:
int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; }
After the loop, sum holds the total of numbers 1 to 10.
Constants – When to Use Them
Constants are useful for values that should not change, such as mathematical constants or configuration settings.
Example:
final int DAYS_IN_WEEK = 7;
Using constants improves code readability and prevents accidental changes.
Common Mistakes to Avoid
- Using a variable before it has been assigned a value.
- Changing a constant’s value (the compiler will flag an error).
- Choosing variable names that are too short or unclear.
- Mixing data types – e.g., adding an
intto aStringwithout conversion.
Exam Tip Box 📌
Remember:
- Use
finalfor constants. - Always initialise a variable before use.
- Choose descriptive names (e.g.,
studentScoreinstead ofs).
Practice: Write a short program that asks for a student’s name and score, then prints a message using those variables.
Good luck!
Quick Reference Table
| Name | Type | Initial Value | Example Usage |
|---|---|---|---|
| age | int | 15 | int age = 15; |
| PI | double | 3.14159 | final double PI = 3.14159; |
| greeting | String | "Hello" | String greeting = "Hello"; |
Practice Challenge
Write a program that:
- Declares a constant
MAX_GRADEwith a value of 100. - Asks the user for a score.
- Stores the score in a variable
score. - Prints a message: “Your score is
out of .”
Revision
Log in to practice.