0
0
Javaprogramming~5 mins

Variable declaration and initialization in Java

Choose your learning style9 modes available
Introduction

Variables store information we want to use later. Declaration tells the computer about the variable, and initialization gives it a starting value.

When you want to save a number to use in calculations.
When you need to remember a word or sentence in your program.
When you want to keep track of a true or false condition.
When you want to store a value that might change later.
When you want to organize data with a name for easy access.
Syntax
Java
type variableName = value;

type is the kind of data (like int for numbers, String for text).

You can declare a variable first, then give it a value later.

Examples
This creates a number variable named age and sets it to 25.
Java
int age = 25;
This creates a text variable named name and sets it to "Alice".
Java
String name = "Alice";
Here, isSunny is declared first, then given the value true later.
Java
boolean isSunny;
isSunny = true;
This creates a decimal number variable named price and sets it to 19.99.
Java
double price = 19.99;
Sample Program

This program declares and initializes three variables with different types, then prints their values.

Java
public class Main {
    public static void main(String[] args) {
        int age = 30;
        String city = "New York";
        boolean isStudent = false;

        System.out.println("Age: " + age);
        System.out.println("City: " + city);
        System.out.println("Is student: " + isStudent);
    }
}
OutputSuccess
Important Notes

Variable names should be clear and meaningful, like age or city.

Java requires you to specify the type of variable when you declare it.

Once declared, you can change the value of a variable later if needed.

Summary

Declare variables to tell the computer what kind of data you want to store.

Initialize variables to give them a starting value.

Use variables to keep and change information in your program.