Over a million developers have joined DZone.

Static Variables and Compilers

DZone's Guide to

Static Variables and Compilers

Pointing out an inconvenience in Java that really shouldn't be there anymore.

· Java Zone ·
Free Resource

Take 60 minutes to understand the Power of the Actor Model with "Designing Reactive Systems: The Role Of Actors In Distributed Architecture". Brought to you in partnership with Lightbend.

I am a long time Java programmer, almost 20 years now. I love this language a lot, and I would like to share an observation.

Consider the below code snippet:

public static final String HELLO_WORLD = "Hello" + WORLD;
public static final String WORLD = "World";

When you try to compile the above code, the Java Compiler will raise an compilation error: "illegal forward reference". This is because the compiler expects the static variable ‘WORLD’ to be defined first before referencing it. In order to compile successfully, the code has to be modified to:

public static final String WORLD = "World";
public static final String HELLO_WORLD = "Hello" + WORLD; 

It would be convenient for Java developers if this sort of sequencing can be eliminated. Java developers are already used to this sort of flexibility when they define methods. When you define Java methods, you don’t have to follow any sequence. Methods defined at the bottom of the class can be referenced by methods in top of the class. In Java, function calls are resolved at runtime, whereas static finals are resolved at compile time. That's what causing this inconvenience. 

Advancements in technology have been progressing at an unbelievable pace. Applications are getting smarter and smarter. Applications are getting into the human mind and are starting to understand how a human is thinking and providing solutions accordingly. In this age of rapid advancement, there are a few things which are frozen in time. One of them is the sequencing of static variables in the Java language. Time for a change?

Learn how the Actor model provides a simple but powerful way to design and implement reactive applications that can distribute work across clusters of cores and servers. Brought to you in partnership with Lightbend.

java ,compiler ,static variable

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}