Skip to main content

What are the forward reference rules?

Using an instance variable before its declaration is called a forward reference. If an instance variable tries to forward reference another instance variable during initialization, the result in a compile-time error.
Java Language Specification designs the following restrictions to catch, at compile time, circular or otherwise malformed initializations.

8.3.2.3 Restrictions on the use of Fields during Initialization in Java Language Specification

The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
  • The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
  • The usage is not on the left hand side of an assignment.
  • The usage is via a simple name.
  • C is the innermost class or interface enclosing the usage.
If the declaration of a member does not precede a use of that member, and the above conditions are met, a compile-time error occurs(Warn about problematic forward references).
The last sentence is not the original one in the current specification. It comes from the above bug report. And most of people had been confused by the original one. Please check the above bug report link.
Let's take a look at the examples listed in 8.3.2.3 Restrictions on the use of Fields during Initialization in Java Language Specification:
class Program {
    int i = j; // compile-time error: incorrect forward reference
    int j = 1;
}
let's try to map these restrictions described in the above.
  • Rule 1: The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
    Yes, "int i = j;" is instance variable initializer.
  • Rule 2: The usage is not on the left hand side of an assignment.
    Right. The j is on the right hand side of an assignment.
  • Rule 3: The usage is via a simple name.
    Yes. "int i = j;" and j is a simple name.
  • Rule 4: C is the innermost class or interface enclosing the usage.
    Yes. The innermost class Program is enclosing this reference j.
All restrictions are passed and the declaration of instance variable j should to precede a use of it by the instance variable i. But we did not. Therefore, a compile time error occurs.
The following example compiles without error:
class Program {
    Program() { k = 2; }
    int j = 1;
    int i = j;
    int k;
}
because the usage of k variable is in the constructor and does not match the first restriction.
These restrictions are designed to catch, at compile time, circular or otherwise malformed initializations. Thus, both:
class Z {
 static int i = j + 2; 
 static int j = 4;
}
and:
class Z {
 static { i = j + 2; }
 static int i, j;
 static { j = 4; }
}
result in compile-time errors.
The static initializer expressions are executed in textual order. In the above case, the static initializer block: static{i=j+2;} tries to read the value of j before it has been declared. Hence the compile-time error.

Getting Around the Forward Reference Rule

Accesses by methods are not checked by the forward reference rule, that is a way you could inadvertently (or purposefully) circumvent the compiler's preventative restrictions. However, the value of the forwarded variable will be zero, false, or null, depending on the type of the variable.
class Z {
 static int peek() { return j; }
 static int i = peek();
 static int j = 1;
}
class Program {
 public static void main(String[] args) {
  System.out.println(Z.i);
 }
}
produces the output:
0
because the variable initializer for i uses the class method peek to access the value of the variable j before j0. As a result, peek returns zero, and i is initialized to zero. has been initialized by its variable initializer, at which point it still has its default value that is
 

Comments

Popular posts from this blog

Java Health Center - Overview and Features

This video highlights the features available in Health Center. Health Center is a low-processor and memory usage diagnostic tool for monitoring the status of a running IBM Java Virtual Machine (JVM). Health Center provides live information and recommendations in each of the following areas: - Classes: information about classes being loaded - Environment: details of the configuration and system of the monitored application - Garbage Collection: information about the Java heap and pause times - Locking: information about contention on inflated locks - Profiling: sampling profile of Java methods including call paths

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag...

Java Garbage Collection

Explain Garbage collection mechanism in Java? Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic pro...