$show=/label

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

SHARE:

A Quick Explanation and Understanding public static void main(String args) method. Interview Questions on public static void main.

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

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Understanding public static void main (String[ ] args)) in Java
Understanding public static void main (String[ ] args)) in Java
A Quick Explanation and Understanding public static void main(String args) method. Interview Questions on public static void main.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6l5MYSiOIjPeKKTPpgIkwlGLJIafz_ZYHqU1PdDsFByHtzYHYvl4_hLRTGJanl2ur1WfdRjYObS60bom_Upn9SN6Yt7DL4atQlYGk4Yonuuc4iwatShK2HYB3qYHGNVCFqKy52Fyasuk/s400/Java+public+static+void+main%2528String%255B+%255D+args%2529%2529+method.PNG
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6l5MYSiOIjPeKKTPpgIkwlGLJIafz_ZYHqU1PdDsFByHtzYHYvl4_hLRTGJanl2ur1WfdRjYObS60bom_Upn9SN6Yt7DL4atQlYGk4Yonuuc4iwatShK2HYB3qYHGNVCFqKy52Fyasuk/s72-c/Java+public+static+void+main%2528String%255B+%255D+args%2529%2529+method.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2017/08/java-public-static-void-mainstring-args.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2017/08/java-public-static-void-mainstring-args.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content