Pages

Thursday, August 13, 2020

Understanding public static void main (String[ ] args)) in Java

1. Overview


In this tutorial, We'll understand each term in public static void main(String[] args) method in java.

public static void main() is called as psvm sometimes.

In Java, public static void main plays a vital role in running applications and important topic in SCJP or OCA certification exam.

we will discuss now the following in this post.


Java public static void main(String[ ] args)) method usage, Rules, Example, Interview Questions


We will discuss in-depth in the following areas.
Rules
Explanation of each keyword
Examples
Real-time scenario
Negative cases.
What will happen if we apply different keywords
Interview questions.
Summary 


Java public static void main(String[ ] args)) method usage, Rules, Example, Interview Questions





When we execute a java program, JVM should know from which point it has to start the program execution. JVM knows only one method that is main method. If we try to change the main method name to different name then it gives compile time error.

2. Syntax

The main method declaration has the follow the following rules and has to meet one of them, all these are valid.

public static void main(String[] args)
public static void main(String... args)
static public void main(String args[])

public static void main method example:


package java.w3schools.main.method;

public class MainDemo {
    public static void main(String[] args) {
        System.out.println("public static void main method demo class");
    }
}

Output:

public static void main method demo class

3. Explanation of each keyword in public static void main


We will now discuss the usage of each keyword in the public static void main method.

Static:

Static is a keyword in java which is can be applied on a variable, method, static block, inner class. Static is used to invoke any static method without creating or instantiating an object for a class. Here, we have not created an object for class MainDemo and while executing the class run-time directly JVM will call the main method. Because of this main method is declared as static.


More about Static:

Static initializers and Initializer blocks in Java


Static block Importance in Java

Public:

Public keyword is used when you want to call a method from outside class. Here the main method is invoked by the JVM system class. So the main method should be declared as public.

Public is one of the access modifiers in java.

Void:

Usually, if any method has return type means whoever is invoking the method they will get the required output in that class. Here, JVM is invoking the main method. If the main method is returning any value then JVM does not know what to do with that value. So java people have decided to keep the main method return type as void.

Main:

While executing any program in java, JVM knows only about the main method. So the main method should be part of the class with argument String[] array.

4. public static void main Examples

Example 1:

We can use any order on public and static. The following two are legal.

public static void main(String[] args)
static public void main(String[] args)


package java.w3schools.main.method;

public class MainRuleDemo {
    public static void main(String[] args) {
        System.out.println("public static void main(String[] args) example");
    }
}

Output:

public static void main(String[] args) example

Example 2:

We can use varargs in method argument declaration or method signature. This is legal.


public class MainRuleDemo {
     static public void main(String... args) {
        System.out.println("public static void main(String... args) varargs example");
    }
}

Output:

public static void main(String... args) varargs example

Example 3:

As mentioned earlier, the below two are legal and the array declaration is at the end of the argument name.

static public void main(String args[])
public static void main(String args[])


public class MainRuleDemo {
     static public void main(String args[]) {
        System.out.println("static public void main(String args[]) example");
    }
}

5. Real-time scenario

The main method is essentially used in financial companies to run the java process in the background for a given time interval. Following is a simple example to start a java process in the background.

Example:

nohup java -jar /proj/module.jar &

here module.jar is an application jar file.

& symbol:

The & switches the program to run in the background.

The nohup utility:

This makes the command passed as an argument run in the background even after you log out.

If your application jar has many classes that have the main method then we need to pass the class name (fully classified name of the class) after the jar file name and its parameters as below.

nohup java -jar /proj/module.jar java.w3schools.DemoClass arg1 arg2 &

6. Interview Questions

Nowadays interviewers asking many questions on the main() method. These can be tricky if you are confused. Some interview questions on the main method that my friends have experienced.

6.1. How many ways we can declare the main method?

Ans: 3 ways.

6.2. Can we declare the main method as private or protected or default?

private:  Nope. If we declare as private then it is not visible to JVM. So, it should not declare as private and get a run-time error.

private static void main(String args[]) { }

Error message:

Error: Main method not found in class java1.w3schools.main.method.MainRuleDemo, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

protected: same as above and get a runtime error. the protected method is available for its subclasses.

protected static void main(String args[]) { }

default: same as above and get a runtime error. default means no keyword is applied on method and default method is visible within the package.

static void main(String args[]) { }

6.3. What will happen if declare the main method as non-static?

If we declare the main method as non-static then we will get a runtime error saying.

Error: Main method is not static in class java1.w3schools.main.method.MainRuleDemo, please define the main method as:
   public static void main(String[] args)

JVM will not able to call the main method since JVM does not create an object for it. So, the main should be static.

6.4. What occurs if the main method returns some value or return type?


public class MainIntReturnDemo {
    public static int main(String args[]) {
        int intValue = 0;
        System.out.println("int returning main method");
        return intValue;
    }
}

Produces runtime error.

Error: Main method must return a value of type void in class java1.w3schools.main.method.MainRuleDemo, please

define the main method as:

public static void main(String[] args)

6. 5. Is the main method can be synchronized?

Yes. It is legal.

public class MainSynchronizedDemo {
    public static synchronized void main(String args[]) {
        System.out.println("synchronized main method");
    }
}

Output:

synchronized main method

6.6. Can we use the final on the main method?


public class FinalMainMethodDemo {
    public static final void main(String args[]) {
        System.out.println("final main method");
    }
}

Yes. It is legal. A final method can not be overridden in subclasses.

Output:

final main method

6. 7. What happens if no main method in a class?


public class NoMainMethodDemo {
       // no main method.
}

Produces a run-time error saying no main method found.

Error: Main method not found in class

6.8. If we have many main methods?


If we have multiple main methods then JVM will look for public static void main (String[] args). Look below the program has two main methods. JVM will look for the main method which takes String array as it's an argument.

public class MainRuleDemo {
    public static void main(String[] args) {
        System.out.println("default main method");
    }



    public static void main(StringBuffer buffer) {
        System.out.println("main method: StringBuffer argument");
    }
}

6.9. How to come out from a certain point of the main method?


Yeah, We can come out from any point of the class using the return statement.

if(count)

return;

To terminate we can exit() method.

System.exit(0);

If you know any interview question this please post us in a comment or using contact us page.


7. Key Points

The following are the key points of the public static void main method.

the main method should be as "public static void main(String[] args)".
Three legal ways to declare the main method.
varargs main method is legal.  main(String... args)
Can swap the order of public static.
main method argument should take String array. String[] args.
private, protected, default is not allowed and will get a run-time error.
can not use a return type for it.
Using the final and synchronized is legal.
If no method is not present then we will get "no main method found" error.

8. Conclusion

In this tutorial, We've explored in-depth on an understanding of public static void main.

Worked on valid and invalid examples on the main method.

Further in this article, Discussed on interview questions and answers. 


Ref

No comments:

Post a Comment

Please do not add any spam links in the comments section.