How do I create a class in Java?

A class is a specification or blueprint from which individual objects are created. A class contains fields that represent the object’s states and methods that defines the operations that are possible on the objects of the class.

The file name that contains the definition of a class is always the same as the public class name and the extension is .java to identify that the file contains a Java source code.

A class has constructors, a special method that is used to create an instance or object of the class. When no constructor define a default constructor will be used. The constructor method have the same name with the class name without a return value. The constructors can have parameters that will be used to initialize object’s states.

Here is a Person.java file that defines the Person class.

package org.kodejava.example.fundamental;

public class Person {
    private String name;
    private String title;
    private String address;

    /**
     * Constructor to create Person object
     */
    public Person() {

    }

    /**
     * Constructor with parameter
     *
     * @param name
     */
    public Person(String name) {
        this.name = name;
    }

    /**
     * Method to get the name of person
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * Method to set the name of person
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Method to get the title of person
     *
     * @return title
     */
    public String getTitle() {
        return title;
    }

    /**
     * Method to set the title of person
     *
     * @param title
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * Method to get address of person
     *
     * @return address
     */
    public String getAddress() {
        return address;
    }

    /**
     * Method to set the address of person
     *
     * @param address
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * Method to get name with title of person
     *
     * @return nameTitle
     */
    public String getNameWithTitle() {
        String nameTitle;
        if (title != null) {
            nameTitle = name + ", " + title;
        } else {
            nameTitle = name;
        }
        return nameTitle;
    }

    /**
     * Method used to print the information of person
     */
    @Override
    public String toString() {
        return "Info [" +
                "name='" + name + ''' +
                ", title='" + title + ''' +
                ", address='" + address + ''' +
                ']';
    }
}

Here is a ClassExample.java file that defines the ClassExample class that use the Person class.

package org.kodejava.example.fundamental;

public class ClassExample {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Andy");
        person.setTitle("MBA");
        person.setAddress("NY City");
        System.out.println(person);

        String nameTitle1 = person.getNameWithTitle();
        System.out.println("Name with title: " + nameTitle1);

        Person person2 = new Person("Sarah");
        String nameTitle2 = person2.getNameWithTitle();
        System.out.println("Name with title 2: " + nameTitle2);
    }
}

How do I use checked and unchecked exception?

By throwing a checked exception, you force the caller to handle the exception in a catch block. If a method throws a checked exception, it must declare that it throw the exception in the method declaration.

All exceptions are checked exceptions, except for those indicated by java.lang.Error, java.lang.RuntimeException, and their subclasses.

Runtime exception are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. Runtime exceptions are those indicated by java.lang.RuntimeException and its subclasses.

RuntimeException are known as unchecked exception. It doesn’t require to declare the unchecked exception in the method declaration.

package org.kodejava.basic;

import java.io.File;
import java.io.IOException;

public class ExceptionExample {
    public static void main(String[] args) {
        // You must catch the checked exception otherwise you get a
        // compile time error.
        try {
            ExceptionExample.checkFileSize("data.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // The unchecked exception doesn't requires you to catch
        // it and it doesn't produce a compile time error.
        ExceptionExample.divide();
    }

    /**
     * This method throws a Checked Exception, so it must declare the
     * Exception in its method declaration
     *
     * @param fileName given file name
     * @throws IOException when the file size is to large.
     */

    public static void checkFileSize(String fileName) throws IOException {
        File file = new File(fileName);
        if (file.length() > Integer.MAX_VALUE) {
            throw new IOException("File is too large.");
        }
    }

    /**
     * This method throws a RuntimeException.
     * There is no need to declare the Exception in method declaration
     *
     * @return a division result.
     * @throws ArithmeticException when arithmetic exception occurs.
     */
    public static int divide() throws ArithmeticException {
        int x = 1, y = 0;
        return x / y;
    }
}

How do I create custom exception class?

You can define your own exception class for your application specific purposes. The exception class is created by extending the java.lang.Exception class for checked exception or java.lang.RuntimeException for unchecked exception. By creating your own Exception classes, you could identify the problem more precisely.

package org.kodejava.basic;

public class CustomExceptionExample {
    public static void main(String[] args) {
        int x = 1, y = 0;

        try {
            int z = CustomExceptionExample.divide(x, y);
            System.out.println("z = " + z);
        } catch (DivideByZeroException e) {
            e.printStackTrace();
        }
    }

    public static int divide(int x, int y) throws DivideByZeroException {
        try {
            return (x / y);
        } catch (ArithmeticException e) {
            String m = x + " / " + y + ", trying to divide by zero";
            throw new DivideByZeroException(m, e);
        }
    }
}
package org.kodejava.basic;

class DivideByZeroException extends Exception {
    DivideByZeroException() {
        super();
    }

    DivideByZeroException(String message) {
        super(message);
    }

    DivideByZeroException(String message, Throwable cause) {
        super(message, cause);
    }
}

How do I throw exceptions in Java?

The exceptions that you catch in a try-catch block must have been raised by a method that you’ve called. You can raise an exception with a statement that consists of the throw keyword, followed by an exception object. This exception object is an instance of any subclass of the Throwable class.

In the example below we have two static methods that throws exception. The first method, throwException() will throw an ArithmethicException when the divider is a zero value integer. The second method, printDate(Date date) will throw a NullPointerException if the date parameter value is null.

package org.kodejava.basic;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ThrowExample {
    public static void main(String[] args) {
        try {
            ThrowExample.throwException();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            ThrowExample.printDate(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void throwException() {
        int x = 6;
        int[] numbers = {3, 2, 1, 0};

        for (int y : numbers) {
            if (y == 0) {
                // Throws an ArithmeticException when about to
                // divide by zero.
                String message = String.format(
                        "x = %d; y = %d; a division by zero.",
                        x, y);
                throw new ArithmeticException(message);
            } else {
                int z = x / y;
                System.out.println("z = " + z);
            }
        }
    }

    public static void printDate(Date date) {
        if (date == null) {
            throw new NullPointerException("Date cannot be null.");
        }
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        System.out.println("Date: " + df.format(date));
    }
}

The output of our code:

z = 2
z = 3
z = 6
java.lang.ArithmeticException: x = 6; y = 0; a division by zero.
    at org.kodejava.basic.ThrowExample.throwException(ThrowExample.java:33)
    at org.kodejava.basic.ThrowExample.main(ThrowExample.java:10)
java.lang.NullPointerException: Date cannot be null.
    at org.kodejava.basic.ThrowExample.printDate(ThrowExample.java:43)
    at org.kodejava.basic.ThrowExample.main(ThrowExample.java:16)

How do I catch multiple exceptions?

If a try block can throw several kind of exceptions, and you want to handle each exception differently, you can put several catch blocks to handle it.

package org.kodejava.basic;

public class MultipleCatchExample {
    public static void main(String[] args) {
        int[] numbers1 = {1, 2, 3, 4, 5};
        int[] numbers2 = {1, 2, 3, 4, 5, 6};

        try {
            // This line throws an ArrayIndexOutOfBoundsException
            MultipleCatchExample.printResult(numbers1);

            // This line throws an ArithmeticException
            MultipleCatchExample.printResult(numbers2);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally block is always executed.");
        }
    }

    /**
     * Divide the given first number by the second number.
     *
     * @param x the first number.
     * @param y the second number.
     * @return the result of division.
     */
    private static int divide(int x, int y) {
        return x / y;
    }

    /**
     * Print the output result of divide operation by calling the
     * divide() method.
     *
     * @param numbers integer arrays of the divided number
     * @throws ArrayIndexOutOfBoundsException when an exception
     *                                        occurs.
     */
    private static void printResult(int[] numbers) {
        int x, z, y = 1;
        for (int i = 0; i < 6; i++) {
            x = numbers[i];
            if (i == 5) {
                y = 0;
            }
            z = MultipleCatchExample.divide(x, y);
            System.out.println("z = " + z);
        }
    }
}

How do I use the throws keyword to declare method exceptions?

The throws keyword is used in method declarations to specify which exceptions are not handled within the method body but rather passed to the next higher level of the program. All uncaught exceptions in a method that are not instances of RuntimeException must be declared using the throws keyword.

In the example below you could see that the getConnection() method can cause a ClassNotFoundException when the driver class cannot be found and an SQLException when it fails to initiate a connection to database.

On the other end, the main() method which call the getConnection() method should catch all the exception throws by the getConnection() method in its body.

package org.kodejava.basic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ThrowsExample {
    public static void main(String[] args) {
        Connection connection = null;

        try {
            // Might throw ClassNotFoundException or SQLException
            // that's why we should catch them.
            connection = getConnection();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally is always executed");
            System.out.println("Close connection");
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.out.println("Sql exception caught");
            }
        }
    }

    /**
     * Get database connection.
     *
     * @return Connection
     * @throws ClassNotFoundException when driver class is not found.
     * @throws SQLException           when database error occurs.
     */
    private static Connection getConnection()
            throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://localhost/kodejava",
                "root", "");
    }
}

Without adding the database driver it will get the following exception:

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:375)
    at org.kodejava.basic.ThrowsExample.getConnection(ThrowsExample.java:40)
    at org.kodejava.basic.ThrowsExample.main(ThrowsExample.java:14)
Finally is always executed
Close connection

How do I handle exceptions using try-catch block?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When an abnormal situation occurs within a method, an Exception object is thrown. This object contains information about the error or unusual problems that occur.

Creating an exception object and handing it to the runtime system is called throwing an exception. If you want to deal with the exceptions where they occur, you can include three kinds of code blocks in a method to handle them. try, catch, and finally blocks.

  • The try block encloses code that may give rise to one or more exceptions.
  • The catch block encloses code that is intended to handle exceptions to a particular type that may be thrown in the associated try block.
  • The code in a finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.
package org.kodejava.basic;

public class ExceptionHandlerExample {

    public static void main(String[] args) {
        int x = 1, y = 0, z = 0;

        try {
            // divide by 0 will throw an exception
            z = ExceptionHandlerExample.divide(x, y);
            System.out.println("z = " + z);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally block is always executed.");
        }
    }

    /**
     * Divide the given first number by the second number.
     *
     * @param x the first number.
     * @param y the second number.
     * @return the result of division.
     * @throws RuntimeException when an exception occurs.
     */
    private static int divide(int x, int y) throws RuntimeException {
        return x / y;
    }
}

Here is what happening when we run the program:

java.lang.ArithmeticException: / by zero
    at org.kodejava.basic.ExceptionHandlerExample.divide(ExceptionHandlerExample.java:28)
    at org.kodejava.basic.ExceptionHandlerExample.main(ExceptionHandlerExample.java:10)
Finally block is always executed.

How do I use the shift right “>>” operator?

The signed shift right operator >> shifts a bit pattern to the right. This operator operates with two operand, the left-hand operand to be shifted and the right-hand operand tells how much position to shift.

Shifting a 1000 bit pattern using the >> operator 2 position will produce a 0010 bit pattern. The signed shift right operator produce a result that equals to dividing a number by 2.

package org.kodejava.basic;

public class SignedRightShiftOperator {
    public static void main(String[] args) {
        // The binary representation of 32 is
        // "00000000000000000000000000100000"
        int number = 32;
        System.out.println("number       = " + number);
        System.out.println("binary       = " +
                Integer.toBinaryString(number));

        // Using the shift right operator we shift the bits
        // four times to the right which resulting the result
        // of "00000000000000000000000000000010"
        int shiftedRight = number >> 4;
        System.out.println("shiftedRight = " + shiftedRight);
        System.out.println("binary       = " +
                Integer.toBinaryString(shiftedRight));
    }
}

The result of the code snippet:

number       = 32
binary       = 100000
shiftedRight = 2
binary       = 10

How do I use the shift left “<<" operator?

The signed shift left operator << shifts a bit pattern to the left. This operator operates with two operand, the left-hand operand to be shifted and the right-hand operand tells how much position to shift.

Shifting a 0010 bit pattern using the << operator 2 position will produce a 1000 bit pattern. The signed shift left operator produce a result that equals to multiplying a number by 2, which double the value of a number.

package org.kodejava.basic;

public class SignedLeftShiftOperator {
    public static void main(String[] args) {
        // The binary representation of 2 is "0010"
        int number = 2;
        System.out.println("number      = " + number);
        System.out.println("binary      = " +
                Integer.toBinaryString(number));

        // Using the shift left operator we shift the bits two
        // times to the left. This will shift the "0010" into
        // "1000"
        int shiftedLeft = number << 2;
        System.out.println("shiftedLeft = " + shiftedLeft);
        System.out.println("binary      = " +
                Integer.toBinaryString(shiftedLeft));
    }
}

The result of the code snippet:

number      = 2
binary      = 10
shiftedLeft = 8
binary      = 1000

How do I use the unary bitwise complement “~” operator?

The unary bitwise complement operator (~) inverts a bit pattern; it can be applied to any of the integral types, making every 0 a 1 and every 1 a 0.

For example, an integer contains 32 bits; applying this operator to a value whose bit pattern is 00000000000000000000000000001000 would change its pattern to 11111111111111111111111111110111.

package org.kodejava.basic;

public class UnaryBitwiseComplementOperator {
    public static void main(String[] args) {
        // An integer type contains 32 bit information.
        // 8 = 00000000000000000000000000001000
        int number = 8;
        System.out.println("number = " + number);
        System.out.println(Integer.toBinaryString(number));

        // Using the ~ operator inverts the number by change the
        // every "0" to "1" and every "1" to "0".
        // 00000000000000000000000000001000
        // 11111111111111111111111111110111
        //
        int invertedNumber = ~number;
        System.out.println("invertedNumber = " + invertedNumber);
        System.out.println(Integer.toBinaryString(invertedNumber));
    }
}

The result of the code snippet:

number = 8
1000
invertedNumber = -9
11111111111111111111111111110111