Will Java Final variables have default values?

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html, chapter “Initializing Instance Members”: The Java compiler copies initializer blocks into every constructor. That is to say: { printX(); } Test() { System.out.println(“const called”); } behaves exactly like: Test() { printX(); System.out.println(“const called”); } As you can thus see, once an instance has been created, the final field has not been definitely assigned, while … Read more

Cannot reference “X” before supertype constructor has been called, where x is a final variable

The reason why the code would not initially compile is because defaultValue is an instance variable of the class Test, meaning that when an object of type Test is created, a unique instance of defaultValue is also created and attached to that particular object. Because of this, it is not possible to reference defaultValue in … Read more

Final variable assignment with try/catch

One way to do this is by introducing a (non-final) temporary variable, but you said you didn’t want to do that. Another way is to move both branches of the code into a function: final int x = getValue(); private int getValue() { try { return Integer.parseInt(“someinput”); } catch(NumberFormatException e) { return 42; } } … Read more

Java : in what order are static final fields initialized?

Yes, they are initialized in the order in which they appear in the source. You can read all of the gory details in The Java Language Specification, §12.4.2. See step 9, which reads: … execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual … Read more

Anonymous-Inner classes showing incorrect modifier

Note that the wording in the JLS of that particular section has changed significantly since then. It now (JLS 11) reads: 15.9.5. Anonymous Class Declarations: An anonymous class is never final (§8.1.1.2). The fact that an anonymous class is not final is relevant in casting, in particular the narrowing reference conversion allowed for the cast … Read more

Does using final for variables in Java improve garbage collection?

Here’s a slightly different example, one with final reference-type fields rather than final value-type local variables: public class MyClass { public final MyOtherObject obj; } Every time you create an instance of MyClass, you’ll be creating an outgoing reference to a MyOtherObject instance, and the GC will have to follow that link to look for … Read more

Making java method arguments as final

As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final. This saves you from declaring another local final variable in the method body: void m(final int param) { new Thread(new Runnable() { public void run() { System.err.println(param); } }).start(); }