go to previous page   go to home page   go to next page highlighting

Answer:

No, nothing is wrong.

public class UnitTest
{
  
  public static long factorial( int N )
  {
    long fct = 1;
    for ( int j=1; j<=N; j++ )
      fct *= j;
    return fct;
  }
  
  public static void main (String[] args ) 
  {
     int N = 10;
     System.out.println( "factorial of " + N + ": " + factorial( N ) );
  }
}

Scope (Review)

scope of N

The scope of a formal parameter is the section of source code that can see the parameter. The scope of a formal parameter is the body of its method. The scope of the parameter N is the body of its method. The scope of the variable N is the body of main().

So in the above code there is no interference between the N in the main method and the N in factorial().

The main method copies the value 10 into its local variable N. Then, when factorial(N) is executed, the 10 is copied from the local variable into the formal parameter of the called method. The code of the method describes how the parameter is used.

The diagram shows the two different Ns and the scope of each. Refer back to chapter 51 if you are fuzzy about this.


QUESTION 10:

If factorial() changed the value in its N would that affect the one in main() ?


go to previous page   go to home page   go to next page