Java mini scopes inside methods

You can create mini scopes inside single Java method. One purpose can be to reuse variable names especially if we need to test or practice over some code.

public class MainClassInternalScopeInsideMethod {
    public static void main(String[] args) {
        int a = 10;
        // This is internal scope inside method
        {
            // We can have same naming for variables inside scope
            // Also inside this scope we can use method variables like "a"
            int b = 10;
            int res = a + b;
            System.out.println("First scope here b is 10: a + b = " + res );
        }

        // This is another internal scope inside method
        {
            int b = 40;
            int res = a - b;
            System.out.println("Second scope here b is 40: a - b = " + res );
        }
    }
}

Output:

First scope here b is 10: a + b = 20
Second scope here b is 40: a - b = -30

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.