Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Any variable or method that is declared <strong>static</strong> can be used independently of a class instance.</p> <p><strong>Experiment</strong></p> <p>Try compiling this class:</p> <pre><code>public class HelloWorld { public static int INT_VALUE = 42; public static void main( String args[] ) { System.out.println( "Hello, " + INT_VALUE ); } } </code></pre> <p>This succeeds because the variable <code>INT_VALUE</code> is declared static (like the method <code>main</code>).</p> <p>Try compiling this class along with the previous class:</p> <pre><code>public class HelloWorld2 { public static void main( String args[] ) { System.out.println( "Hello, " + HelloWorld.INT_VALUE ); } } </code></pre> <p>This succeeds because the <code>INT_VALUE</code> variable is both <strong>static</strong> and <strong>public</strong>. Without going into too much detail, it is usually good to avoid making variables public.</p> <p>Try compiling this class:</p> <pre><code>public class HelloWorld { public int int_value = 42; public static void main( String args[] ) { System.out.println( "Hello, " + int_value ); } } </code></pre> <p>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:</p> <pre><code>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 ); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload