Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

final instance variable  RSS feed

 
Ankur kothari
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Final
{
final int x;
public static void main(String args[])
{
final int y;
Final f=new Final();
System.out.println(f.x+""+y);
}
}

when compiled this shows that x and y both must be initialised before use.....but i thought that when an instance of Final is made,x is given a default value of 0. then why does it show that x must be initialised..
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

Please do not post the same question to multiple forums: http://faq.javaranch.com/java/CarefullyChooseOneForum. I have deleted the other copies of this question.
 
pete stein
Bartender
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Per the JLS, chapter 16: "Each local variable (§14.4) and every blank final (§4.12.4) field (§8.3.1.2) must have a definitely assigned value when any access of its value occurs."

I believe that your unassigned final variable is a "blank" final variable.

Much luck and hope this helps.
 
Campbell Ritchie
Marshal
Posts: 55745
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any final field has to be assigned before the constructor for that class completes. And it cannot be assigned twice.
 
Nitish Bangera
Ranch Hand
Posts: 537
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about it... if the JVM were to assign a default value then that value cannot be assigned to any value in the future. Final variables should always be initialised before use be it instance or loacal variables.
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Java Linux
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!