Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

forward refrerences

 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How is it that the following code prints 0?
Why doesn't it throw a compiler error, because of the forward reference to j?

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);
}
}
 
Ransika deSilva
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kedar,
I guess it is because the variable j is refered before it is getting initialized so that it returns the defualt value for the int data type, Hope it make sence.
 
Arunkumar Ayyavu
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Forward references apply only to the variables. It doesn't apply to the methods.

This restriction is done to avoid circular references. For e.g.,
int i = j;
int j = i;
This circular reference issue will not occur in Methods.

But you might ask about this:
private void m1() {m2();}
private void m2() {m1();}
In this example, the compiler doesn't know what the methods do.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you search this forum for "giveMeJ" you will see that this question has come up often. Here's Corey's Tipline Article on the topic.
 
Skool. Stay in. Smartness. Tiny ad:
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!