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().

Which successfully outputted the following:

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)”
Comments are closed.