Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does every program in Java require a class?

Tags:

java

Every Java program requires the presence of at least one class.

Is the above statement always true ?

like image 965
Tony Avatar asked Mar 05 '11 14:03

Tony


People also ask

Do all Java programs need a class?

All Java programs are made of at least one class. The class name must match the file: our file is HelloWorld. java and our class is HelloWorld .

Does every object in Java belong to a class?

Every object belongs to some class. We say that the object is an instance of that class. In object-oriented programming, classes are templates for making objects.


1 Answers

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

The reason you need a class is because in Java, all code is inside classes. So to have any code, you need a class. However, code doesn't necessarily need to be in a method. It can also be in initializers. So, here is a complete Java program with no methods:

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

And that gives...

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

EDIT : From Java 7 the above code with just static block and no main method does not produce any output. Main method is now compulsory. The code with no main method compiles successfully though.

like image 119
rlibby Avatar answered Oct 06 '22 21:10

rlibby