Question

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

From the above, if we say that MyClass is the class and public static void main(String[] args) is the method, then I would like to know what part of the code would be considered as the Object.

If we say that classes have objects and objects have methods, then in the code above, which part is the object? Is there any object created here?

Was it helpful?

Solution

static methods don't belong to object references but to classes instead. You can execute a static method without creating an instance of the class. Knowing this, the only object references that would be created here would be:

  • String[] args object
  • Every String inside args array
  • "Hello world" String.

Note that args and its contents aren't created by you, the JVM will do it (thanks to Thilo's comment).

OTHER TIPS

In above case no object of your class is created. To do that you need to write:

MyClass myclass = new MyClass();

No object created there.Because that is a main method where the program starts. If it is not a static,otherwise, it would need an instance of the object to be executed.

Static Method no need to create object for execution. When you load the class the static members on the class are loaded automatically by JVM.

Specially for execution in Java the JVM find the main method and execute it from the beginning of execution.

Then, each statement from the main method is executed until the termination point.

In the main method what is String args[] it is an array of objects, which is useful when you need to pass the parameters via command line.

So, finally static method execute on when the class is loaded on JVM. So we don't need instance/object for the main method execution

So when is the main method is loaded on JVM? It's loaded when you initialize to create any objects like this

MyClass myobj = new MyClass();

It calls the default constructor MyClass() and load the class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top