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);
}
}
}
}
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With