Home » Java » java – Is it mandatory to declare a function outside the main method?-Exceptionshub

java – Is it mandatory to declare a function outside the main method?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

In Java, when I write:

public class Hello {

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

public static void hello() {
    System.out.println("hello world"); }
}

“Hello world” is printed normally. But when I call the hello() function outside the main methode such as:

public class Hello {

    public static void main(String[] args) {        

    }

    hello()

    public static void hello() {
        System.out.println("hello world"); 
    }
}

Or when I define the function inside the main method such as:

public class Hello {

    public static void main(String[] args) {        

        public static void hello() {
            System.out.println("hello world"); 
        }

        hello();
    }   
}

In both these two last cases I get an error. Does this mean that it is necessary for the function to be defined OUTSIDE the main method but called INSIDE the main method or am I missing something?

How to&Answers: