Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java's Hello World work without an object instance?

Tags:

java

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!");  
    }  
}
like image 621
webkul Avatar asked Jul 09 '09 10:07

webkul


2 Answers

This doesn't create an instance of HelloWorld because main is a static method. Static methods (and static fields) are related to the type rather than to a particular instance of the type.

See the Java Tutorial page on static/instance members for more details, along with this Stack Overflow question (amongst others).

like image 164
Jon Skeet Avatar answered Oct 20 '22 20:10

Jon Skeet


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 );
    }  
}
like image 21
Dave Jarvis Avatar answered Oct 20 '22 20:10

Dave Jarvis