javaobjectmemorymemory-managementstatic

Are all objects created in java, are static objects in the main method?


In order to access a non-static members/variables of a class you need to first create an object in public static void main(String args[]) method.

Does this mean that all the objects that are created are static?

I need a clear explanation and also I need to know how the memory allocation is done for static methods/variables of a class.

I know this sounds like a naive question, but I need to know about it.


Solution

  • You state this:

    In order to access a non-static members/variables of a class you need to first create an object in public static void main(String args[]) method.

    That is only partiallly true. Yes. You do need to create an instance of a class in order to use its non-static members. But the instance does not need to be created in the main method. Indeed, you don't necessarily need to create any objects in main. (There are other ways to create your application's "primordial" objects ... and indeed, your application may not even have a main.)

    Does this mean that all the objects that are created are static?

    No. For a number of reasons.

    This notion1 of static applies to fields and methods. A static field or method is one that is not a member of a single object (instance). But that doesn't apply to objects (instances) themselves. In Java, objects are always independent entities, and they are never members of something else ... at least at the programming language level.

    For example:

    public class Example {
    
        public static String test;
    
        public static void main(String[] args) {
            test = new String("Hi mum!");
        }
    }
    

    The test variable is static and we assign a reference to a freshly created String object to it. But later on, we could assign the value of test to a non-static variable, or assign a reference to a different object to test. The object that we created is no different to one that we might create in a non-static context.

    I need to know how the memory allocation is done for static methods/variables of a class.

    There are a couple of points of difference between static and non-static fields as far as memory management is concerned:


    1 - The static keyword is also used with nested class declarations, but it means something rather different there. I only mention this for "completeness".

    2 - If an application or framework implements "hot loading", and you don't have "class loader leaks" then classes and their associated statics can be garbage collected. Hence, static fields are not always permanently reachable.