Reputation: 1
I'm building a GUI program in Java that uses the BorderLayout. And specifically, it uses only the CENTER, PAGE_END, and LINE_END areas. I have a class for each area, and often they need to share info. My main class and PAGE_END class start out like this:
public class JSudokuSolver extends JFrame {
protected static Dimension sBoardDim = new Dimension(500, 500);
protected static Dimension lineEndDim = new Dimension(200, 500);
protected static Dimension pageEndDim = new Dimension(650, 120);
...
public class PAGE_END_objs {
static Dimension pageEndDim = JSudokuSolver.pageEndDim;
...
Sometimes this works fine; sometimes it doesn't. When it doesn't, I get a null pointer (in this example) when trying to use 'pageEndDim' in the PAGE_END_objs code. Then in Eclipse Neon debug mode, if I hover over 'JSudokuSolver.pageEndDim', I do see the Dimension data. But, if I hover over 'pageEndDim =', I see 'null'.
To me, that looks like the static assignment hasn't happened yet. Yes/no? If yes, when does it happen, and what triggers it? If no, do you have helpful info, I hope? TIA!
Upvotes: 0
Views: 72
Reputation: 2415
Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time. These variables will be initialized first, before the initialization of any instance variables.
Upvotes: 0
Reputation: 1074208
The static
variables for a class will be completely initialized before any code using the class can access them*, in a conforming Java runtime environment.
If you're getting an NPE accessing pageEndDim
, something somewhere is assigning null
to pageEndDim
after the class is loaded. You might consider making those variables final
.
* It gets a bit complicated if initializers rely on one another or you have static
initializer blocks doing the init, but that's not the case here.
Upvotes: 2