Static void main что это

от admin

Lesson: A Closer Look at the «Hello World!» Application

Now that you've seen the "Hello World!" application (and perhaps even compiled and run it), you might be wondering how it works. Here again is its code:

The "Hello World!" application consists of three primary components: source code comments, the HelloWorldApp class definition, and the main method. The following explanation will provide you with a basic understanding of the code, but the deeper implications will only become apparent after you've finished reading the rest of the tutorial.

Source Code Comments

Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments:

/* text */ The compiler ignores everything from /* to */ . /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */ . The javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc , see the Javadoc™ tool documentation . // text The compiler ignores everything from // to the end of the line.

The HelloWorldApp Class Definition

As shown above, the most basic form of a class definition is:

The keyword class begins the class definition for a class named name , and the code for each class appears between the opening and closing curly braces marked in bold above. Chapter 2 provides an overview of classes in general, and Chapter 4 discusses classes in detail. For now it is enough to know that every application begins with a class definition.

The main Method

In the Java programming language, every application must contain a main method whose signature is:

The modifiers public and static can be written in either order ( public static or static public ), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".

The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.

The main method accepts a single argument: an array of elements of type String .

This array is the mechanism through which the runtime system passes information to your application. For example:

Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:

The "Hello World!" application ignores its command-line arguments, but you should be aware of the fact that such arguments do exist.

Finally, the line:

uses the System class from the core library to print the "Hello World!" message to standard output. Portions of this library (also known as the "Application Programming Interface", or "API") will be discussed throughout the remainder of the tutorial.

Урок 14. Метод public static void main

В этой статье из моего курса Java я буду обсуждать метод public static void main (String[] args). До этого момента в серии мы запускали наш код только через фреймворк JUnit. Это здравая, методологическая практика, однако она отличается от того, как наша программа будет работать в производстве. Теперь давайте рассмотрим, как наш код будет работать вне среды разработки.

public static void main

Изначально код, который вы пишете в компьютерной программе, — это просто статический текст, пассивно лежащий в файле. Для выполнения кода среда выполнения Java (JRE) отвечает за загрузку скомпилированной программы и запуск ее запуска. Для выполнения кода JRE нужна точка входа. При запуске класса Java из командной строки точкой входа, которую ищет JRE, является следующий метод:

Давайте рассмотрим каждую часть метода в деталях:

  • public — позволяет вызывать метод из-за пределов класса.
  • static — позволяет вызывать метод без создания экземпляра класса.
  • void — не возвращает значения.
  • main () — чтобы выполнить вашу программу, Java будет специально искать метод с именем «main».
  • String [] args — вы можете вызвать свою программу с несколькими аргументами. Ваша программа может получить доступ к этим аргументам из этого массива.

Оба кода распознаются JRE. Кроме того, одна вещь о главном методе, который вы можете найти интересным, заключается в том, что вам даже не нужно использовать массив – вы можете заменить массив параметром переменной длины:

Входной параметр, показанный здесь похож на более гибкую версию массива – если вы непосредственно вызываете этот метод, например из теста, он имеет преимущество в принятии переменного числа строковых аргументов, например main(“BMW”, “Porsche”, “Mercedes”), без необходимости создавать массив заранее. Честно говоря, я никогда не использую такой параметр для основного метода, но я думаю, что это хорошая деталь, чтобы знать и хвастаться ;-).

Статический основной метод, который мы используем в качестве точки доступа, очень специфичен. Если вы измените его сверх того, что я обсуждал, он не будет работать так, как вы намереваетесь. Если вы хотите свести своих коллег с ума ; -), вы можете отклониться от этого шаблона, например, сделав метод int вместо void, как показано ниже:

Это код создаст метод с именем main, но он не будет распознан как «основной» метод, и поэтому программа не сможет работать, используя этот метод в качестве отправной точки.

Примеры кода

Давайте создадим класс calledCarSelector и добавим к нему метод main. Он выводит каждый из аргументов командной строки обратно на консоль:

С помощью основного метода мы можем выполнить этот код без использования тест для вызова, как мы делали до текущего момента.

Компиляция c помощью командной строки

Чтобы запустить нашу программу из командной строки, мы должны сначала перейти в корневую папку нашего исходного кода. В нашем случае это src/main/ java. Кроме того, это структура папок по умолчанию для “Maven», инструмента управления сборкой, который я выделил ранее, когда говорил об инструментах Java.

Для компиляции кода мы вводим:

Это создаст файл под названием CarSelector.класс в той же папке, что и CarSelector.java, и мы, наконец, можем выполнить нашу программу:

Как вы можете видеть, вызов нашего класса без каких-либо аргументов на самом деле ничего не делает. Так что давайте добавим несколько аргументов:

Ура! Мы успешно выполнили нашу собственную программу с консоли!

Запуск программы с помощью IntelliJ IDEA

Чтобы запустить нашу программу из IntelliJ IDEA, мы просто щелкаем правой кнопкой мыши метод и выбираем » Run ‘CarSelector.main’ » из контекстного меню.

Если мы изменим сигнатуру метода main(), то запустим CarSelector.команда main исчезнет из контекстного меню, так как у нас больше не будет действительной точки входа. Однако, когда мы запускаем его, ничего не печатается. Это происходит потому, что никто не передает методу main() никаких аргументов. Для этого в IDE: в меню «Run“ выберите ”edit configurations…. “, а во вкладке ”конфигурация“ добавьте разделенные пробелами строки в ” Program Parameters».

Теперь, когда мы запускаем метод main (), мы видим, что наши автомобили успешно выводятся на консоль.

Комментарий

Если вы закончили еще один курс Java до этого, или даже если это ваш первый курс, вы можете задаться вопросом, почему я отложил введение метода main() до этого относительно продвинутого этапа в курсе. Я сделал это по нескольким причинам. Во-первых, я считаю, что важно дать вам инструменты, чтобы полностью понять что-то, прежде чем я представлю его. Если бы вы не знали, что такое public static void, или не знали, что такое массив, было бы нечестно учить вас этому. Теперь, когда у вас есть некоторые знания обо всех этих вещах, вы можете начать полностью понимать, как работает этот метод.

Читать:
Outlook программа пытается отправить сообщение от вашего имени как отключить

Еще одна причина, по которой я решил отложить это обсуждение на столь долгое время, заключается в том, что в объектно-ориентированной разработке статические переменные и методы должны использоваться редко. Есть несколько случаев, когда вы используете статический модификатор, но я не хочу продвигать его использование в этом курсе.

Наконец, вам редко придется писать основной метод самостоятельно (если вы не будете программировать в одиночку). Для каждой программы (любого размера) существует только один основной метод, и к тому времени, когда вы присоединились к проекту, он, вероятно, уже был написан кем-то другим.


Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

тегистатьи IT, уроки по java, java, методы

Static void main что это

C# applications have an entry point called Main Method. It is the first method which gets invoked whenever an application started and it is present in every C# executable file. The application may be Console Application or Windows Application. The most common entry point of a C# program is static void Main() or static void Main(String []args) .

Different Declaration of Main() Method

Below are the valid declarations of Main Method in a C# program:

  1. With command line arguments: This can accept n number of array type parameters during the runtime.

Example:

Output:

Meaning of the Main Syntax:

static: It means Main Method can be called without an object.
public: It is access modifiers which means the compiler can execute this from anywhere.
void: The Main method doesn’t return anything.
Main(): It is the configured name of the Main method.
String []args: For accepting the zero-indexed command line arguments. args is the user-defined name. So you can change it by a valid identifier. [] must come before the args otherwise compiler will give errors.

Example:

Output:

Example:

Output:

Example:

Compiler Error:

More than one protection modifier specified

Example:

Output:

Example:

Output:

Example:

Output:

Example:

Output:

Example:

Output:

Important Points:

  • The Main() method is the entry point a C# program from where the execution starts.
  • Main() method must be static because it is a class level method. To invoked without any instance of the class it must be static. Non-static Main() method will give a compile-time error.
  • Main() Method cannot be overridden because it is the static method. Also, the static method cannot be virtual or abstract.
  • Overloading of Main() method is allowed. But in that case, only one Main() method is considered as one entry point to start the execution of the program.

public static void main(String args[])<> — A Complete Story

Below is the list of questions the interviewer can ask on the main method in java.

1.) Explain the meaning of each word in public static void main?

2.) Will the program run if I write static public void main instead of public static void main?

3.) Why is the main method static in java?

4.) What happens when main method isn’t declared as static?

5.) What if the main method is declared as private?

6.) What if I write String a[] instead of String args[] in an argument in the main method?

Before we move ahead, let’s take some knowledge…

The main method is the starting point of a program or an application in java. So when we run the java code, JVM calls the main method first. In short, JVM (Java Virtual Machine) needs the main method to start the execution of the java program.

See above code once. We have a People class and the main method is defined inside the People class. We are using this class as reference to understand this topic.

public: It is the access specifier which tells who can access this method. “public” ensures that the method is globally available thus can be accessed from anywhere. The main method is made public so that JVM can call it from outside as JVM is not present inside the People class.

static: When a method or variable is defined as static then it is called class method or class variable respectively i.e. it can be accessed without creating the object. So we don’t need any object to call the main method. Remember this.

void: It tells the return type of the method. “void” means the main method will not return any value.

main: It is the name of the method.

String args[]: It is the argument of the main method. You can keep any name of the argument. It is not necessary to keep args only. You can keep any name like a,b, ashay, your name, etc.

Now, let’s see each question one by one.

1.) Explain the meaning of each word in public static void main?

Ans: We have just completed it above.

2.) Will the program run if I write static public void main instead of public static void main?

Ans: Yes, it will compile and run successfully. You can also give it a try on ide.

3.) Why is the main method static in java?

Ans: “static” allows JVM to call the main method without creating the object of the People class. If static is not there then JVM needs to make the object of People class to call the main method but the issue is that object creation depends on the constructor of People class. Let’s understand.

a.) If People class doesn’t contain any constructor or have constructor without parameter then to access the main method, our object will be People obj = new People().

b.) If People class contain constructor with one parameter then to access the main method, our object will be People obj = new People(some value).

c.) If People class contain constructor with multiple parameters (two or more) then to access the main method, our object will be People obj = new People(value1, value2, …..) depend on the number of parameters.

In short, JVM needs to create an object based on the constructor present in the People class. Unnecessary making it complex. Also, what would be the value JVM should pass for parametrized constructors. Thus, ambiguous i.e. not clear. So, creating objects will lead to complexity and ambiguity. Hence, the main is static in java.

4.) What happens when main() isn’t declared as static?

Ans: Program compiles successfully. But at runtime throws an error:

5.) What if the main method is declared as private?

Ans: Program compiles successfully. But at runtime throws an error :

6.) What if I write String a[] instead of String args[] in an argument in the main method?

Ans: I think I have answered it above. Hope you remember.

I hope you get the whole story.

Feel free to ask your doubts in the comments. Want to thank me? Buy Me a Coffee.

Please clap, follow, and share it with your friends if you find this helpful or if it is adding value to you.

Connect with me on LinkedIn if you are looking for coding tips, interview preparation, and interview tips. Check out my other interview-oriented articles here.

Похожие статьи