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 determine 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 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.example.fundamental;

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 declare and initialize 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.example.fundamental;

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 variable is variable that 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.example.fundamental;

public class StaticDemo {
    // static variable
    static int x = 12;

    // static variable with final value that never change
    final static int Y = 20;

    // 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 inherited, 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.example.fundamental;

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

    // 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;
    }

    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);
    }
}

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 use to create an instance or object of the class. Every time you create an instance, you must invoked 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.example.fundamental;

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);
    }

}

How do I overload methods in Java?

Method overloading allows a method to use the same name or identifier as the method name as long as the argument list is different. Java can differentiate each method by their method signatures. For example to print some value you can create a print method that accept different kind of objects or values as its parameters.

Overloaded method is differentiated by the number and the type of argument they accept. The print(String string) and print(int number) are distinct and unique due to their argument type.

The compiler does not count a return type as a method differentiator. So it is not legal to create a method with the same name, the same number, the same type of argument but with a different return type.

package org.kodejava.example.fundamental;

public class OverloadedExample {
    public void print(Object object) {
        System.out.println("object = " + object);
    }

    public void print(String string) {
        System.out.println("string = " + string);
    }

    public void print(int number) {
        System.out.println("number = " + number);
    }

    public void print(float number) {
        System.out.println("number = " + number);
    }

    public void print(double number) {
        System.out.println("number = " + number);
    }
}

How do I use the super keyword?

When a class extends from other class, the class or usually called as subclass inherits all the accessible members and methods of the superclass. If the subclass overrides a method provided by its superclass, a way to access the method defined in the superclass is through the super keyword.

package org.kodejava.example.fundamental;

public class Bike {
    public void moveForward() {
        System.out.println("Bike: Move Forward.");
    }
}

In the ThreeWheelsBike‘s moveForward() method we call the overridden method using the super.moveForward() which will print the message from the Bike class.

package org.kodejava.example.fundamental;

public class ThreeWheelsBike extends Bike {
    @Override
    public void moveForward() {
        super.moveForward();
        System.out.println("Three Wheels Bike: Move Forward.");
    }

    public static void main(String[] args) {
        Bike bike = new ThreeWheelsBike();
        bike.moveForward();
    }
}

How do I create an interface in Java?

Inteface only contains methods declaration and all its methods are abstract methods. In its most common form, an interface is a group of related methods with empty bodies. To create an interface, use interface keyword in class definition. The file name of interface always the same with the interface name in class definition and the extension is .java.

The RemoteControl interface defines four move methods and a getPosition() methods. These methods has no bodieds. If a class implements an interface, the class should implements all the contracts / methods defined by the interface.

package org.kodejava.example.fundamental;

public interface RemoteController {
    void moveUp(int n);

    void moveRight(int n);

    void moveDown(int n);

    void moveLeft(int n);

    int[] getPosition();
}

The following snippet show you how to create a class that implements the RemoteController interface.

package org.kodejava.example.fundamental;

public class DummyRemoteControl implements RemoteController {
    private int x;
    private int y;

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

    public void moveUp(int n) {
        x = x + n;
    }

    public void moveRight(int n) {
        y = y + n;
    }

    public void moveDown(int n) {
        x = x - n;
    }

    public void moveLeft(int n) {
        y = y - n;
    }

    public int[] getPosition() {
        return new int[] {x, y};
    }

    public static void main(String[] args) {
        RemoteController control = new DummyRemoteControl(0, 0);
        control.moveDown(10);
        control.moveLeft(5);
        System.out.println("X = " + control.getPosition()[0]);
        System.out.println("Y = " + control.getPosition()[1]);
    }
}

How do I implement interfaces in Java?

To implement an interface, a java class must use implements keyword on its class definition. For example, class A implements interface B. The class definition of class A would look like this:

class A implements B {
}

A class can implements more than one interfaces. For example, class A can implements interface B and interface C:

class A implements B, C {
}

Classes that implements an interface must implements all methods declared in that interface.

package org.kodejava.example.fundamental;

public interface Language {

    String getBirthday();
    String getGreeting();

}

The following class is an English implementation of the Language interface.

package org.kodejava.example.fundamental;

public class English implements Language {
    public String getBirthday() {
        return "Happy Birthday";
    }

    public String getGreeting() {
        return "How are you?";
    }
}

The following class is an Indonesian implementation of the Language interface.

package org.kodejava.example.fundamental;

public class Indonesian implements Language {
    public String getBirthday() {
        return "Selamat Ulang Tahun";
    }

    public String getGreeting() {
        return "Apa kabar?";
    }
}

And here is a snippet that show the interface and classes in action.

package org.kodejava.example.fundamental;

public class LanguageDemo {
    public static void main(String[] args) {
        Language language = new English();
        System.out.println(language.getBirthday());
        System.out.println(language.getGreeting());

        language = new Indonesian();
        System.out.println(language.getBirthday());
        System.out.println(language.getGreeting());
    }
}

How do I extend classes in Java?

Inheritance is one of object oriented programming concepts. This concept allows classes to inherit commonly used state and behavior from other classes. Inheritance is the way to put commonly used states and behaviors into one class and reuse it.

The class that inherits all the attributes from other class is called as sub class. While, the class that inherited is called as superclass. You can use the extends keyword in class definition to inherit from other classes.

When you apply the final keyword to the class declaration you will make the class final, a final class cannot be extended by other class.

For example below we have, a Truck class and a Sedan that derived from a Car class.

package org.kodejava.example.fundamental;

public class CarDemo {
    public static void main(String[] args) {
        Car car = new Car();
        car.setBrand("Honda");
        System.out.println("Brand = " + car.getBrand());

        // The setBrand() and getBrand() is inherited from the Car
        // class.
        Truck truck = new Truck();
        truck.setBrand("Ford");
        System.out.println("Brand = " + truck.getBrand());
        truck.getLoadCapacity();

        // The setBrand(), getBrand() and setNumberOfSeat methods
        // are is inherited from the Car class.
        Sedan sedan = new Sedan();
        sedan.setBrand("Hyundai");
        System.out.println("Brand = " + sedan.getBrand());
        sedan.setNumberOfSeat(2);
        sedan.getGearType();
    }
}

Here the definition of the Car, the Truck and the Sedan classes.

package org.kodejava.example.fundamental;

public class Car {
    private String type;
    private String brand;
    private String model;
    private int numberOfSeat;

    public Car() {
    }

    public Car(String type, String brand, String model) {
        this.type = type;
        this.brand = brand;
        this.model = model;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getNumberOfSeat() {
        return numberOfSeat;
    }

    public void setNumberOfSeat(int numberOfSeat) {
        this.numberOfSeat = numberOfSeat;
    }

    public String getCarInfo() {
        return "Type: " + type
                + "; Brand: " + brand
                + "; Model: " + model;
    }
}
package org.kodejava.example.fundamental;

public class Truck extends Car {
    private int loadCapacity;

    public Truck() {
    }

    public Truck(String type, String brand, String model) {
        super(type, brand, model);
    }

    public int getLoadCapacity() {
        return loadCapacity;
    }

    public void setLoadCapacity(int loadCapacity) {
        this.loadCapacity = loadCapacity;
    }

    @Override
    public String getCarInfo() {
        return "Type: " + getType()
                + "; Brand: " + getBrand()
                + "; Model: " + getModel()
                + "; Load capacity: " + getLoadCapacity();
    }
}
package org.kodejava.example.fundamental;

public class Sedan extends Car {
    private int gearType;

    public Sedan() {
    }

    public int getGearType() {
        return gearType;
    }

    public void setGearType(int gearType) {
        this.gearType = gearType;
    }
}