Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variables

 
Parameswaran Thangavel
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i didn't follow why it prints 0 instead 5

public class Static
{


static
{
int x=5;
}

static int x,y;
public static void main String(args[])
{
System.out.println(x);//ouput is 0 not 5 why???
}


}
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

i didn't follow why it prints 0 instead 5


Because ur assigning value 5 to the local variable x in static block not to class variable x

If u remove the word int from variable x in the static block then the value will be 5
 
amit taneja
Ranch Hand
Posts: 813
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hii
i still didn't get why we have to remove the int from static block ..

i think code under static block ( i.e declaration and intialization )
are all static so...
why not its intializing at class is compiled...

i may have two answer

1. if we remove int from static block then we are using forward reference to intizalize 5 to x

2 . but if we put int x=5 in static block its overridding by another declaration of int x


what is the correct answer...
remove confustion and give proper explanation pls...
 
Soni Prasad
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


output is 5.

Forward referencing problem will occur only if you are using an undefined variable in the right hand side of a expression.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic