How do I use try-with-resources statement?

The try-with-resources statement is introduced in the Java 7. With this new statement we can simplify resource management in our program, also known as ARM (Automatic Resource Management).

This statement is a try statement that declares one or more resources. After the program finish with the resource, it must be closed. The try-with-resources ensures that each resource is closed and the end of the statement.

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

package org.kodejava.basic;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class TryWithResourceExample {
    public static void main(String[] args) {
        try {
            TryWithResourceExample demo = new TryWithResourceExample();
            demo.printStream("F:/tmp/data.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void printStream(String fileName) throws IOException {
        char[] buffer = new char[1024];

        try (InputStream is = new FileInputStream(fileName);
             Reader reader = new BufferedReader(
                     new InputStreamReader(is, StandardCharsets.UTF_8))) {

            while (reader.read(buffer) != -1) {
                System.out.println(buffer);
            }
        }
    }
}

How do I use the instanceof keyword?

To check whether an object is of a particular type (class or interface type) you can use instanceof operator. The instanceof operator is used only for object reference variable. x instanceof y can be read as x is-a y.

The instanceof returns true if the reference variable being tested is of the type being compared to. It will still return true if the object being compared is assignment compatible with the type on the right.

For interface type, an object is said to be of a particular interface type (meaning it will pass the instanceof test) if any of the object’s superclasses implement the interface.

package org.kodejava.basic;

interface Man {
}

public class InstanceofDemo {
    public static void main(String[] args) {
        Body body = new Body();
        Hand hand = new Hand();
        Nail nail = new Nail();
        Shoes shoe = new Shoes();

        if (body instanceof Man) {
            System.out.println("body is a Man");
        }

        if (hand instanceof Man) {
            System.out.println("hand is a Man too");
        }

        if (hand instanceof Body) {
            System.out.println("hand is a Body");
        }

        // it should be return false
        if (hand instanceof Nail) {
            System.out.println("hand is a Nail");
        } else {
            System.out.println("hand is not a Nail");
        }

        if (nail instanceof Man) {
            System.out.println("nail is a Man too");
        }

        if (nail instanceof Hand) {
            System.out.println("nail is a Hand");
        }
        if (nail instanceof Body) {
            System.out.println("nail is a Body too");
        }

        // it should return false, cause Shoes is not implements Man
        if (shoe instanceof Man) {
            System.out.println("shoe is a Man");
        } else {
            System.out.println("shoe is not a Man");
        }

        // compile error. cannot test against class in different
        // class hierarchies.
        //
        //if (shoe instanceof Body) {
        //}

    }

}

class Body implements Man {
}

// indirect implements Man
class Hand extends Body {
}

// indirect implements Man
class Nail extends Hand {
}

class Shoes {
}

The result of the code snippet above:

body is a Man
hand is a Man too
hand is a Body
hand is not a Nail
nail is a Man too
nail is a Hand
nail is a Body too
shoe is not a Man

How do I use the “this” keyword in Java?

Every instance method has a variable with the name this that refers to the current object for which the method is being called. You can refer to any member of the current object from within an instance method or a constructor by using this keyword.

Each time an instance method is called, the this variable is set to reference the particular class object to which it is being applied. The code in the method will then relate to the specific members of the object referred to by this keyword.

package org.kodejava.basic;

public class RemoteControl {
    private String channelName;
    private int channelNum;
    private int minVolume;
    private int maxVolume;

    RemoteControl() {
    }

    RemoteControl(String channelName, int channelNum) {
        // use "this" keyword to call another constructor in the 
        // same class
        this(channelName, channelNum, 0, 0);
    }

    RemoteControl(String channelName, int channelNum, int minVol, int maxVol) {
        this.channelName = channelName;
        this.channelNum = channelNum;
        this.minVolume = minVol;
        this.maxVolume = maxVol;
    }

    public static void main(String[] args) {
        RemoteControl remote = new RemoteControl("ATV", 10);

        // when the following line is executed, the variable in
        // changeVolume() is referring to remote object.
        remote.changeVolume(0, 25);
    }

    public void changeVolume(int x, int y) {
        this.minVolume = x;
        this.maxVolume = y;
    }
}

How do I use the “return” keyword in Java?

The return keyword is used to return from a method when its execution is complete. When a return statement is reached in a method, the program returns to the code that invoked it.

A method can return a value or reference type or does not return a value. If a method does not return a value, the method must be declared void and it doesn’t need to contain a return statement.

If a method declare to return a value, then it must use the return statement within the body of method. The data type of the return value must match the method’s declared return type.

package org.kodejava.basic;

public class ReturnDemo {

    public static void main(String[] args) {
        int z = ReturnDemo.calculate(2, 3);
        System.out.println("z = " + z);

        Dog dog = new Dog("Spaniel", "Doggie");
        System.out.println(dog.getDog());
    }

    public static int calculate(int x, int y) {
        // return an int type value
        return x + y;
    }

    public void print() {
        System.out.println("void method");

        // it does not need to contain a return statement, but it
        // may do so
        return;
    }

    public String getString() {
        return "return String type value";

        // try to execute a statement after return a value will
        // cause a compile-time error.
        //
        // String error = "error";
    }
}

class Dog {
    private String breed;
    private String name;

    Dog(String breed, String name) {
        this.breed = breed;
        this.name = name;
    }

    public Dog getDog() {
        // return Dog type
        return this;
    }

    public String toString() {
        return "breed: " + breed.concat("name: " + name);
    }
}

Sometimes learning Java can be challenging, but the main thing is to remember that you can find any help on our website. Just be dedicated and passionate about what you do. If you are still at university, a pay for essay service EssayWritingService can be of any assistance for you.

How do I invoke superclass constructor?

This example shows you how to use the super keyword to call a superclass constructor. The Female class constructor calls its superclass constructor and initializes its own initialization parameters. The call to the superclass constructor must be done in the first line of the constructor in the subclass.

package org.kodejava.example.fundamental;

public class Human {
    private String gender;
    private int age;

    public Human(String gender) {
        this.gender = gender;
    }
}

To call a superclass constructor we call super(). In the case below we call the superclass constructor with one string variable as a parameter.

package org.kodejava.example.fundamental;

public class Female extends Human {
    private String hairStyle;

    public Female(String hairStyle, String gender) {
        super(gender);
        this.hairStyle = hairStyle;
    }
}

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 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.basic;

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.basic;

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

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

Java Programming Keywords Summary

Here are the summary of the available keywords in the Java programming language. Keywords are reserved words that already taken and internally used by Java, so we cannot create variables and name it using this keyword.

Keyword Meaning
abstract an abstract class or method
assert used to locate internal program errors
boolean the Boolean type
break breaks out of a switch or loop
byte the 8-bit integer type
case a case of a switch
catch the clause of a try block catching an exception
char the Unicode character type
class defines a class type
const not used
continue continues at the end of a loop
default the default clause of a switch
do the top of a do/while loop
double the double-precision floating-number type
Keyword Meaning
else the else clause of an if statement
enum define an enum type
extends defines the parent class of a class
final a constant, or a class or method that cannot be overridden
finally the part of a try block that is always executed
float the single-precision floating-point type
for a loop type
goto not used
if a conditional statement
implements defines the interface(s) that a class implements
import imports a package
instanceof tests if an object is an instance of a class
int the 32-bit integer type
interface an abstract type with methods that a class can implement
long the 64-bit long integer type
Keyword Meaning
native a method implemented by the host system
new allocates a new object or array
null a null reference
package a package of classes
private a feature that is accessible only by methods of this class
protected a feature that is accessible only by methods of this class, its children, and other classes in the same package
public a feature that is accessible by methods of all classes
return returns from a method
short the 16-bit integer type
static a feature that is unique to its class, not to objects of its class
strictfp Use strict rules for floating-point computations
super the superclass object or constructor
switch a selection statement
synchronized a method or code block that is atomic to a thread
this the implicit argument of a method, or a constructor of this class
Keyword Meaning
throw throws an exception
throws the exceptions that a method can throw
transient marks data that should not be persistent
try a block of code that traps exceptions
void denotes a method that returns no value
volatile ensures that a field is coherently accessed by multiple threads
while a while loop type