• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

What Is the Purpose of main() in Java?

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



When you're first introduced to Java, one of the first things you’ll write is:


public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}

It works, it prints something, and you're told that main() is the "entry point" of your application.

But why is main() the method that Java looks for? Why does it have to be public static void main(String[] args) and not anything else?


Let's take a look through a practical lens.

Java Needs a Starting Point


Every program needs an entry point — a location where execution begins. In Java, this role is filled by the main() method.
When you run a Java application using: java HelloWorld
the Java Virtual Machine (JVM) looks for a method that matches this exact signature:


public static void main(String[] args)

Here’s why each part matters:

public– The JVM must be able to call this method from outside the class. If it were private or protected, the JVM wouldn’t have access.

static – The JVM doesn’t create an object of your class to call main(). That would be inefficient and unnecessary just to start execution. So main() needs to be static to be callable without instantiating the class.

void– The JVM doesn’t expect any return value. It’s not waiting for output from main(), just looking to execute your logic.

String[] args– This allows users to pass command-line arguments. You can run your Java app with java MyApp arg1 arg2, and those arguments land in this array.

What Happens If You Change the Signature?


Let’s say you try to change the signature slightly:


public static int main(String[] args) // Won’t work

The JVM won’t recognize it as a valid entry point and throws an error, it’s not what the JVM is looking for.

This strict contract is defined in the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

. It's what allows the JVM to find your code and start running it.

Real-World Use Cases of main()


Most real-world Java applications don't live their entire life inside the main() method. But main() is still the launching pad. For example:

  • Spring Boot apps often have a main() method that calls SpringApplication.run() to bootstrap the framework.

public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}

  • Command-line tools written in Java also rely on main() to accept input arguments and run logic accordingly.


  • Testing frameworks or build tools like JUnit or Maven don’t use main() in the same way, because they are run by other tools, not as standalone applications. But even then, somewhere under the hood, a main() is used to launch the process.
Can You Have More Than One main()?


No, in a single Java class, you can only have one method named main() with the exact signature:

public static void main(String[] args)

You can overload the main() method — that is, you can have other methods in the same class named main with different parameters:


public class MainOverloadExample {

public static void main(String[] args) {
System.out.println("Main method with String[] args");

// You can manually call other overloaded main() methods
main("Single String");
main(5);
main(new int[]{1, 2, 3});
}

public static void main(String arg) {
System.out.println("Overloaded main with a single String: " + arg);
}

public static void main(int number) {
System.out.println("Overloaded main with an int: " + number);
}

public static void main(int[] numbers) {
System.out.print("Overloaded main with int[]: ");
for (int n : numbers) {
System.out.print(n + " ");
}
System.out.println();
}
}

But these are not recognized by the JVM as entry points. Only the one with the exact signature — public static void main(String[] args) — is considered the application's starting point.

So practically speaking, for a class to be executable as a Java program, it must contain only one valid main() method. If you try to define more than one with the same signature, the compiler will throw an error due to duplicate method definitions.

However, across multiple classes in the same project, you can have one main() in each class — this is useful when creating utilities, demos, or testing individual components. But again, when you run the program, the JVM will only execute the main() of the class you specify.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу