How do I declare and initialize variable?

Variable is a field in which object store its state. It also an allocations for the placement of data in memory. When the statement of variable declaration is compiled, some bytes of memory will be allocated for the variable. The size is determined by the type of variable.

One variable definition is able to store data only of one particular type. Before it can use, the variable must be declared. The name and type of variable must be specified in variable declaration. If you want the variable to have an initial value, you must specify your own value in the declaration.

You can assign a value into variable by using an assignment statement. The assignment operator is =.

package org.kodejava.basic;

public class VariableExample {
    // declares a double variable number1 and total
    private double number1, total;

    // declares a double variable and initializes its value to 10000
    private double number2 = 1000;


    public static void main(String[] args) {
        VariableExample ve = new VariableExample();

        // assigns a value to variable number1
        ve.number1 = 500;

        // assigns the calculation result of number1 + number2 to 
        // total
        ve.total = ve.number1 + ve.number2;
        System.out.println(ve.total);
    }
}

How do I declare and initialize local variable?

Local variables are variables that are not fields of a class. A function or method often store its temporary state in local variables. Local variables only visible to the methods in which they are declared.

Local variables must be declared and initialized before it used for the first time. Local variables will not get a default value if you do not initialize it and could cause a compile-time error.

package org.kodejava.basic;

public class LocalVariableExample {
    // it's okay if total variable does not initialize.
    // it will initialize with default value = 0.
    int total;

    public static int add() {
        // this will cause compile-time error if does not initialize
        int x = 1, y = 2;

        // z is assigned by the calculation result of x + y
        int z = x + y;
        return z;
    }

    public static void main(String[] args) {
        LocalVariableExample lve = new LocalVariableExample();
        // assigns total with the result of add() method execution
        lve.total = add();
        System.out.println("total= " + lve.total);
    }
}

How do I create static variables in Java?

Class variables or static variables are variables that are declared with static modifier. A given class will have only one copy of each of its static variables, regardless of how many times the class has been instantiated.

If the value of a static variable is changed, the new value is available equally in all instances of the class. The final keyword could be added to indicate the value of static variable will never change.

If you try to assign a new value to final variable, you will get a compile error.

package org.kodejava.basic;

public class StaticDemo {
    // static variable with final value that never change
    final static int Y = 20;
    // static variable
    static int x = 12;
    // non-static variable
    int z;

    public static void main(String[] args) {
        StaticDemo sd0 = new StaticDemo();

        System.out.println("x before update = " + StaticDemo.x);
        System.out.println("y= " + StaticDemo.Y);

        sd0.z = StaticDemo.x + StaticDemo.Y;
        System.out.println("z= " + sd0.z);

        StaticDemo.x = 15;
        System.out.println("x after update = " + StaticDemo.x);

        StaticDemo sd1 = new StaticDemo();
        StaticDemo sd2 = new StaticDemo();
        StaticDemo.x = 20;

        System.out.println("StaticDemo.x = " + StaticDemo.x);
        System.out.println("sd0 = " + sd0.getX());
        System.out.println("sd1 = " + sd1.getX());
        System.out.println("sd2 = " + sd2.getX());

        //
        // try to assign value to final variable, it will cause a
        // compile time error
        //
        // StaticDemo.Y = 30;
    }

    public int getX() {
        return StaticDemo.x;
    }
}

Here is the output printed by the program:

x before update = 12
y= 20
z= 32
x after update = 15
StaticDemo.x = 20
sd0 = 20
sd1 = 20
sd2 = 20

How do I use the final keyword in Java?

The final modifier is used to mark a class final so that it cannot be extended, to prevent a method being overridden, and to prevent changing the value of a variable. Arguments of a method if declared as final is also can not be modified within the method.

package org.kodejava.basic;

public class FinalExample {
    // breed is declared final.
    // can't change the value assigned to breed
    public final String breed = "pig";
    private int count = 0;

    public static void main(String[] args) {
        FinalExample fe = new FinalExample();
        // assign a value to breed variable will cause a
        // compile-time error
        //
        // fe.breed = "dog";

        int number = fe.count(20);
    }

    // sound() method is declared final, so it can't be overridden
    public final void sound() {
        System.out.println("oink oink");
    }

    // number parameter is declared final. can't change the value
    // assigned to number
    public int count(final int number) {
        // assign a value to number variable will cause a
        // compile-time error
        //
        // number = 1;

        count = +number;
        return count;
    }
}

final class SubFinalExample extends FinalExample {

    // try to override sound() method of superclass will cause a
    // compile-time error
    //
    // public void sound() {
    //     System.out.println("oink");
    // }
}

// try to inherit a class that declared final will cause a
// compile-time error
//
class OtherFinalExample extends SubFinalExample {
}

How do I create constructors for a class?

Every class in Java has a constructor. constructor is a method that is used to create an instance or object of the class. Every time you create an instance, you must invoke a constructor.

If you do not create a constructor method of your class, the compiler will build a default one. A default constructors is a constructor that accept no argument.

Things to be noted when you declare a constructor:

  • Constructor must have the same name as the class in which they are declared.
  • Constructor can’t have a return type.
  • Constructor can have access modifier.
  • Constructor can take arguments.
  • Constructor can’t be marked static.
  • Constructor can’t be marked final or abstract.
package org.kodejava.basic;

public class ConstructorDemo {
    private String arg;
    private int x;
    private int y;

    public ConstructorDemo() {
    }

    public ConstructorDemo(String arg) {
        this.arg = arg;
    }

    public ConstructorDemo(int x) {
        this.x = x;
    }

    public ConstructorDemo(int x, int y) {
        this.y = y;
    }
}

class RunConstructor {
    public static void main(String[] args) {
        // Change the default constructor from private to public in
        // the ConstructorDemo class above then call the statement 
        // below. It will create an instance object cons0 without 
        // any error.
        ConstructorDemo cons0 = new ConstructorDemo();

        // Change the default constructor back to private, then call 
        // the statement below. ConstructorDemo() is not visible 
        // because it declared as private.
        ConstructorDemo cons1 = new ConstructorDemo();

        // invoke Constructor(String arg)
        ConstructorDemo cons2 = new ConstructorDemo("constructor");

        // invoke public Constructor(int x)
        ConstructorDemo cons3 = new ConstructorDemo(1);

        //invoke Constructor(int x, int y)
        ConstructorDemo cons4 = new ConstructorDemo(1, 2);
    }

}