Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Main Class and Method | Classes
Java Extended
course content

Course Content

Java Extended

Java Extended

1. Deep Java Structure
2. Methods
3. String Advanced
4. Classes
5. Classes Advanced

bookMain Class and Method

Main class

Earlier, we work with the class named Main, but why? Main serves as the entry point of the application, the starting point. It is in the main method that we execute everything we have written earlier. The name Main should remain unchanged so the compiler recognizes it as our entry point. Within the main method, we can write many methods, but they must be static and marked with the static keyword.

Static

The keyword static in Java is used to declare a member (variable or method) that belongs to the class itself rather than an instance of the class. Here's a simple explanation:

  1. Static Variables: When a variable is declared as static, there is only one copy of that variable shared by all instances of the class. It means that any changes made to the variable will be reflected across all instances of the class;

  2. Static Methods: When a method is declared as static, it can be invoked directly on the class itself without needing an instance of the class. Static methods are commonly used for utility methods or operations that don't require accessing instance-specific data.

That's why we were able to use the methods created in the Main class within the main method. We didn't have to create an instance of the Main class (although it is possible) to invoke a method on it.

Why Should the main Method in Java Be Static?

The main method is the entry point of a Java program, and it needs to be static because it needs to be called without creating an instance of the class. When the Java Virtual Machine (JVM) starts executing a Java program, it looks for the main method with the specific signature (public static void main(String[] args)) to begin the execution. Since the main method is called directly on the class, it must be static so that the JVM can access it without creating an object.

1. Why is the class named ``Main`` used in our programs?
2. Why should the ``main`` method in Java be declared as static
Why is the class named ``Main`` used in our programs?

Why is the class named Main used in our programs?

Select the correct answer

Why should the ``main`` method in Java be declared as static

Why should the main method in Java be declared as static

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 2
We're sorry to hear that something went wrong. What happened?
some-alt