Declaring Variables in Java

Java Program

This tutorial is to show you how to declare variables in Java.

In Java, all variables must be declared before they can be used in the programs. The following is the syntax of variable declaration in Java.

Java - Variable Declaration Syntax

type identifier [ = value ][, identifier [ = value ] ...];

Here the type is the Java supported data types, or the class name, or interface name. The identifier is the name of the variable. To initialize a variable in Java, use equal sign and a value. To declare more than one variable of the same type, use a comma to separate.

Example - Declaring Variables in Java

In the following Java program, it is declaring multiple variables, and some of them include an initialization.

public class Variables {
    public static void main(String args[])
    {
        int x, y, z; // declares three intejers of x, y, and z.
        int a = 4, b, c = 9; // declares intejer a with value 4 and c with value 9 but b not yet initialized

        byte d = 21;
        double pi = 89.14252;
        
        char ch = 'x';
        
        String s = "abc";

        // printing the variables value that have been initialized
        System.out.println("a = " + a);
        System.out.println("c = " + c);
        
        System.out.println("d = " + d);
        System.out.println("pi = " + pi);
        
        System.out.println("ch = " + ch);
        System.out.println("s = " + s);        
        
        // variables x, y, z, and b not yet initialized
        
    }
}

Output

a = 4
c = 9
d = 21
pi = 89.14252
ch = x
s = abc

Learn how to declare variables in Java program and how to initialize them.