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 Explanation

LineDescription
1Declares a public class called Datatypes
2Declares a static class called main() of type void. So the method does not expect any returns. The input parameters of the main() method (string[] args) are command-line arguments
3 – 12Declaration and initialization of different variables of different data types
14 – 23Outputs one variable per line
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