Variable Scope

Contact Us or call 1-877-932-8228
Variable Scope

Variable Scope

The variable scope rules are similar to those in C++.

Variables can be declared at any point in your code, not just at the top of a block:

  • Local variables (those within methods) are not visible to any code that precedes the declaration.
  • Object elements are visible to any code within the object, regardless of the order of declaration.

Variables declared within a set of curly braces cease to exist after the closing brace has been reached (it is said that they go out of scope); therefore, local variables exist only within that method.

Variables can be declared in the control portion of a for loop, and will exist for the duration of the loop

Parameters to a method are local variables within that method

It is legal to use the same variable name in different scopes, as long as the two scopes have no irresolvable conflicts. Some explanation:

  • Non-overlapping scopes. For example, two different methods could each have a local variable called firstName.
  • Overlapping scopes. It is valid for a method to have a variable whose name conflicts with a property name for that class - in that case, the local variable hides the property, but there is a special syntax that allows the method to access the property; we will cover this later.
  • It is legal for a method and a field of a class to have the same name, although it is not considered a good practice to do so.
  • An example of an irresolvable conflict is declaring a local variable within a block when the same name is already in scope in that method as a local variable.

Code Sample:

public class MethodExample {
  public static void sayHello() {
  public static void showNumber(int number) {
    System.out.println("The number is: " + number);
  public static int calculateSum(int num1, int num2) {
    int answer = num1 + num2;
    return answer;
  public static void main(String[] args) {
    int b = calculateSum(4, 6);
    System.out.println("The sum of 4 and 6 is:" + b);
    b = calculateSum(4, 6) / 2;
    System.out.println("That divided by 2 is: " + b);

We will cover the concept of static elements later, but, for now, since main is static, the methods it calls must be static as well