• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference b/w referencing a variable and assigning value to a variable  RSS feed

 
palanisamy subramani
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


How a=100; is working fine without defining the variable before to that assignment, and if this is correct means, why System.out,println(a) is not working. Please clarify
Thanks
 
Allan Kiplagat
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

For your first question, the code in static { } does not show any errors because it initializes the values of static variables, in this case a, which has been defined in line 7.

System.out.println(a) does not work because 'a' has been defined as a static variable, meaning its value resides in the 'Test' class. To access the values of static variables, stating the class in which the static variable resides is a must.

In order for System.out.println(a) to work, think about changing 'a' into a local variable defined within the main method.

I hope this helps.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!