Declaration and initialization

In Java, declaration and initialization are fundamental steps in working with variables and data types.

Declaration

Declaration is the process of defining a variable by specifying its type and name. When you declare a variable, you are essentially telling the Java compiler about the variable’s existence and the type of data it can hold. The syntax for declaring a variable is:

type variableName;

For example:

int number;
double price;
boolean isAvailable;

Initialization

Initialization is the process of assigning an initial value to a variable at the time of declaration or later in the code. This can be done in a single step (combined with the declaration) or separately.

Initialization at Declaration

You can initialize a variable at the time you declare it. This is often done to ensure that the variable starts with a known value. The syntax for this is:

type variableName = initialValue;

For example:

int number = 10;
double price = 19.99;
boolean isAvailable = true;

Separate Initialization

You can also declare a variable first and initialize it later in your code. This might be necessary when the initial value is not available at the time of declaration.

For example:

int number;
number = 10;

double price;
price = 19.99;

boolean isAvailable;
isAvailable = true;

Examples of Declaration and Initialization

Here are some examples for different types of variables:

  1. Primitive Data Types:
// Declaration
int age;
float height;

// Initialization
age = 25;
height = 5.9f;

// Declaration and Initialization
char initial = 'A';
boolean isMarried = false;
  1. Reference Data Types:
// Declaration
String name;
int[] numbers;

// Initialization
name = "John Doe";
numbers = new int[10]; // Array of 10 integers

// Declaration and Initialization
String greeting = "Hello, World!";
int[] scores = {95, 85, 75, 65, 55};

Important Points to Remember

Default Values:

  • Primitive types have default values if not explicitly initialized (e.g., 0 for integers, false for boolean).
  • Reference types have a default value of null.

Scope:

  • The scope of a variable declared inside a block (e.g., within a method) is limited to that block.
  • Class-level variables (fields) can be accessed throughout the class.

Final Variables:

  • If a variable is declared with the final keyword, it can only be assigned once.

final int maxAge = 100;

Type Compatibility:

  • The type of the variable must match the type of the value assigned to it.

int age = 25; // Correct
// int age = 25.5; // Incorrect: 25.5 is a double