How to declare variable in Java

As a Java programmer, I would like to share on how to declare variables in Java. A variable is an item of data used to store state of objects; it has a data type and a name. The data type indicates the type of value that the variable can hold. The variable name must follow rules for identifiers. To declare a variable in Java is as follows:

<data type> <name> [=initial value];

Note: Values enclosed in <> are required values, while those values enclosed in [] are optional. Here is a sample program on how to declare variable in Java:

public class VariableExamples
{
    public static void main( String[] args ){
        //declare a data type with variable name
       double average; 
       int num1;
       int num2;
       int sum;
       num1=3;
       num2=7;
       sum=num1+num2;
       average = sum/2;

      System.out.println(“Average of two numbers: “ + average);
    }
}

The example Java program above declares the following variables: average of data type double, num1, num2, and sum of data type as integer.  The variable num1 is assigned a value of 3, variable num2 is assigned a value of 7, variable sum is assign a formula sum=num1+num2, variable average is assign a formula of average = sum/2, and finally the string “Average of two numbers:” together with the value hold by variable average is printed on the screen using the output command in Java System.out.println.

Some guidelines to follow in declaring variables in Java:

1. It always good to initialize your variables as you declare them.
2. Use descriptive names for your variables. Like for example, if you want to have a variable that contains average, name it as, average and not just some random letters you choose.
3. Declare one variable per line of code just like in the example code above.