How does Hello World work in Java without an instance of an object?

advertisements

I'm a newbie to Java and I'm confused about something:

In the simple hello world program in Java, no object is created so how does the class work in the following example?

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


Any variable or method that is declared static can be used independently of a class instance.

Experiment

Try compiling this class:

public class HelloWorld {
    public static int INT_VALUE = 42;

    public static void main( String args[] ) {
        System.out.println( "Hello, " + INT_VALUE );
    }
}

This succeeds because the variable INT_VALUE is declared static (like the method main).

Try compiling this class along with the previous class:

public class HelloWorld2 {
    public static void main( String args[] ) {
        System.out.println( "Hello, " + HelloWorld.INT_VALUE );
    }
}

This succeeds because the INT_VALUE variable is both static and public. Without going into too much detail, it is usually good to avoid making variables public.

Try compiling this class:

public class HelloWorld {
    public int int_value = 42;

    public static void main( String args[] ) {
        System.out.println( "Hello, " + int_value );
    }
}

This does not compile because there is no object instance from the class HelloWorld. For this program to compile (and run), it would have to be changed:

public class HelloWorld {
    public int int_value = 42;

    public HelloWorld() { }

    public static void main( String args[] ) {
        HelloWorld hw = new HelloWorld();
        System.out.println( "Hello, " + hw.int_value );
    }
}