- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Java static method
- Are static methods inherited in Java?
- What are the restrictions imposed on a static method or a static block of code in java?
- Are static local variables allowed in Java?
- What are static imports in java? Example.
- What are Class/Static methods in Java?
- Interface variables are static and final by default in Java, Why?
- Static method in Interface in Java
- Static vs. Non-Static method in C#
- Are the values of static variables stored when an object is serialized in Java?
- When and where static blocks are executed in java?
- What are static members of a Java class?
- Assigning values to static final variables in java
- How to call a non-static method of an abstract class from a static method in java?
- Why main() method must be static in java?
