What is the difference between a local variable, an instance field, an input parameter, and a class field?

local variable is defined within the scope of a block. It cannot be used outside of that block.

Example:

if(x > 10) {
    String local = "Local value";
}

I cannot use local outside of that if block.

An instance field, or field, is a variable that’s bound to the object itself. I can use it in the object without the need to use accessors, and any method contained within the object may use it.

If I wanted to use it outside of the object, and it was not public, I would have to use getters and/or setters.

Example:

public class Point {
    private int xValue; // xValue is a field

    public void showX() {
        System.out.println("X is: " + xValue);
    }
}

An input parameter, or parameter or even argument, is something that we pass into a method or constructor. It has scope with respect to the method or constructor that we pass it into.

Example:

public class Point {
    private int xValue;
    public Point(int x) {
        xValue = x;
   }

    public void setX(int x) {
        xValue = x;
    }
}

Both x parameters are bound to different scopes.

class field, or static field, is similar to a field, but the difference is that you do not need to have an instance of the containing object to use it.

Example:

System.out.println(Integer.MAX_VALUE);

I don’t need an instance of Integer to retrieve the globally known maximum value of all ints.

Leave a Comment