wood burning stoves
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

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

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: 812
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
I agree. Here's the link: http://aspose.com/file-tools
subject: static variables
It's not a secret anymore!