Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods inside methods [duplicate]

Tags:

java

methods

Is it syntactically correct to have a method inside the main method in Java? For example

class Blastoff {

    public static void main(String[] args) {

        //countdown method inside main
        public static void countdown(int n) {

            if (n == 0) {
                System.out.println("Blastoff!");
            } else {
                System.out.println(n);
                countdown(n - 1);
            }
        }
    }
}
like image 863
user1940007 Avatar asked Feb 23 '13 20:02

user1940007


1 Answers

No, not directly; however, it is possible for a method to contain a local inner class, and of course that inner class can contain methods. This StackOverflow question gives some examples of that.

In your case, however, you probably just want to call countdown from inside main; you don't actually need its entire definition to be inside main. For example:

class Blastoff {

    public static void main(String[] args) {
        countdown(Integer.parseInt(args[0]));
    }

    private static void countdown(int n) {
        if (n == 0) {
            System.out.println("Blastoff!");
        } else {
            System.out.println(n);
            countdown(n - 1);
        }
    }
}

(Note that I've declared countdown as private, so that it can only be called from within the Blastoff class, which I'm assuming was your intent?)

like image 142
ruakh Avatar answered Oct 09 '22 00:10

ruakh