• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

static variables

 
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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???
}


}
 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 817
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
He was expelled for perverse baking experiments. This tiny ad is a model student:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic