String args java что это
Перейти к содержимому

String args java что это

  • автор:

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.

Как работает метод main в Java

main в Java – это обычно первый метод, о котором узнают начинающие, потому что он является точкой входа в программирование на Java. Метод main может содержать код для выполнения или вызова других методов и его можно вложить в любой класс, который является частью программы. Более сложные программы обычно содержат класс, в котором есть только метод main. Название класса, содержащего main, может быть любым, но обычно его называют просто класс Main.

В следующих примерах класс, содержащий метод main, называется Test:

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

Синтаксис метода Main

Синтаксис метода всегда выглядит так:

Изменить здесь можно только название аргумента массива String. Например, вы можете изменить args на myStringArgs. Аргумент массива String может быть записан как String… args или String args[].

Модификатор public

Чтобы JRE могла получить доступ к main методу и выполнить его, модификатором доступа этого метода должен быть public. Если метод не является public, доступ к нему будет ограничен. В следующем примере кода в методе main модификатор доступа public отсутствует:

Возникает ошибка при компиляции и запуске программы. Это происходит потому, что метод main не является общедоступным и JRE не может его найти:

Модификатор static

При запуске Java-программы объект класса отсутствует. Чтобы JVM могла загрузить класс в память и вызвать main метод без предварительного создания экземпляра класса, main методу нужен модификатор static. В следующем примере кода в main методе нет модификатора static:

Так как метод main не имеет модификатора static, при компиляции и запуске программы возникает следующая ошибка:

Модификатор void

Каждый метод Java должен указывать тип возвращаемого значения. Тип возвращаемого значения main метода в Java — void, поскольку он ничего не возвращает. Когда main метод завершает выполнение, программа Java завершает работу, поэтому в возвращаемом объекте нет необходимости. В следующем примере метод main пытается что-то вернуть при типе возврата void:

При компиляции программы возникает ошибка, потому что Java не ожидает возврата значения, когда тип возврата void:

Метод main

При запуске программа Java всегда ищет метод main. Данный метод может называться только так, его нельзя переименовывать. В следующем примере кода мы для наглядности переименовали main метод в myMain:

Во время компиляции и запуска программы возникает ошибка, так как JRE не находит метод main в классе:

Массив String[] args

Main принимает один аргумент массива String. Каждая строка в массиве является аргументом командной строки. Их можно использовать, чтобы влиять на работу программы или передавать в нее информацию во время выполнения. Далее показано, как вывести аргументы командной строки при запуске программы:

Когда скомпилируете программу и потом запустите ее с несколькими аргументами командной строки, разделенными пробелами, аргументы будут выводиться в терминале:

java Test 1 2 3 “Testing the main method”

Заключение

В этой статье мы подробно остановились на каждом компоненте метода main в Java.

String args java что это

In Java programs, the point from where the program starts its execution or simply the entry point of Java programs is the main() method. Hence, it is one of the most important methods of Java, and having a proper understanding of it is very important.

The Java compiler or JVM looks for the main method when it starts executing a Java program. The signature of the main method needs to be in a specific way for the JVM to recognize that method as its entry point. If we change the signature of the method, the program compiles but does not execute.

The execution of the Java program, the java.exe is called. The Java.exe in turn makes Java Native Interface or JNI calls, and they load the JVM. The java.exe parses the command line, generates a new String array, and invokes the main() method. A daemon thread is attached to the main method, and this thread gets destroyed only when the Java program stops execution.

Java main() Method

Syntax of main() Method

The most common in defining the main() method is shown in the below example.

Every word in the public static void main statement has got a meaning in the JVM that is described below:

1. Public

It is an Access modifier, which specifies from where and who can access the method. Making the main() method public makes it globally available. It is made public so that JVM can invoke it from outside the class as it is not present in the current class.

Output

2. Static

It is a keyword that is when associated with a method, making it a class-related method. The main() method is static so that JVM can invoke it without instantiating the class. This also saves the unnecessary wastage of memory which would have been used by the object declared only for calling the main() method by the JVM.

Output

3. Void

It is a keyword and is used to specify that a method doesn’t return anything. As the main() method doesn’t return anything, its return type is void. As soon as the main() method terminates, the java program terminates too. Hence, it doesn’t make any sense to return from the main() method as JVM can’t do anything with the return value of it.

Output

4. main

It is the name of the Java main method. It is the identifier that the JVM looks for as the starting point of the java program. It’s not a keyword.

Output

5. String[] args

It stores Java command-line arguments and is an array of type java.lang.String class. Here, the name of the String array is args but it is not fixed and the user can use any name in place of it.

Output

Apart from the above-mentioned signature of main, you could use public static void main(String args[]) or public static void main(String… args) to call the main function in Java. The main method is called if its formal parameter matches that of an array of Strings.

FAQs on Java main() Method

Q1. Can the main method be int? If not, why?

Output

Java does not return int implicitly, even if we declare the return type of main as int. We will get a compile-time error

Output

Now, even if we do return 0 or an integer explicitly ourselves, from int main. We get a run time error.

Explanation of the above programs:

The C and C++ programs which return int from main are processes of Operating System. The int value returned from main in C and C++ is exit code or exit status. The exit code of the C or C++ program illustrates, why the program was terminated. Exit code 0 means successful termination. However, the non-zero exit status indicates an error.

For Example exit code 1 depicts Miscellaneous errors, such as “divide by zero”.

The parent process of any child process keeps waiting for the exit status of the child. And after receiving the exit status of the child, cleans up the child process from the process table and free the resources allocated to it. This is why it becomes mandatory for C and C++ programs(which are processes of OS) to pass their exit status from the main explicitly or implicitly.

However, the Java program runs as a ‘main thread’ in JVM. The Java program is not even a process of Operating System directly. There is no direct interaction between the Java program and Operating System. There is no direct allocation of resources to the Java program directly, or the Java program does not occupy any place in the process table. Whom should it return an exit status to, then? This is why the main method of Java is designed not to return an int or exit status.

But JVM is a process of an operating system, and JVM can be terminated with a certain exit status. With help of java.lang.Runtime.exit(int status) or System.exit(int status).

Q2. Can we execute a Java program without the main method?

Ans:

Yes, we can execute a Java program without a main method by using a static block.

A static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by ClassLoader, It is also known as a static initialization block, and it goes into the stack memory.

Q3. Can we declare the main() method without String[] args?

Ans:

Yes, we can declare the main() method without String[] args. Although it will generate an error message if we directly try to execute the main method inside the driver class as done in the below example.

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

Ashay Nayak

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *