Are values returned by static method are static in java?


Whenever you return values from a static method they are either static nor instance by default, they are just values.

The user invoking the method can use them as he wants. i.e. you can retrieve the values and declare them static.

But, since you cannot declare variables of a method static if you need to declare the vales returned by a method static you need to invoke it in the class outside the methods.

Example

Assume we have a class with name Demo as −

class Demo{
   int data = 20;
   public Demo(int data){
      this.data = data;
   }
   public int getData(){
      return this.data;
   }
}

In the following Java example, we have two methods getObject() and getInt() returning an object and an integer respectively.

We are invoking these methods twice in the class and within a method. In the class we have declared the values returned by them as static.

And in the method we are using them (values returned by the methods) as local variables (obviously non-static).

public class StaticExample{
   static int data = StaticExample.getInt();
   static Demo obj = StaticExample.getObject();
   public static Demo getObject(){
      Demo obj = new Demo(300);
      return obj;
   }
   public static int getInt(){
      return 20;
   }
   public static void main(String args[]) {
      System.out.println(StaticExample.data);
      System.out.println(StaticExample.obj.data);
      StaticExample obj = new StaticExample();
      System.out.println(obj.getInt());
      Demo demo = obj.getObject();
      System.out.println(demo.data);
   }
}

Output

20
300
20
300

Updated on: 05-Aug-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements