Variable Scope Part 2

There are 3 main types of variables:

  • Local
  • Parameter
  • Instance

The scope of a variable is the part of the program where the variable can be accessed.

It’s good programming practice to keep the scope of all variables to a minimum.

Snap 2014-04-21 at 21.42.34
Credit: this is a screen shot from slide nerd videos on youtube

The parameter variable val is available inside the orange box.

The local variable i is available inside the blue box

The local variable x is available in the purple box

2 local variables can have the same name providing their scopes don’t overlap.

E.g.

Snap 2014-04-21 at 21.48.49
Credit: this is a screen shot from slidenerd videos on youtube

Instance variable scope

Snap 2014-04-21 at 21.55.01
Credit: this is a screen shot from slidenerd videos on youtube

Instance variable shadowing

Snap 2014-04-21 at 21.59.04
Credit: this is a screen shot from slidenerd videos on youtube

The above is fine as the purple is a instance variable, and the green is a local variable. You can always have local and instance variables with the same name. It’s only when you have 2 instance variables, or 2 local variables that they cannot have the same name.

In the following example:

Snap 2014-04-21 at 22.36.46
Credit: this is a screen shot from slidenerd videos on youtube

the first

System.out.println(name) will be Makarov, but the System.out.println(this.name) will be Vladimir

e.g.

public class ThisKeyword {

	public static void main(String[] args) {
		
		MyClass myClass = new MyClass();
		myClass.showInfo();	
	}
}


class MyClass
{
	String name="James";
	
	public void showInfo(){
		String name="Froggy";		
		System.out.println(name);
		System.out.println(this.name);
	}
}

Outputs:

Froggy
James

Leave a Reply