Comp 110 Local Variables

Local Variables

Local variables are variables that are declared within a method or constructor and then can only be used within that method or constructor in which they were declared.

class Person {

    // Fields
    private int _height;
    private double _weight;
    private String _name;
    private String _gender;

    // Constructor
    public Person(String name, String gender, double height, double weight) {
        _name = name;
        _gender = gender;
        _height = height;
        _weight = weight;
    }

    // Methods
    public String talk() {
        return "My name is " + _name + " and I am a " + _gender;
    }

    public int solveHWproblem() {
        int x = 340;
        int y = 10;
        System.out.println("Solving x + y");
        int z = x + y;
        return z;
     }

}

Let's take a look at the solveHWproblem() method in the above image. 

 Here int x, int y, and int z are all local variables. They were all declared within the solveHWproblem() method and can only be used within the solveHWproblem() method. 

What would happen if we tried to use int x, int y, or int z in the talk() method?

If tried to use int x, int y, or int z from the talk() method, we would not be able to access them because xy, and z are local variables in the solveHWproblem() method. If we wanted to access xy, or z in some other method, such as talk(), we would need to change xy, and z from local variables to fields. 

Another important note on local variables is that the parameters to methods and constructors are also local variables to that method or constructor. In the above image, we can see that the Person constructor has a String name parameter and a String gender parameter. Both name and gender are local variables to that Person constructor and they won't be able to be accessed anywhere else in the class.