user2148463
user2148463

Reputation: 57

Method level scope of variables

I am a beginner in Java and came across these errors while practicing, so I thought of clarifying them instead of trying to memorize the error to avoid them.

public static int gcd(int a, int b) {
  if(a > b) {
    int result = a % b;
  }
  return result;
}

This generates me a cannot find symbol, but I thought I initialize the result as int in the if loops?

public static int gcd(int a, int b) {
  if(a > b) {
    int result = a % b;
    return result;
  }
}

For this, if I return the result in the if loop, is it wrong because it continues looping?

public static int gcd(int a, int b) {
  int result = 0;
  if(a > b) {
    result = a % b;
  }
  return result;
}

The error goes away on declaring result outside of the if loop. Why is that?

Upvotes: 2

Views: 185

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234807

The reason for the first error is that the if statement establishes a new context for variables. The declaration of result is not visible outside the body of the if.

In the second case, the if condition may fail to be satisfied, in which case the function will not execute a return statement. That is also an error, because the function needs to return an int (or throw an exception) for every execution path.

Upvotes: 0

Daniel Imms
Daniel Imms

Reputation: 50189

This is related to the scope of the variable result. When it was inside the if it stopped existing when you left the if (the }).

public static int gcd(int a, int b){
    int result = 0;
    if (a > b) {
        result = a % b;
    }
    return result;
} // result exists until here

public static int gcd(int a, int b){
    if (a > b) {
        int result = a % b;
    } // result exists until here
    return result; // result doesn't exist in this scope
} 

Basically you can only access variables within the blocks of code where they are defined, a block of code is defined by curly braces { ... }.

An alternative implementation of your function could be done without the variable at all.

public static int gcd(int a, int b){
    if (a > b) {
        return a % b;
    }
    return 0;
} 

Upvotes: 4

Bruno Reis
Bruno Reis

Reputation: 37822

Local variables are called local because they can only be seen inside the block they were created in.

A block is any code inside { ... }.

Let's see the blocks you have in your first version:

public static int gcd(int a, int b) { // first block starts here
  if(a>b) { // second block, an inner block, starts here
      int result=a%b;
  } // second block ends here
  return result;
} // first block ends here

So, you create a local variable in the second block, and try to use it outside that block, ie, in the first block. That's what the compiler is complaining about. The variable result kind of disappeared after the second block finished.

Upvotes: 1

Related Questions