Does every Java program require a class?

Every Java program requires at least one class.

Is this statement always true?

+6
java
source share
5 answers

Yes, you need at least one class to have a program, but no, you do not need any methods (unlike some other answers).

The reason you need a class is because in Java all the code is inside classes. Therefore, in order to have any code, you need a class. However, the code does not have to be in the method. It can also be in initializers. So here is the complete Java program without methods:

class LookMaNoMethods { static { System.out.println("Hello, world!"); System.exit(0); } } 

And it gives ...

 $ javac LookMaNoMethods.java $ java LookMaNoMethods Hello, world! $ 

EDIT: from Java 7, the above code using only a static block and no main method produces any output. The main method is now required. Code without the main method compiles successfully.

+20
source share

The program requires an entry point. The entry point must be a method. In Java, every method must be contained in a class.

This means that every program must have at least one class.

+6
source share

From the point of view of the JVM; Yes. From the point of view of programmers, it can be a class or Enum.

 public enum AAA { AAA; public static void main(final String[] args) { System.out.println("H"); } } 

EDIT: even if you have a class with an empty main method, there are many main classes that work behind the scenes to just run your “empty” class. A list of these classes (about 200 from the java.* Package) can be viewed by setting the -verbose:class JVM parameter.

+6
source share

Yes. In Java, you always need one class with the main function to run the JRE.

+2
source share

Yes, you need at least one class.

0
source share

All Articles