Way2Java

Using Variables from Methods

Using Variables from Methods

Summary

: In this Java tutorial

Using Variables from Methods

, you understand how to call instance and local variables from methods.

Observe keenly the difference of using variables from methods. An object is required to call instance variables but not local. You know, C/C++

global variables

in Java are called as

instance variables

.

We have seen earlier with, Using Methods program, how to use methods in Java, but it was without using instance variables. Now let us use instance variables from methods.

public class VariablesWithMethods
{
  int a = 100;
  public void show()
  {
    int b = 200;                                          // calling instance variable a
    System.out.println("a value from show(): " + a);   
                                                          // calling local variable b
    System.out.println("b value from show(): " + b);    
    a = 300;
  }
  public static void main(String args[])
  {
    VariablesWithMethods vwm = new VariablesWithMethods();
    vwm.show();   
    System.out.println("a value from main(): " + vwm.a);  // prints 300    
  }
}
Output screen of VariablesWithMethods.java

Even though the code looks simple, there is a necessity to explain how vwm.a called from main() method printed 300 and not 100. What are the principles involved and what is going actually inside when using variables from methods?

Java behavior in using variables from methods

To make coding simple, designers share a lot of work which we are supposed to do ourselves. Whenever a method is called with an object, like vwm.show(), the instance variables inside the method are linked with the object implicitly. For this reason, the a called from show() becomes vwm.a. One more principle is, whenever an instance variable is called with an object, a global location is created for vwm.a. This location even though created through show() method, the location can be accessed by any other method, but with vwm object only. The location a is private to object vwm only. This is how encapsulation is maintained. If another object is there like vwm1 and called the show() as vwm1.show(), then there creates a location on the name of vwm1.a and this location is private to vwm1.

Now a value in show() method is changed from 100 to 300. But a is nothing but vwm.a. Earlier value in the location is 100 and now changed to 300. By the time control comes to vwm.a in main() method, the value of vwm.a is already changed. For this reason, vwm.a from main() method prints 300.

To get the concept more clearer, let us write one more program with an additional explanation of data binding, data hiding and encapsulation.

Following topics give more command over variables and methods.

1. Using Local and Instance Variables.

2. Data Types Default Values – No Garbage.

3. Primitive Data Types.

4. Java Drawbacks.