Is it necessary to create a Java class everytime?

Can I just create the program directly the way I do it in other languages?

No.

I mean is the concept of class necessary in Java?

Yes. Every method, field etc is always in a class (or interface). Yes, that's an overhead for tiny programs - but for larger programs, the impact is pretty tiny.

As ever, use the right tool for the job - if you want a script of a few lines, use a scripting language. If you want more structure and organization, then you should expect a bit of "ceremony" to go with that.


Java requires every function/method to be defined in a class. That includes the main method.

The restriction is not imposed by all object-oriented languages. In some cases the constraint is lifted merely as a convenience (i.e. Python, Ruby). Some languages, like JavaScript and Lua, provide OOP features through a prototype-based mechanism. Java enforces OOP with a class system, so you may hear it referred to as a class-oriented language.


While you do have to create a class, the question specifically asks if you have to create a class for your program and a main class to call it. The answer to that is "no".

You can create a single class with a main method and have your logic inside that if you want a very minimal program. Something like this:

public class MyClass {
    public static void main(String[] args)  {
        // Do Something here
    }
}

Tags:

Java

Oop