Variable Scope

LOCAL VARIABLES & PARAMETER VARIABLES

A local variable is a variable declared in the body of a method.

A parameter variable(s) is/are declared in the method headers

e.g.

class Circle
{
	public double getArea(double radius) // radius us a parameter variable
	{
		double area= 3.14 * radius * radius; // area is a local variable
		return area;
	}
}

when the method runs, the local and parameter variables come to life, when the method exits, they die immediately.

INSTANCE VARIABLES

An object of a class is called an instance on the class. Instance variables will be accessible to all methods in the class where they’re contained.

class Circle
{
	double radius; // this is an instance variable
	
	public double getArea()
	{
		double area= 3.14 * radius * radius;
		return area;
	}
}

… every object has its own copy of instance variables.

e.g.

Circle c = new Circle();
c.radius = 5.2;

this creates a circle object with radius value of 5.2.

Circle d = new Circle();
d.radius = 3.6;

this creates a circle object with radius value of 3.6.

Instance variables do not need to be initialised, but we use a constructor if you want to initialise them.

Instance variables are alive as long as the object is alive.

If instance variables are not initialised, they are given default values:

Numbers are given default 0.
Objects are given null.
Boolean has default of false.

e.g.

class Person{
	
	String name;
	
	public void display(){
		System.out.println(name.length());
	}
}

This will give an error as the object ‘name’ is given a null value. You CANNOT call methods on a reference whose value is null.

With parameter variables, you’re never supposed to change them.

BAD WAY

public void deposit(int amount){
	
	amount = balance + amount;
}

GOOD WAY

public void deposit(int amount){
	
	double newBalance =  balance + amount;
}

Leave a Reply