Variables and Constants in Java
Variables in Java
A variable in Java is a container that holds a value of a specific data type. Java is a statically-typed language, which means it is mandatory to declare the data type of a variable before assigning a value.
Variables in Java can be classified into two types:
1. Global Variables: These are declared at the class level, outside methods, constructors, and blocks.
2. Local Variables: These are declared inside methods, constructors, or blocks.
Global Variables
Global variables are declared within a class but outside of any methods, constructors, or blocks. There are two types of global variables:
1. Class Variables (Static Variables)
• A class variable is declared with the static keyword.
• The value of a class variable remains the same for all instances of the class.
• Only one copy of the class variable is created in the static pool, and all objects of the class point to this single copy.
• Class variables are accessed using the class name.
Syntax:
<access modifier> static <data type> <varname>;
Example:
static String ceoName = "Tom";
Here, ceoName is declared as static because the CEO’s name will be the same for all employees in the organization.
Instance Variables -
• Instance variables are declared at the global scope, outside of methods, constructors, or blocks, without the static keyword.
• These variables have different values for each instance (object) of the class.
• Instance variables are created in the heap memory because they are tied to objects.
Syntax
<access modifier> <data type> <variable name> = <value>;
Example - int age;
Code Demonstrating Class variable and Instance Variables
In this example, orgName is a class variable, and name, age are instance variables.
Local Variables
• Local variables are declared within methods, constructors, or blocks.
• They do not have a default initialization, so they must be explicitly initialized before use.
• Local variables can only be accessed within the method, block, or constructor where they are declared.
Syntax:
<access modifier> <data type> <variable name> = <value>;
Constants in Java
In Java, you can declare a variable as a constant using the final keyword. A constant variable cannot be reinitialized after its value is set.
• The final keyword can be applied to variables, methods, and classes:
• A final variable cannot be reassigned.
• A final method cannot be overridden.
• A final class cannot be subclassed.
Syntax:
<access modifier> <static> <final> <data type> <variable name> = <value>;
static and final are optional, but final ensures that the value remains constant.
Example:
final double PI = 3.142; // Constant variable
In this example, PI is declared as a constant and cannot be modified after initialization.