Calling Methods In Java – Hello World Example

Calling Methods In Java – Hello World Example

First, your method should be named test (not Test). Also, it should be (in this case) static.

public static void main(String[] args) {
    test();
}

public static void test(){
    System.out.println(Hello World!);
}

Or, you could also write it like so,

public static void main(String[] args) {
    new HelloWorld().test(); // Need an instance of HelloWorld to call test on.
}

public void test() { //<-- not a static method.
    System.out.println(Hello World!);
}

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) :-

 public class HelloWorld {

 public static void main(String[] args) {
    new HelloWorld().Test();
 }

 public void Test(){
    System.out.println(Hello World!);
 }
}

Alternative code(if you want to call non-staticmethod from a static-method,make the former static) :-

public class HelloWorld {

 public static void main(String[] args) {
   Test();
 }

 public static void Test(){
    System.out.println(Hello World!);
 }
}

Calling Methods In Java – Hello World Example

The method Test() needs to be declared as static, so:

public static void Test(){
        System.out.println(Hello World!);
    }

or you can create a new HelloWorld object and then having it call Test():

public static void main(String[] args){
     HelloWorld foo = new HelloWorld();
     food.Test();
}

Leave a Reply

Your email address will not be published. Required fields are marked *