• Register
28,501 points
12 7 5
 non-static method cannot be referenced from a static context

Have you ever seen this error? Have you ever wondered why this error occurs? In this article, you are going to find the answer to these questions. 

For understanding the reason for any error, it is necessary to understand the error message. The above-mentioned error message says that you cannot call a non-static method from a static method. It means that you should never try to call a static method from a non-static method or vice versa. Before going deep into the subject, let’s first see what a static method is in Java:

A static method can be called directly with the class name without creating an instance of that class. All the static methods are shared among the objects of a certain class. They are almost the same as the static variables that are shared among the instances of a particular class. A static method can only be called by the static reference and it can call only another static method. In simple words, you cannot call a non-static method from a static method. 

Now that we have the idea of a static method, let’s see why does this error occurs. Consider the following example program to understand better:

In the following program, I have 3 methods, two of which are static and one is non-static. I have first called the static method inside a non-static method and then called the non-static method from the static reference:

public class Main
{
	public static void main(String[] args)    //static method
{
	 addition();  
	}
	public static int string_num_sum(String str)  //method that checks whether a character is digit and add it to the sum  //static method
	{
       int sum = 0;
        for(int i = 0; i < str.length() ; i++)   //looping through the string
        {
            if( Character.isDigit(str.charAt(i)) )  //checking if the character at certain position is digit or not
            {
                sum = sum + Character.getNumericValue(str.charAt(i));  //digits are being added in this step
            }
        }
        return sum;  //returning the sum
    }
    
    public void addition()  //non-static method
    {
           System.out.println("The sum of the string is: " + string_num_sum("7h15 15 @ 57r1ng"));
    }
}

This program is supposed to calculate the sum of numbers that appears in a string but, it is showing the error that I have mentioned at the beginning of this article.

Now, if I declare the non-static method as static, no error will occur:

public static void addition()
    {
           System.out.println("The sum of the string is: " + string_num_sum("7h15 15 @ 57r1ng"));
    }

Output:

The sum of the string is: 32

So, from this discussion, we understood that if we want to call a static method, we can only call it inside another static method, Same goes for the non-static methods.