Constant & Variables

Comprehensive study notes, diagrams, and exam preparation for Constant & Variables.

Constants & Variables in Java

Definition

In Java programming, a Variable is a named container that holds data which can change during the execution of a program, while a Constant is a fixed value that remains unchanged throughout the program's lifecycle.


Main Content

1. Variables

  • A variable represents a memory location where a value is stored.
  • In Java, every variable must have a specific data type (e.g., int, double, String) that determines the kind of data it can hold.
  • Example: int age = 25; where age is the variable.

2. Constants

  • A constant is a variable whose value cannot be modified once it is assigned.
  • In Java, we use the final keyword to declare a constant.
  • Example: final double PI = 3.14159; where PI is a constant.

3. Memory Representation

  • Variables act as buckets that can be emptied and refilled.
  • Constants act as sealed boxes that are filled once and cannot be opened to change the content.
[VARIABLE: 'age']      [CONSTANT: 'PI']
+-----------+          +-----------+
|    25     |          |  3.14159  |
+-----------+          +-----------+
      |                      |
(Can change to 26)     (Stays 3.14159)

Working / Process

1. Declaration

  • This step involves informing the compiler about the name and data type of the storage.
  • Syntax: dataType variableName; (e.g., int score;)

2. Initialization

  • This is the process of assigning an initial value to the variable for the first time.
  • Syntax: variableName = value; (e.g., score = 100;)

3. Modification

  • For variables, you can update the value later in the code.
  • Constants cannot undergo this step; attempting to reassign a final variable will cause a compilation error.

Advantages / Applications

  • Data Management: Variables allow programs to process dynamic user input and changing states.
  • Code Readability: Using meaningful names for constants (like MAX_USERS) makes code easier to understand than using raw numbers.
  • Security: Constants prevent accidental modification of critical configuration values like tax rates or mathematical constants.

Summary

In Java, variables are flexible storage spaces for data that may update, while constants are immutable values locked with the final keyword. Variables allow for dynamic logic and user interaction, whereas constants provide stability and clarity for fixed program settings. Key terms include Data Type, Initialization, and the final keyword.