Win a copy of Spring Boot in Practice this week in the Spring forum!
  • 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
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Doubt

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From abHilash's java quiz site:
public class Aquestion
{
private int i = giveMeJ();
private int j = 10;
private int giveMeJ()
{

return j;
}
public static void main(String args[])
{
System.out.println((new Aquestion()).i);
}
}
1. Compiler error complaining about access restriction of private variables of AQuestion.
2. Compiler error complaining about forward referencing.
3. No Compilation error - The output is 0;
4. No Compilation error - The output is 10;
The correct answer is:3
I thought 4 is correct. when I compiled and run it gave the output is: 0. Can someone explain why the output is :0?
Thanks
VR

 
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
VR,
giveMeJ() is called before j is initialized to 10. Hence the method returns the default value of int which is 0. If you swap the call to the method giveMeJ() with the declaration of j, it will print 10!!
Ajith
 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

why sould it take a default value, instead of an assigned value,
eventhough it is assigned after the method call?(if it is able to see the variable declaration,and take the default value, why can't it take the assigned value?)
 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For a good explanation of what is happening hear see the past thread on this same question:
http://www.javaranch.com/ubb/Forum24/HTML/001464.html
In particular read Prabhu's and Maha Anna's responses.
 
reply
    Bookmark Topic Watch Topic
  • New Topic