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

How to fix exceptions in the main thread in Java?

Static methods belong to the class and they will be loaded into memory along with the class. You can call them without creating an object. (Use the class name as the reference).

Example

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method");
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

Output Result

Contents of the static method

The keyword 'this' is used as a reference to an instance. Since static methods do not belong to any instance,Therefore, 'this' cannot be used in static methods. If it is still like this, please try to do this, which will generate a compile-time error.

Example

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method"+this.num);
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

Compile-time error

Sample.java:4: error: non-static variable this cannot be referenced from a static context
   System.out.println("Contents of the static method"+this.num);
                                                      ^
1 error