• 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

doubt in variable initialisation

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys
Could anyone explain me the behaviour of this code?


1.public class A {
2.int a=v();
3.int x=1000;
4.int b=v();
5.public void v() {
6.System.out.println("x is"+x);
7.return x;
8. }
9.public static void main(String as[]) {
10.A aobj = new A();
11.}
12.}

when i compile and run this code it first prints x is 0
then it prints x is 1000;
I dont understand how it says x is 0? once the v() method is invoked, directly it goes to that method and i think during this the compiler doesnt have any idea about x.Then how it assumes x to be an integer and gives its default value?
But if i change the line 2 as
int a=x;
it says illegal forward reference.
could anyone explain me why?
Thanx.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check this thread...

https://coderanch.com/t/246397/java-programmer-SCJP/certification/little-help-class
reply
    Bookmark Topic Watch Topic
  • New Topic