"Automation is not about replacing jobs; it's about empowering people to do more meaningful work." — Unknown

Variable Declaration and Initialization

Estimated reading: 1 minute 9 views

In Java, variables are used to store data values. To use a variable, you need to declare it (specify its type and name) and initialize it (assign a value).

Variable Declaration

The declaration involves specifying the data type and variable name.

Syntax:

				
					dataType variableName;

				
			

Example:

				
					int age;      // Declares an integer variable 'age'
double salary; // Declares a double variable 'salary'

				
			

Variable Initialization

After declaring a variable, it must be initialized by assigning a value.

Syntax:

				
					variableName = value;

				
			

Example:

				
					age = 25;     // Initializes 'age' to 25
salary = 50000.50; // Initializes 'salary'

				
			

Combining Declaration and Initialization

You can declare and initialize a variable in one line.

Syntax:

				
					dataType variableName = value;

				
			

Example Code:

				
					public class VariableExample {
    public static void main(String[] args) {
        int age = 25;
        double salary = 50000.50;
        boolean isActive = true;
        char grade = 'A';
        
        System.out.println("Age: " + age);
        System.out.println("Salary: " + salary);
        System.out.println("Is Active: " + isActive);
        System.out.println("Grade: " + grade);
    }
}

				
			

Output:

				
					Age: 25
Salary: 50000.5
Is Active: true
Grade: A

				
			

Best Practices

  • Use meaningful names (e.g., employeeSalary).
  • Initialize variables before using them.
  • Use final for constants (e.g., final double PI = 3.14).

Leave a Comment

Share this Doc

Variable Declaration and Initialization

Or copy link

CONTENTS