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!");
}
}
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).
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 );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With