This question already has an answer here:
I am slowly but surely working my way through java and have gotten a program to work. However, the program I am using has all of the code in the main method and I'd like to use other methods to keep things better organized.
My question is very simple so I will use the simplest of examples. Say I wanted to create a Hello World program like this:
public class HelloWorld {
public static void main(String[] args) {
Test();
}
public void Test(){
System.out.println("Hello World!");
}
}
How do I call Test() correctly in java? The way I have written it creates a compiler error. I am coming from R which would allow something like this.
Thank you.
The method Test() needs to be declared as static, so:
or you can create a new HelloWorld object and then having it call Test():
First, your method should be named
test
(not "Test"). Also, it should be (in this case)static
.Or, you could also write it like so,
See,what you have done with your code is that you have called a non-static method from a static method which is "public static void main(String[] args)" here. Later on,with the time you will come to know that static members are the very first to be called by the compiler and then follows the normal flow of non-static members.
In Java,to call a non-static method,either you need to create a Class object to call a non-static method from the main() method,or you itself declare the non-static method as a static method,which might not be good in every case,but that would simply be called in the main() method as it is!
Correct code(if you want to call non-static methods from a static-method) :-
Alternative code(if you want to call non-staticmethod from a static-method,make the former static) :-