Wednesday 14 March 2018

Can we call non-static method from static method in java?



Suppose we are writing a code where we intend to call any non-static method from within a method that is declared static

Since main() method is static so lets try to call any non static method or variable from within main method.

See the code snippet below where duplicateString  is being called within main method. 


Do you think this code snippet will compile and execute normally? 


package String_Programs;

public class DuplicateString {
      
       public void duplicateString(String str){
           System.out.print(str);
       }

       public static void main(String[] args) {
              duplicateString("This is This and That is This");

       }

}

OUTPUT:
Compile time error

In this case at you will get red underline under duplicateString called within main( ) method in eclipse. Bring your cursor on the method name and you will see this message - 'Cannot make a static reference to the non-static method duplicateString(String) from the type DuplicateString'



Calling non-static method from a static method directly is not allowed in java

How to solve the compile time error?

1. Declare the method to be called as static

You need to declare the duplicateString(String str) method static as shown below.
public static void duplicateString(String str)

Lets re-write our code again.



package String_Programs;

public class DuplicateString {
      
       public static void duplicateString(String str){
             
       }

       public static void main(String[] args) {
              duplicateString("This is This and That is This");

       }

}

OUTPUT:
This is This and That is This



2. Create the instance of the class and then call the method

We have shown an example in the below screenshot.


can we call non static method from static method in java by javaradar
















OUTPUT:

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.