Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How this is code is getting compiled even though we are using a constant which is defined later?

Tags:

java

In the following code DEFAULT_CACHE_SIZE is declared later, but it is used to assign a value to String variable before than that, so was curious how is it possible?

public class Test  { 

public String getName() { 
return this.name; 
} 

public int getCacheSize() { 
return this.cacheSize; 
} 

public synchronized void setCacheSize(int size) {
this.cacheSize = size; 

System.out.println("Cache size now " + this.cacheSize); 
} 

private final String name = "Reginald"; 
private int cacheSize = DEFAULT_CACHE_SIZE; 
private static final int DEFAULT_CACHE_SIZE = 200; 
}
like image 445
GuruKulki Avatar asked Dec 18 '22 02:12

GuruKulki


1 Answers

From Sun docs:

The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.

If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant

In your code DEFAULT_CACHE_SIZE is a compile-time constant.

like image 79
codaddict Avatar answered Dec 19 '22 16:12

codaddict