Java error non static variable this cannot be referenced from a static context

I've written this test code: class MyProgram { int count = 0; public static void main(String[] args) { System.out.println(count); } } But it gives the following error: Main.

I’ve written this test code:

class MyProgram
{
    int count = 0;
    public static void main(String[] args)
    {
        System.out.println(count);
    }
}

But it gives the following error:

Main.java:6: error: non-static variable count cannot be referenced from a static context
        System.out.println(count);
                           ^

How do I get my methods to recognize my class variables?

Bernhard Barker's user avatar

asked Apr 1, 2010 at 9:57

Greg's user avatar

2

You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it’s a car even if you can’t see which model or type. This is because you compare what you see with the class «car». The class contains which is similar to all cars. Think of it as a template or an idea.

At the same time, the car you see is an instance of the class «car» since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.

So the class says «all cars have a color» and the instance says «this specific car is red».

In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.

Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it’s usually constants (like car types, i.e. something where you have a limited set which doesn’t change often).

To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don’t want).

In your case, try this code as a starting block:

public static void main (String[] args)
{
    try
    {
        MyProgram7 obj = new MyProgram7 ();
        obj.run (args);
    }
    catch (Exception e)
    {
        e.printStackTrace ();
    }
}

// instance variables here

public void run (String[] args) throws Exception
{
    // put your code here
}

The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).

answered Apr 1, 2010 at 10:10

Aaron Digulla's user avatar

Aaron DigullaAaron Digulla

317k106 gold badges588 silver badges812 bronze badges

4

Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a ‘normal’ (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.

The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:

class Programm {

    public static void main(String[] args) {
        Programm programm = new Programm();
        programm.start();
    }

    public void start() {
        // can now access non-static fields
    }
}

mlntdrv's user avatar

answered Apr 1, 2010 at 10:14

Mnementh's user avatar

MnementhMnementh

49.8k47 gold badges147 silver badges202 bronze badges

The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.

The lifecycle of a class, in broad terms, is:

  1. the source code for the class is written creating a template or
    pattern or stamp which can then be used to
  2. create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
  3. destroy the object reclaiming the resources it is holding such as memory during garbage collection.

In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.

The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.

So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.

However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.

import java.io.*;

class HelloWorld {
    int myInt;      // this is a class variable that is unique to each object
    static int myInt2;  // this is a class variable shared by all objects of this class

    static void main (String [] args) {
        // this is the main entry point for this Java application
        System.out.println ("Hello, Worldn");
        myInt2 = 14;    // able to access the static int
        HelloWorld myWorld = new HelloWorld();
        myWorld.myInt = 32;   // able to access non-static through an object
    }
}

Matilda Smeds's user avatar

answered Jan 16, 2015 at 15:37

Richard Chambers's user avatar

Richard ChambersRichard Chambers

16.3k4 gold badges77 silver badges105 bronze badges

1

To be able to access them from your static methods they need to be static member variables, like this:

public class MyProgram7 {
  static Scanner scan = new Scanner(System.in);
  static int compareCount = 0;
  static int low = 0;
  static int high = 0;
  static int mid = 0;  
  static int key = 0;  
  static Scanner temp;  
  static int[]list;  
  static String menu, outputString;  
  static int option = 1;  
  static boolean found = false;

  public static void main (String[]args) throws IOException {
  ...

answered Apr 1, 2010 at 10:08

Nick Moore's user avatar

Nick MooreNick Moore

15.4k5 gold badges60 silver badges83 bronze badges

Let’s analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method… Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can’t use those variables outside that method. This is the basic error u made.

Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the «static» keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).

And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.

Michal Trojanowski's user avatar

answered Jul 18, 2011 at 9:10

Suseendran.P's user avatar

The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That’s why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.

answered Jul 24, 2013 at 13:26

Ajay Bhojak's user avatar

Ajay BhojakAjay Bhojak

1,1619 silver badges17 bronze badges

Now you can add/use instances with in the method

public class Myprogram7 {

  Scanner scan;
  int compareCount = 0;
  int low = 0;
  int high = 0;
  int mid = 0;  
  int key = 0;  
  Scanner temp;  
  int[]list;  
  String menu, outputString;  
  int option = 1;  
  boolean found = false;  

  private void readLine() {

  }

  private void findkey() {

  }

  private void printCount() {

  }
  public static void main(String[] args){

    Myprogram7 myprg=new Myprogram7();
    myprg.readLine();
    myprg.findkey();
    myprg.printCount();
  }
}

Zaheer Ahmed's user avatar

Zaheer Ahmed

28k11 gold badges73 silver badges110 bronze badges

answered Sep 24, 2013 at 10:03

Sainath Patwary karnate's user avatar

1

I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That’s why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.

answered Apr 1, 2010 at 10:13

Petar Minchev's user avatar

Petar MinchevPetar Minchev

46.5k11 gold badges103 silver badges119 bronze badges

  • The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.

  • Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class

  • As a corollary to the above

    1. variables within a method can not be static
    2. static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(…)
  • The lifetime of a static field/method is equivalent to the lifetime of your application

E.g.
Say, car has the property colour, and exhibits the behaviour ‘motion’.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.

Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.

HTH

answered Apr 1, 2010 at 11:55

Everyone's user avatar

EveryoneEveryone

2,3462 gold badges26 silver badges38 bronze badges

Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn’t know which is the object this variable belongs to. Because static methods doesn’t have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it’s own copy of instance methods and variables.

Static variables are marked as static and instance variables doesn’t have specific keyword.

answered May 25, 2018 at 19:45

Lakindu Akash's user avatar

Lakindu AkashLakindu Akash

9141 gold badge11 silver badges27 bronze badges

It is ClassLoader responsible to load the class files.Let’s see what happens when we write our own classes.

Example 1:

class StaticTest {

      static int a;
      int b;
      int c;
}

Now we can see that class «StaticTest» has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest’s see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That’s why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it’s object not instantiated yet.

Let’s see another example:
Example 2:

class StaticTest {

      public void display() {
          System.out.println("Static Test");
      }


      public static void main(String []cmd) {

             display();       
      }

}

Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.

Now For ClassLoader it looks like:

class StaticTest {

      public static void main(String []cmd) {

             display();       
      }

}

In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.

answered Sep 3, 2015 at 12:21

Newaz Sharif Amit's user avatar

1

This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.

|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like

NamCls.NamFnc();

System.out.println();

This is because NamFnc and println wil be declared using key word static before them.

|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.

NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();

Below code explains you neatly

|*| Static and non Static function in class :

public class NamCls
{
    public static void main(String[] args)
    {
        PlsPrnFnc("Tst Txt");

        NamCls NamObjVar = new NamCls();
        NamObjVar.PrnFnc("Tst Txt");
    }

    static void PlsPrnFnc(String SrgPsgVal)
    {
        System.out.println(SrgPsgVal);
    }

    void PrnFnc(String SrgPsgVal)
    {
        System.out.println(SrgPsgVal);
    }
}

|*| Static and non Static Class inside a Class :

public class NamCls
{
    public static void main(String[] args)
    {
        NamTicCls NamTicVaj = new NamTicCls();
        NamTicVaj.PrnFnc("Tst Txt");

        NamCls NamObjVar = new NamCls();
        NamNicCls NamNicVar = NamObjVar.new NamNicCls();
        NamNicVar.PrnFnc("Tst Txt");
    }

    static class NamTicCls
    {
        void PrnFnc(String SrgPsgVal)
        {
            System.out.println(SrgPsgVal);
        }
    }

    class NamNicCls
    {
        void PrnFnc(String SrgPsgVal)
        {
            System.out.println(SrgPsgVal);
        }
    }
}

answered Jun 6, 2017 at 22:31

Sujay U N's user avatar

Sujay U NSujay U N

4,80610 gold badges49 silver badges85 bronze badges

In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.

This means that only one instance of that static member is created which is shared across all instances of the class.

So if you want to use your int count = 0; in static void main() , count variable must be declared as static

static int count = 0;

answered Sep 26, 2021 at 14:54

hakkikonu's user avatar

hakkikonuhakkikonu

5,8866 gold badges61 silver badges108 bronze badges

In this Program you want to use count, so declare count method as a static

class MyProgram<br>
{
    int count = 0;
    public static void main(String[] args)
    {
        System.out.println(count);
    }
}

Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.

class MyProgram
{
    static int count = 0;
    public static void main(String[] args)
    {
        System.out.println(count);
    }
}

Etienne Kaiser's user avatar

answered Aug 17, 2021 at 18:28

Vikas Dhiman's user avatar

This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.

you can easily fix this see below images

Without Instance making

without making instance of class

enter image description here

My model class file

enter image description here

By just creating instance then use class non-static methods or variables easily error gone

answered Jan 27, 2022 at 9:33

KaranKulshrestha's user avatar

Introduction to Static Variables and Methods

The static keyword in Java is a modifier that makes a member of a class independent of the instances of that class. In other words, the static modifier is used to define variables and methods related to the class as a whole, rather than to an instance (object) of the class. Hence, static variables are often called class variables, while static methods are commonly referred to as class methods. Class variables and methods are stored in fixed locations in memory and are accessed without a reference to an object, directly through the class name itself [1].

A common use for static methods is to access static variables. However, not all combinations of instance and class variables and methods are allowed. Namely, static methods can only use static variables and call static methods—they cannot access instance variables or methods directly, without an object reference. This is because instance variables and methods are always tied to a specific instance, i.e., object of their class.

Due to their instance-less nature, static variables and methods are sometimes used to construct stateless utility classes [2].

Non-static Variable X Cannot be Referenced from a Static Context & Non-static Method X Cannot be Referenced from a Static Context

A static variable is initialized once, when its class is loaded into memory, and its value is shared among all instances of that class. On the other hand, a non-static variable is initialized every time a new instance of its class is created, and as such there can be multiple copies of it in memory, each with a different value. Consequently, attempting to access a non-static variable from a static context (a static method or block) without a class instance creates ambiguity—every instantiated object has its own variable, so the compiler is unable to tell which value is being referenced. And if no class instance is created, the non-static variable is never initialized and there is no value to reference. For the same reasons, a non-static method cannot be referenced from a static context, either, as the compiler cannot tell which particular object the non-static member belongs to.

To prevent this conundrum when accessing instance variables and methods from a static context, the Java compiler raises the non-static variable X cannot be referenced from a static context, or the non-static method X cannot be referenced from a static context error, respectively. To rectify this problem, there are two possible solutions:

  • refer to the non-static member through a class instance, or
  • declare the non-static member static.

Examples

Non-static Variable X Cannot be Referenced from a Static Context

The code example in Fig. 1(a) shows how attempting to increment and print the value of the non-static variable count from the static main method results in the non-static variable count cannot be referenced from a static context error. The Java compiler flags both attempts to reference the instance variable without an actual class instance and points to their exact location in the source code.

Creating a local class instance in the main method and accessing the count variable through this object resolves this issue (Fig. 1(b)), as it unambiguously links the variable to a specific object. In scenarios where the variable in question doesn’t need to hold data specific to a class instance, but can either be shared among all class instances or used independently of any, adding the static modifier to it makes it accessible from a static context, effectively resolving the error, as shown in Fig. 1(c).

(a)

package rollbar;

public class StaticContextVariable {

 private int count = 0;

 public static void main(String... args) {
   count++;
   System.out.println(count);
 }
}
StaticContextVariable.java:8: error: non-static variable count cannot be referenced from a static context
    count++;
    ^
StaticContextVariable.java:9: error: non-static variable count cannot be referenced from a static context
    System.out.println(count);
                       ^
2 errors              

(b)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

public class StaticContextVariable {

 private int count = 0;

 public static void main(String... args) {
   var classInstance = new StaticContextVariable();
   classInstance.count++;
   System.out.println(classInstance.count);
 }
}
1

(c)

package rollbar;

public class StaticContextVariable {

 private static int count = 0;

 public static void main(String... args) {
   StaticContextVariable.count++;
   System.out.println(StaticContextVariable.count);
 }
}
1
Figure 1: Non-static Variable Cannot be Referenced from a Static Context (a) error and (b) resolution by class instantiation or (c) resolution by making the variable static

Non-static Method X Cannot be Referenced from a Static Context

Just like non-static variables, non-static methods need an object in order to be instantiated into memory and referenced. Fig. 2(a) shows how trying to access the instance method incrementAndGetCount() without a class instance raises the non-static method incrementAndGetCount() cannot be referenced from a static context error.

Creating a class instance and calling this method on it, as demonstrated in Fig. 2(b), fixes the error. Making the incrementAndGetCount() method static and referencing it via the class itself (lines 7 and 12 in Fig. 2(c)) also mediates this problem, as there is no longer the need for an object to exist before the method can be invoked.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class StaticContextMethod {

 private static int count = 0;

 private int incrementAndGetCount() {
   return ++count;
 }

 public static void main(String... args) {
   System.out.println(incrementAndGetCount());
 }
}
StaticContextMethod.java:12: error: non-static method incrementAndGetCount() cannot be referenced from a static context
    System.out.println(incrementAndGetCount());

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package rollbar;

public class StaticContextMethod {

 private static int count = 0;

 private int incrementAndGetCount() {
   return ++count;
 }

 public static void main(String... args) {
   var classInstance = new StaticContextMethod();
   System.out.println(classInstance.incrementAndGetCount());
 }
}
1

(c)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class StaticContextMethod {

 private static int count = 0;

 private static int incrementAndGetCount() {
   return ++count;
 }

 public static void main(String... args) {
   System.out.println(StaticContextMethod.incrementAndGetCount());
 }
}
1
Figure 2: Non-static Method Cannot be Referenced from a Static Context (a) error and (b) resolution by class instantiation or (c) resolution by making the method static

Summary

Static variables and methods, jointly known as static class members in Java, are used to model data and behavior common to all instances of a class, or in some cases to store data and procedures for stateless classes which don’t need to be instantiated. Contrary to this, non-static variables and methods depend on class instances, as they store and manipulate data specific to individual objects. Therefore, non-static members cannot be accessed from a static context, i.e., there has to be a class instance that references these members. Failing to abide by this rule inevitably produces the non-static variable X cannot be referenced from a static context or the non-static method X cannot be referenced from a static context compile-time error, depending on whether it’s a variable or a method that is being referenced. The error message generated by the Java compiler contains the exact location of the variable or method in question, and resolving the issue involves making use of a new or an existing class instance, or alternatively making the class member static where appropriate.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] Oracle, 2021. Understanding Class Members (The Java™ Tutorials > Learning the Java Language > Classes and Objects), Oracle and/or its affiliates. [Online]. Available: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html. [Accessed: Dec. 08, 2021]

[2] Y. Taz, 2019. Writing a Utility Class for Collections in Java 8, Yavuz Tas. [Online]. Available: https://yavuztas.dev/java/collections/streams/2019/08/10/java8-utility-class.html. [Accessed: Dec. 08, 2021]

Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let’s discuss why non-static variable cannot be referenced from a static method. 
Before getting into the error, lets first understand what each of the methods means: 
 

  • Static Method: A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
  • Non-static method: Any method whose definition doesn’t contain the static keyword is a non-static method. In the non-static method, the method can access static data members and static methods as well as non-static members and method of another class or same class, also can change the values of any static data member.

What is the Issue with non-static variable referenced from static context?
Let’s consider the following code where class A is created with a non-static variable and a static method. The object of this class is being created in another class and the static method is being accessed as follows:
 

JAVA

class A {

    int N;

    public static void increment()

    {

        N++;

    }

}

public class Demo {

    public static void main(String args[])

    {

        A obj1 = new A();

        A obj2 = new A();

        A obj3 = new A();

        obj1.N = 3;

        obj2.N = 4;

        obj3.N = 5;

        A.increment();

        System.out.println(obj1.N);

        System.out.println(obj2.N);

        System.out.println(obj3.N);

    }

}

IF this code could actually be run, you would expect the output to be: 
 

4
5
6

But instead a compile-time error is thrown
 

Compile Errors:

prog.java:16: error: non-static variable N cannot be referenced from a static context
        N++;
        ^
1 error

As we can see that the above program gives the error. Though in the above code, all the objects names have the same variable name N, if we try to increment N, its giving an error. This error is very common during object oriented programming. 
Why does this error occur?
For the non-static variable, there is a need for an object instance to call the variables. We can also create multiple objects by assigning different values for that non-static variable. So, different objects may have different values for the same variable. In the above program we have created three objects obj1, obj2, obj3 for the class A and assigned the three different values 3, 4, 5 for the objects obj1, obj2, obj3 respectively. When we try to call the function increment, as every object of N have its own value there will be ambiguity for the compiler to understand for what value of N should the method increment the value.
How to solve this error? 
In order to avoid ambiguity, the java compiler throws a compile time error. Therefore, this issue can be solved by addressing the variables with the object names. In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created. By using the reference of the new instance, these variables can be accessed. For example:
 

Java

public class GFG {

    int count = 0;

    public static void main(String args[])

    {

        GFG test = new GFG();

        test.count++;

        System.out.println(test.count);

    }

}

Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

«non-static variable cannot be referenced from a static context» is the biggest nemesis of someone who has just started programming and that too in Java. Since the main method in java is the most popular method among all beginners and they try to put program code there they face «non-static variable cannot be referenced from a static context» compiler error when they try to access a non-static member variable inside the main in Java which is static. if you want to know why the main is declared static in Java see the link.

public class StaticTest {

    private int count=0;

    public static void main(String args[]) throws IOException {

        count++; //compiler error: non-static variable count cannot be referenced from a static context

    }

}

Why the non-static variable can not be called from static method

non-static variable cannot be referenced from a static contextNow before finding the answer of compiler error «non-static variable cannot be referenced from a static context«, let’s have a quick revision of static. The static variable in Java belongs to Class and its value remains the same for all instances


static variable initialized when class is loaded into JVM on the other hand instance variable has a different value for each instance and they get created when an instance of an object is created either by using the new() operator or using reflection like Class.newInstance(). 


So if you try to access a non-static variable without any instance compiler will complain because those variables are not yet created and they don’t have any existence until an instance is created and they are associated with any instance. So in my opinion, the only reason which makes sense to disallow non-static or instance variable inside static context is the non-existence of instance.

In Summary, since code in static context can be run even without creating an instance of a class, it does not make sense asking value for a specific instance which is not yet created. 

How to access non-static variable inside static method or block

You can still access any non-static variable inside any static method or block by creating an instance of class in Java and using that instance to reference instance variable. This is the only legitimate way to access non static variable on static context. 

here is a code example of accessing non static variable inside static context:

public class StaticTest {

    private int count=0;

    public static void main(String args[]) throws IOException {

        StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class

        test.count++;

    }  

}

So next time if you get compiler error “non-static variable cannot be referenced from a static contextaccess static member by creating an instance of Class. Let me know if you find any other reason why non-static variables cannot be referenced from a static context.

Other Java Tutorials you may find useful:

Error: Non-Static Variable Count Cannot Be Referenced From a Static Context in Java

This tutorial demonstrates the error: non-static variable count cannot be referenced from a static context in Java.

the Error: non-static variable count cannot be referenced from a static context in Java

Most of the time, the error: non-static variable count cannot be referenced from a static context occurs when we try to use a non-static member variable in the main method because the main() method is static and is invoked automatically. We don’t need to create an object to invoke the main() method.

To understand the error: non-static variable count cannot be referenced from a static context, first, we need to understand the concept of static and non-static methods.

Static Methods

The static methods belong to a class but not to the instance of that class. The static method is called without the instance or object of the class.

The static methods can only access the static variables and other members of the static methods of their class and other classes. The static methods cannot access the non-static members of a class.

Non-Static Methods

Any method which doesn’t contain a Static keyword is a non-static method. The non-static methods can access the static and non-static variables and members of the same class or another class.

The non-static methods can also change the value of static data.

Example of Static and Non-Static Methods in Java

Let’s try an example to demonstrate static and non-static methods.

package delftstack;


class DelftstackDemo {

    //non-static variable
    int Demo;

    //Static method
    public static void increment() {
        // Using a Non-Static Variable in Static Method. Error
        Demo++;
    }
}

public class Example {

    //Static Main method
    public static void main(String args[]) {
        DelftstackDemo Demo1 = new DelftstackDemo();
        DelftstackDemo Demo2 = new DelftstackDemo();
        DelftstackDemo Demo3 = new DelftstackDemo();

        Demo1.Demo = 7;
        Demo2.Demo = 8;
        Demo3.Demo = 9;

        // Calling the method
        DelftstackDemo.increment();

        System.out.println(Demo1.Demo);
        System.out.println(Demo2.Demo);
        System.out.println(Demo3.Demo);
    }
}

The code above has two classes. In the first class, the code uses a non-static member variable in a static method, and the second class tries to change the values of the non-static member from the instance in the main method.

The code will throw an error.

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
	Cannot make a static reference to the non-static field Demo

	at delftstack.DelftstackDemo.increment(Example.java:12)
	at delftstack.Example.main(Example.java:29)

The code above throws the error because a non-static member Demo is used in the static method. Changing the method increment to non-static and calling it with the first class instance will solve the problem.

See solution:

package delftstack;


class DelftstackDemo {

    //non-static variable
    int Demo;

    //change to a non-static method
    public void increment() {
        // No error
        Demo++;
    }
}

public class Example {

    //Static Main method
    public static void main(String args[]) {
        DelftstackDemo Demo1 = new DelftstackDemo();
        DelftstackDemo Demo2 = new DelftstackDemo();
        DelftstackDemo Demo3 = new DelftstackDemo();

        Demo1.Demo = 7;
        Demo2.Demo = 8;
        Demo3.Demo = 9;

        // Calling the method
        Demo1.increment();

        System.out.println(Demo1.Demo);
        System.out.println(Demo2.Demo);
        System.out.println(Demo3.Demo);
    }
}

Now we are using a non-static member in the non-static method and calling a non-static method into the main static by the instance of the first class. It solves the problem.

See output:

You may encounter “Error: Non-static Variable/Method ‘#’ Cannot be Referenced from a Static Context” when starting to learn about non-access modifiers, in this case the static keyword. Continue reading to learn how to fix the error.

Example of error:

import java.util.*;

class MyClass {
	public String name = "learnshareit.com";
	public MyClass() {}
	public void sayName() {
		System.out.println(name);
	}
	public static void main(String[] args) {
	  MyClass.sayName();
  }
}

Output:

MyClass.java:10: error: non-static method sayName() cannot be referenced from a static context
	    MyClass.sayName();

Understanding the problem

The static keyword: Is a non-access modifier for the Methods and Properties/Attributes/Variables of a Class, which lets you access them without the need to create an instance of that Class.

⇒ The error is thrown when a non-static variable/method is accessed without the creation of an instance of the Class containing it.

How to fix this error?

Solution 1: Making the variable static

The most direct way to solve the issue. Simply add the static keyword to the variable. Here is the example to fix it:

import java.util.*;

class MyClass {
	public static String name = "learnshareit.com";
	public MyClass() {}
	public static void sayName() {
		System.out.println(name);
	}
	public static void main(String[] args) {
	  MyClass.sayName();
  }
}

Output:

learnshareit.com

Solution 2: Creating an instance of the Class

In the case that you need the variable to be non-static, you would need to create an instance of the Class containing the variable. You can try this way:

import java.util.*;

class MyClass {
	public String name = "learnshareit.com";
	public MyClass() {}
	public void sayName() {
		System.out.println(name);
	}
	public static void main(String[] args) {
	    MyClass _class = new MyClass();
	    _class.sayName();
  }
}

Output:

learnshareit.com

Summary

You can fix the error "Non-static Variable/Method ‘#’ Cannot be Referenced from a Static Context" either by making the variable in question static or creating an instance of the Class containing the variable

Maybe you are interested:

  • Could not reserve enough space for 2097152kb object heap
  • ERROR : ‘compileJava’ task (current target is 11) and ‘compileKotlin’ task (current target is 1.8) jvm target compatibility should be set to the same Java version in Java
  • java.lang.IllegalAccessError: class lombok.javac.apt.LombokProcessor cannot access class com.sun.tools.javac.processing.JavacProcessingEnvironment

Hello, my name is Davis Cole. I love learning and sharing knowledge about programming languages. Some of my strengths are Java, HTML, CSS, JavaScript, C#,… I believe my articles about them will help you a lot.


Programming Languages: Java, HTML, CSS, JavaScript, C#, ASP.NET, SQL, PHP

Понравилась статья? Поделить с друзьями:
  • Java application error log
  • Java application error illegalargumentexception
  • Java 1603 error windows 7
  • Java 105 error
  • Java 102 error