In Java, declaration and initialization are fundamental steps in working with variables and data types.
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 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.
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;
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;
Here are some examples for different types of variables:
// Declaration
int age;
float height;
// Initialization
age = 25;
height = 5.9f;
// Declaration and Initialization
char initial = 'A';
boolean isMarried = false;
// 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};
Default Values:
null
.Scope:
Final Variables:
final
keyword, it can only be assigned once.final int maxAge = 100;
Type Compatibility:
int age = 25; // Correct
// int age = 25.5; // Incorrect: 25.5 is a double