• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Method returns true value but variable not.

 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Test {

int i = getX ( ) ;
int j = 10 ;

int getX ( ) {
return j ;
}

public static void main ( String args [ ] ) {
System . out . println ( new Test ( ) . i + " " + new Test() . getX() );
}
};


Options :

a . Compiler error - can't call getX ( ) before the constructor completes initialization
b . Compiler error - variable j may not have been initialized
c . Compiles fine & prints 10 10
d . Compiles fine & prints 0 10

The correct answer is d

Can anyone explain me.
[ February 28, 2007: Message edited by: Pankaja Shinde ]
 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here when you call the variable i in new Test ( ) . i the variable j is not yet initialized so it returns 0.But when you call the method new Test() . getX()..variable j is initialized so you get 10. A small change in code will give you 10-10 as the answer
 
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So does that imply when... theres no constructor ...the variables are initialized according to the order they are invoked ??
cause on changing the order the output of the program changed...
and if there would have been a constructor then no issues at all it will be called 1st ...
[ February 28, 2007: Message edited by: lavnish lalchandani ]
 
Come have lunch with me Arthur. Adventure will follow. This tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic