In Java, a variable is a container used to store data values. Variables are used to name and store data in a program, allowing you to organize and manipulate the data in different ways.2Java Identifiers
2. Java Identifiers
All Java components require names. The names used for classes, variables, and methods are called identifiers. In Java, there are several rules to remember about identifiers. They are as follows:
- All identifiers should begin with a letter (A to Z or a to z), a currency character ($), or an underscore (_).
- After the first character, identifiers can include any combination of characters.
- Keywords cannot be used as identifiers.
- Most importantly, identifiers are case-sensitive.
- Examples of valid identifiers: age, $salary, _value, __1_value.
- Examples of invalid identifiers: 123abc, -salary.
3. Variable Declaration and Assignment
You must declare all variables before they can be used. A Java variable is declared by specifying the data type followed by the variable name. To assign a value, use the assignment (=) operator followed by the value. Each declaration or initialization statement must end with a semicolon (;). In Java, variable declaration and initialization are two separate steps used to define and assign a value to a variable. They are as follows:
3.1 Variable Declaration
This step defines a variable by specifying its type and name. Declaring a variable reserves memory for it.
Syntax:
type variableName;
Example:
3.2 Variable Initialization
This step assigns a value to a declared variable. A variable must be initialized before it is used; otherwise, it will cause a compile-time error.
Syntax:
variableName = value;
Example:
3.3 Declaration and Initialization Together
You can combine the declaration and initialization of a variable in a single step.
Syntax:
type variableName = value;
Example:
Source Code:
public class Variable_Declaration {
public static void main(String[] args) {
// TODO: Add your code here
String firstName; // Valid identifier for instance variable
int age; // Variable Declaration
firstName = "Alice"; // Variable Initialization
age = 30;
System.out.println(firstName + " is " + age + " years old.");
}
}Result:
Watch the video:
Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

