This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static variables" Watch "static variables" New topic
Author

static variables

Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
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

Joined: Mar 02, 2005
Posts: 580

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

Joined: Mar 14, 2003
Posts: 810
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...


Thanks and Regards, Amit Taneja
Soni Prasad
Ranch Hand

Joined: Mar 09, 2005
Posts: 97


output is 5.

Forward referencing problem will occur only if you are using an undefined variable in the right hand side of a expression.


SCJP 1.4, SCBCD 1.3
 
GeeCON Prague 2014
 
subject: static variables