Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are non-static class variables initialiized at runtime and not compile time in Java
    primarykey
    data
    text
    <p>This is an extension of question: <a href="https://stackoverflow.com/questions/9865044/order-of-the-initialization-in-java/">Order of the initialization in Java</a> </p> <p>so in the code block:</p> <pre><code>public class Point { int y = getX(); int x = 42; int getX() { return x; } public static void main (String s[]) { Point p = new Point(); System.out.println(p.x + "," + p.y); } </code></pre> <p>} </p> <p>It outputs <code>42,0</code></p> <p>While the above question was answered by describing the behavior of the Java compiler and runtime, it is still bugging me why the compiler does not bake the initial value of x (42) into the bytecode? I know the values of static variables get embedded into the bytecode since they are class level variables and they dont take up any space in the object memory, but doesn't it make sense to also embed any initial values for class level non-static variables also into the bytecode? That way, the code above will be more in-line with expected behavior, and the instantiation of the object will be quicker I am guessing (since the memory assigned to x will immediately contain 42 hence saving time in parsing the initialization line in the class every time an object of class Point is created)</p> <p>I suspect this might have something to do with the tradeoffs between class bytecode size, object initialization efficiency, and compile time efficiency.</p> <p>I am hoping someone with deep knowledge on Java compiler/runtime can throw some light on this. Knowing how a framework works internally always helps us write better code :-)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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