English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Is the value returned by a static method static in Java?

By default, when you return values from a static method, they are neither static values nor instance values, they are just values.

Users who call this method can use them as needed. That is, you can retrieve the value and declare it as static.

However, since you cannot declare variables for the return value of a static method, you need to call it outside the class in the method. The user who calls this method can use them as needed. That is, you can retrieve the value and declare it as static.

Example

Assuming we have a class named Demo-

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 methodsgetObject(), respectivelygetInt()Returns an object and an integer.

We have called these methods twice in the class and method. In this class, we have declared the values returned as static.

In the method, we use them (the values returned by the method) 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 Result

20
300
20
300
Elasticsearch Tutorial