Forward Referencing

Today while I was studying for OCJP certification, I’ve learnt something new called Forward Referencing which yields to assigning a variable before defining it. So such below code will compile and work successfully

public class ForwardReferencingExample {
	static {
		count = 2;
	}

	{
		count = 1;
	}

	public static int count;

	public static void main(String[] args) {
		new ForwardReferencingExample();
		System.out.println(ForwardReferencingExample.count);
	}
}

If we run this code, the output will be 1, if you comment the object creation section, the output will be 2, because non static initializer will be neglected to assign the value. But the below such code will fail to compile, because the static initializer cannot increment and it isn’t the form of reference counting. However, if you remove the static initializer or comment it, non static initializer will increment the count value and perfectly compile and work and print the value

public class ForwardReferencingExample {
	static {
		++count;
	}

	{
		++count;
	}

	public static int count;

	public static void main(String[] args) {
		new ForwardReferencingExample();
		System.out.println(ForwardReferencingExample.count);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *