Call a Variable From Another Method in Java

Rupam Yadav Apr 12, 2022 Nov 27, 2020
  1. Call a Static Variable in a Static Method Within the Same Class in Java
  2. Call a Static Variable From a Non-Static Method Within the Same Class in Java
Call a Variable From Another Method in Java

In this tutorial, we will learn how we can call a variable from another method in Java. It depends on the type of the variable and its scope inside the class.

Call a Static Variable in a Static Method Within the Same Class in Java

A variable that is static and declared in the same class can be accessed within the main method and other methods. In the below example, the variable val declared inside the scope of the main method is only available within that scope while the static variable y is accessed inside the other static method.

We can access the scope limited variable to pass it to the method where we intend to access the variable.

public class CallAVariable {
    static int y = 4; //declared inside class scope.
    public static void main(String[] args) {
        String val = "Hello"; //declared inside the scope of main method hence available in main only.

        System.out.println("In Main where static variable y is: "+y);
        callInNormal(val);
      
    }
    public static void callInNormal (String val){
        System.out.println("Value of static variable y in a static method is : "+y +" and String passed is: "+val);
      
    }
}

Output:

In Main where static variable y is: 4
Value of static variable y in a static method is : 4 and String passed is: Hello

Call a Static Variable From a Non-Static Method Within the Same Class in Java

The variable y is static but the method accessing it is non-static. Hence, we need to create an instance of the class to access the method and the non-static variable x.

public class CallAVariable {
    int x = 2; 
    static int y = 6;
  
    public static void main(String[] args) {
        //since the method is non static it needs to be called on the instance of class.
        //and so does the variable x.  
        CallAVariable  i = new CallAVariable();
        System.out.println("In Main where static variable y is: "+y+ " and x is: "+i.x);
        i.callInNormal(i.x);      
      
    }
    public void callInNormal (int x){
      
        CallAVariable i = new CallAVariable();
        System.out.println("Non static variable x is : " +x+" and static variable y is: "+y);
      
    }
}

Output:

In Main where static variable y is: 6 and x is: 2
Non static variable x is : 2 and static variable y is: 6
Author: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn

Related Article - Java Class

Related Article - Java Method