11.7 Variable Scope

Something to pay attention to when dealing with methods is that any variables declared inside of a method (including parameters) can only be used in that method. They are called local variables because they can only be used in their local area. Analyze the code below.
public class VariableScope { public static void main(String[] args) { method1(); // prints 5.0 method2(); // prints 2.0 // System.out.println(a); throws an exception } public static void method1() { double a = 5; System.out.println(a); } public static void method2() { // both variables are called a double a = 2; System.out.println(a); } }
Notice that there is one variable in each method called a. However, each variable a only exists within that method (within the curly braces of that method). This allows us to have variables with the same name, but in different parts of our code. Also notice that you can’t print the variable a in the main method because there is no variable a in the main method.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.