- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Why "this" keyword cannot be used in the main method of java class?
The static methods belong to the class and they will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as 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
Contents of the static method
The "this" keyword is used as a reference to an instance. Since the static methods doesn’t have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated.
And main method is static therefore, you cannot use the "this" reference in main method.
Example
public class Sample{ int num = 50; public static void main(String args[]){ System.out.println("Contents of the main method"+this.num); } }
Compile time error
Sample.java:4: error: non-static variable this cannot be referenced from a static context System.out.println("Contents of the main method"+this.num); ^ 1 error
- Related Articles
- Why the main method has to be in a java class?
- Why main() method must be static in java?
- What are all the ways keyword ‘this’ can be used in Java?
- Can a "this" keyword be used to refer to static members in Java?\n
- What is the keyword used in instantiating a class in Java?
- When should I use the keyword ‘this’ in a Java class?
- Why variables defined in try cannot be used in catch or finally in java?
- Why constructor cannot be final in Java
- Why the main () method in Java is always static?
- Is main a keyword in Java?
- Why Final Class used in Java?
- Why a constructor cannot be final in Java?
- This keyword in Java
- Why Abstract Class is used in Java?
- Can we return this keyword from a method in java?

Advertisements