Methods (Java)

Methods in 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 thought on “Methods (Java)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.