Functions/Methods in Java

Functions in Java are very common and are used very much. Functions are called reusable blocks of code. For example, writing a block/statement of code which can be used again and again by writing it once rather than writing it every time for the same thing to happen. Here is a normal function within Java

public class Main {

    public static void main(String[] args) {
        add(5, 6);
    }

    private static void add(double valueOne, double valueTwo) {
        System.out.println(valueOne + valueTwo);
    }

}

Output

11.0

Challenge

Try making a calculator using functions

Within the above Java code we have the following elements

  • Line 3 – 5: Main method
    • The main method is where execution is performed. All the methods have to be called within the main method
  • Line 4: Function/Method calling
    • Method calling is the process in which a method is called by its name anywhere in a class. In the above example, we are calling the add function with its name.
  • Line 7 & 4: Function/Method Parameters & Arguments
    • Method parameters are a way of passing dynamic data to a method. If parameters are passed then arguments (values) are essential when the method is called. Take a look at the structure below. The value (5, 6) can be anything related to the Double Datatype.
  • Line 7 – 9: Function/Method
    • A simple function which adds and prints out the result to the console.

Here is the basic structure of a function

A simple function in Java consists of the following elements:

  1. Access modifier –
  2. static keyword
  3. Return Type
  4. Parameters (optional)
  5. Body statement

Types of functions in Java

  1. Static methods
  2. Instance methods
    1. Accessor methods
    2. Mutator methods

Static methods/functions:

A static method in Java is a method which doesn’t require an object creation for its execution. Following is a static method within Java.

public class Main {

    public static void main(String[] args) {

        // Saving the return value from the function
        // There is no need to create an object to access the function
        double result = calculate(5, 100, "+");
        if (result == 0) {
            System.out.println("Not an operation");
        } else if (result == 1){
            System.out.println("Cannot divide to 0");
        } else {
            System.out.println("Calculated result to: " + result);
        }

    }

    @Contract(pure = true)
    private static double calculate(double valueOne,
                                    double valueTwo,
                                    @NotNull String operation) {
        switch (operation) {
            case "+":
                return valueOne + valueTwo;
            case "-":
                return valueOne - valueTwo;
            case "*":
                return valueOne * valueTwo;
            case "/":
                if (valueOne == 0 || valueTwo == 0) {
                    return 1;
                } else {
                    return valueOne / valueTwo;
                }
            case "%":
                return valueOne % valueTwo;
            default:
                return 0;
        }
    }
}

Output

Calculated result to: 105.0

Challenge

Try converting the whole calculate function into multiple functions in a way that every arithmetic operation has its own function.

Instance methods/functions

Instance methods are invoked through an instance variable of a class. Object creation is a must to access the function if the function is not static. For example, let’s convert the calculate static method into an instance method.

public class Main {

    public static void main(String[] args) {

        /*
        * Saving the return value from the function
        * We need to create an object of the current class
        * to access the function
        */

        Main mainClass = new Main();
        double result = mainClass.calculate(5, 100, "+");
        if (result == 0) {
            System.out.println("Not an operation");
        } else if (result == 1){
            System.out.println("Cannot divide to 0");
        } else {
            System.out.println("Calculated result to: " + result);
        }

    }

    @Contract(pure = true)
    private double calculate(double valueOne,
                                    double valueTwo,
                                    @NotNull String operation) {
        switch (operation) {
            case "+":
                return valueOne + valueTwo;
            case "-":
                return valueOne - valueTwo;
            case "*":
                return valueOne * valueTwo;
            case "/":
                if (valueOne == 0 || valueTwo == 0) {
                    return 1;
                } else {
                    return valueOne / valueTwo;
                }
            case "%":
                return valueOne % valueTwo;
            default:
                return 0;
        }
    }
}

Output

Calculated result to: 105.0

Challenge

Try shifting the calculate function into another class and access it in the Main class

In the above example on line 11, an Object is created of the current class and on line 12 using the instance variable of the object the function within the class is accessed. In the world of Object Oriented Programming, there is a concept called POJO class which stands for Plain old Java object class. To make a POJO class following content are a must:

  1. Variables
  2. Constructors / Parameterized Constructors
  3. Getter & Setters also known as Accessor & Mutator methods

We will be talking about Accessor / Mutator methods a.k.a Getters / Setters. They are simple as they are pronounced, getter methods are used to get the data and setter methods are used to set the data. There are tools within IntelliJ which can be used to construct a POJO class. Following is a POJO class

public class User {

    // Assigning variables along their data types
    private String id;
    private String name;
    private String email;
    private String address;
    private boolean emailVerified;
    private long contact;

    // Empty Constructor
    public User() {
    }

    // Parameterized Constructor
    public User(String id, String name, 
                String email, String address, 
                boolean emailVerified, long contact) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.address = address;
        this.emailVerified = emailVerified;
        this.contact = contact;
    }

    /*
    * Below are all Getters and Setters
    */
    
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public boolean isEmailVerified() {
        return emailVerified;
    }

    public void setEmailVerified(boolean emailVerified) {
        this.emailVerified = emailVerified;
    }

    public long getContact() {
        return contact;
    }

    public void setContact(long contact) {
        this.contact = contact;
    }
}

Do you have to write all this? No, within IntelliJ there are tools provided which can generate syntax. Use the Alt + Ins keyboard shortcut to generate Constructors, Getters & Setters but there is a condition before you start generating syntax. You have to write down all the required variables along with their Datatypes. After writing the variables use the shortcut to display the Generate menu.

Through the generate menu, create constructors and Getter and Setter for the variables required by selecting them within the list when generating a constructor or getters & setters.

Challenge

Try creating a POJO class and implementing it within a function

Related

  • Constructors
  • Access Modifiers
  • Return Types