• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Bear Bibeault
  • Liutauras Vilda
  • Devaka Cooray
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

Initializers

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
}
The output is 0 in this case;

public class AQuestion
{
private int i = j;
private int j = 10;
public static void main(String args[])
{
System.out.println((new AQuestion()).i);
}
}
& a compiler error in this second case. In this case it can print 0, b'coz, first, i.e. b4 executing the constructor, the member variables R initialized to 0.
Pls explain
Thanks
kanchan

 
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first one is executed at runtime, and therefore the JVM knows that variable K exists; but it has not been initialized yet.
The second one is determined at compile time. However, variable j must be declared and assigned a value before it is used.
j = 10;
i = j;
 
Because those who mind don't matter and those who matter don't mind - Seuss. Tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!