Methods (Java)

Methods (Java)

Continuing on with my learnings about Java , today I am discussing methods. Within the public class there is a main method, which can then be used to call on other methods. The other methods can be named and defined in any order and then called by the main method in the order they are required.

——

public class HelloWorld { // Java programs start with a public class named after the file
    public static void main(String[] args) { // the public static void main is then created
        method1(); //calls method1
        method3(); //calls method3 to show that methods can be called in different orders
        method2(); //calls method2
        hello(); //calls hello
    }
    public static void method1(){
        System.out.println("method 1 activated!"); //this line prints the output

    }
    public static void method2(){
        System.out.println("method 2 activated but hopefully coming 3rd!"); //this line prints the output

    }
    public static void method3(){
        System.out.println("method 3 activated but hopefully coming 2nd!"); //this line prints the output

    }
    public static void hello(){
        System.out.println("Finally, Hello World!"); //this line prints the output

    }
}

——

I’ve created 4 methods within the main method and then called them in the order method1(), method3(), method2() and finally hello().

Methods in Java
Methods in Java

Which successfully outputted the following:

Java Method Output
Java Method Output

Currently I see the methods in Java to be very similar to functions within Python, in that they can be defined to complete a task and then called on when needed (possibly multiple times if needed).

One response to “Methods (Java)”

  1. Returning Values From Methods (Java) – Geek Tech Stuff Avatar

    […] my Java adventure continues I look today at returning values from methods. So far the methods I have discussed have completed a task but have not returned any values to the main […]

    Like

Welcome to GeekTechStuff

my home away from home and where I will be sharing my adventures in the world of technology and all things geek.

The technology subjects have varied over the years from Python code to handle ciphers and Pig Latin, to IoT sensors in Azure and Python handling Bluetooth, to Ansible and Terraform and material around DevOps.

Let’s connect