Declaration and initialization

Declaration

With the declaration we name a variable and make it known to the compiler. Since each variable name of a data type must be unique, the compiler can also catch the error when trying to declare two variables with the same type and the same name.

Definition

The definition means that a memory area is allocated to a variable. The memory area has a unique address and is used to store values. However, a declaration without definition can also take place. Then both concepts are combined.

Initialization

If we have declared a variable, it has a random value – depending on what is currently in the allocated memory area. Normally you don’t want to work with such random values. Therefore we can use initialization to set the variable to an initial value. Variables should always be initialized to avoid working with a random value.

Code Example

This code defines a Java class called Datatypes that demonstrates the use of various primitive data types in Java, such as byte, short, int, long, double, float, char, boolean, and String. The code also declares and initializes variables for each of these data types, as well as an array of ints.

The main method of the class prints the values of these variables using the System.out.println statement, concatenating the values of the byte, short, int, long, double, float, and char variables with the corresponding string representations, and the value of the boolean variable with either true or false. Finally, it also prints the value of the third element of the myArray array.

public class Datatypes {
    public static void main(String[] args) {
        byte byteNumber = 10;
        short shortNumber = 10000; 
        int integerNumber = 1000000000;
        long longNumber = 10000000000L;
        double doubleNumber = 5.534;
        float floatNumber = 6.767f;
        char symbol = 'c';
        boolean isBoolean= true;
        String charString = "My first string";
        int myArray[] = {16, 24, 35, 41};

        System.out.println(byteNumber + "\n" 
                            + shortNumber + "\n" 
                            + integerNumber + "\n" 
                            + longNumber + "\n" 
                            + doubleNumber + "\n" 
                            + floatNumber + "\n" 
                            + symbol + "\n" 
                            + charString + "\n" 
                            + isBoolean + "\n"
                            + myArray[2]);
    }
}
Output
10
10000
1000000000
10000000000
5.534
6.767
c
My first string
true
35