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:

  1. Ask the user for their age.
  2. Store the answer in age.
  3. Use age to decide what content to show.

Declaring Variables – The Syntax

Syntax: type variableName = value;

Common Types:

  • int – whole numbers
  • double – numbers with decimals
  • char – single characters
  • String – 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 int to a String without conversion.

Exam Tip Box 📌

Tip: When you see a question about variables or constants, check if the problem asks you to declare or use them.

Remember:
  • Use final for constants.
  • Always initialise a variable before use.
  • Choose descriptive names (e.g., studentScore instead of s).

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:

  1. Declares a constant MAX_GRADE with a value of 100.
  2. Asks the user for a score.
  3. Stores the score in a variable score.
  4. Prints a message: “Your score is out of .”
Try to use clear variable names and remember to initialise everything before use.

Revision

Log in to practice.

1 views 0 suggestions