Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Reading the answers I found no real test really getting to the point. Here are my 2 cents :</p> <pre><code>public class ConstTest { private final int value = 10; private static final int valueStatic = 20; private final File valueObject = new File(""); private static final File valueObjectStatic = new File(""); public void printAddresses() { System.out.println("final int address " + ObjectUtils.identityToString(value)); System.out.println("final static int address " + ObjectUtils.identityToString(valueStatic)); System.out.println("final file address " + ObjectUtils.identityToString(valueObject)); System.out.println("final static file address " + ObjectUtils.identityToString(valueObjectStatic)); } public static void main(final String args[]) { final ConstTest firstObj = new ConstTest(); final ConstTest sndObj = new ConstTest(); firstObj.printAdresses(); sndObj.printAdresses(); } } </code></pre> <p>Results for first object :</p> <pre><code>final int address java.lang.Integer@6d9efb05 final static int address java.lang.Integer@60723d7c final file address java.io.File@6c22c95b final static file address java.io.File@5fd1acd3 </code></pre> <p>Results for 2nd object :</p> <pre><code>final int address java.lang.Integer@6d9efb05 final static int address java.lang.Integer@60723d7c final file address java.io.File@3ea981ca final static file address java.io.File@5fd1acd3 </code></pre> <p>Conclusion :</p> <p>As I thought java makes a difference between primitive and other types. Primitive types in Java are always "cached", same for strings literals (not new String objects), so no difference between static and non-static members.</p> <p>However there is a memory duplication for non-static members if they are not instance of a primitive type.</p> <p>Changing value of valueStatic to 10 will even go further as Java will give the same addresses to the two int variables.</p>
 

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