Which is the first method called when Java executes a program? - java

I am learning core Java and I have one question, "Which is the first method called when the program is executed?"

That would be the main method.
It should be declared as
public static void main(String[] args)
It needs to be public, since the JVM should have access to call the method.
It needs to be static, as no objects are instantiated when the program starts
It takes an array of Strings as argument (coming from the command-line)
Some good links to have a look at:
The main Method (from the official Getting started trail)
What is the main method
Entry point for Java applications: main(), init(), or run()?
Some people may recommend you to write
public static void main(String... args)
this is equivalent to String[] args if you're using a compiler of version 1.5 or later. (I would discourage this unless you're extensively calling your main method internally with a varying number of arguments.)
Others may suggest
public static void main(String args[])
This is also equivalent, but discouraged by the Java Coding Convention.

It's usually main. But in this program, it's pain:
public class WhatThe {
public static final int x = pain();
public static int pain() {
System.out.println("pain!");
return 0;
}
public static void main(String[] args) {
System.out.println("main");
}
}
As it is in this one:
public class WhatThe {
static {
pain();
}
public static void pain() {
System.out.println("pain!");
}
public static void main(String[] args) {
System.out.println("main");
}
}
This is unlikely to be useful knowledge, but it's something to be aware of.

public static void main(String ar[])
Java programs start executing at the main method, which has the following method heading:
public static void main(String[] args)
public static void main(String... args) //java 1.5+
public static void main(String args[])
Read more at docs

In addition to aioobes answer
A usual way to start a simple java program is to execute java like this:
java com.example.MyClass
com.example.MyClass (or your fully qualified class name) needs to have a main method with exactly this signature:
public static void main(String[] args)
(you're only allowed to change the name of the parameter, like arguments instead of args). The virtual machine will try to load the named class and try to invoke this static method which will "start the Java program".

The main method will be called first,control goes to main method first which has the method headings:
public static void main(String[] args) or
public static void main(String args[])

Related

Correct syntax for main method

This is a total beginners question. I am new to java and have been browsing StackOverflow and CodeReview. I am finding these two different formats being used:
example 1:
public static void main(String args[])
or
example 2:
public static void main(String[] args)
This is what I have in my course notes:
These words are called modifiers. The main() method is also preceded by the word void to indicate that it does not return any value. Also the main() method always has a list of command line arguments that can be passed to the program
main(String[] args)
which we are going to ignore for now.
So, as you can see, we have been told to ignore this for now, but I'd like to know:
Is there an actual difference between these, if so, what?
From the Java Language Specification:
The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.
For example:
byte[] rowvector, colvector, matrix[];
This declaration is equivalent to:
byte rowvector[], colvector[], matrix[][];
Actaully there are no difference between two main-method defination and both are correct.
But by convention java prefers array declaration as String[] args rather than String args[].
So it is more conventional -
public static void main(String[] args){...}
main method accepts arguement in String array
following ways are accepted
public static void main(String args[])
public static void main(String []args)
public static void main(String... args)
All these are valid declarations of the main function in Java.
public static void main(String[] args) {
// code
}
static public void main(String[] args) {
// code
}
static public void main(String args[]) {
// code
}
public static void main(String[] MarkElliotZuckerberg) {
// code
}
public static void main(String... NewYork) {
// code
}
The keywords public and static are interchangeable but mandatory.
The parameter of the main method can take the var-args syntax.
The name can be anything..!
These are examples of invalid main method declarations -
static void main(String[] args) {
// public is missing
}
public void main(String args[]) {
// static is missing
}
public static int main(String... Java) {
// return type not void
return 0;
}
public void Main(String args[]) {
// "main" not "Main"
}
public void main(string args[]) {
// "String" not "string"
}
public void main(String.. SayHi) {
// Ellipses is 3 dots !
}
I'm sorry if the source code is not soo readable... I always had trouble posting source code... :P ... Hope this helps...! If it did, let me know by commenting..!
Source - Java Tutorials on Theory of Programming

Star secondary class Java

Okay.. so, this may sound stupid. I have two classes. Foo.class, and Bar.class
Foo.class' Code:
public static void main(String[] args){ startBar(); }
Bar.class' Code:
public static void main(String[] args){ echo "HI"; }
I want the output to be "HI".. As in, i want to start my secondary class inside the first one.. I am probably doing a horrible job at explaining this. Things to keep in mind if you do understand what i want, i don't want a process builder that starts the bar.class.. I need it to all run in the one thingy..
Foo class
public static void main(String... args){
Bar.main(args);
}
Bar class
public static void main(String... args){
System.out.println("Hi");
}

In how many different ways can we declare a main method in java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I how many different ways can we declare a main method in java?
class A{
public static void main(String args[]){
System.out.println("hi");
}
}
Now I want different ways to create a main method. Could you explain me?
public static void main(String[] argument)
public static void main(String argument[])
public static void main(String... args)
public static synchronized void main(String... args)
public static strictfp void main(String... args)
public static final void main(String... args)
From the Java Documentation there are only two ways:
public static void main(String[] args)
and
public static void main(String... args)
The multiple ways of declaring the main method is (As everyone explained above)
public static void main(String[] args) or public static void main(String args[])
public static void main(String... args).
The positions of public and static may change as the programmer wish. But remember void should always come before main method. You can also use any parameters for the main method but the main with String[] args will only be executed first.
You can also execute a java program without a main method. For this you need to make use of static block with a break statement at the end.
Look at the methods below. Which ones will not compile? Which ones will compile, but can’t be used as entry points into an application? Which ones compile and act as you would expect a main method to act?
if any doubts in this regard please verify the following link
http://rationalpi.wordpress.com/2007/01/29/main-method...
you can also do this
static public void main(String args[])
There are two possible ways
By using single argument
public static void main(String args) { .. }
Or by varargs
public static void main(String... args) { .. }
Keep in mind that args in (String args) is just a argument name.You can use anything here like (String abc) , (String myargs) etc.
One last thing is that ,you can also pass a multi dimensional array from main like this
public static void main(String[][] args) { .. }
You can use var-args instead of array:
public static void main(String... args) {
Also this
public static void main(String... args)

legal main method signature in java

class NewClass{
public static void main(String a){
System.out.print("Hello");
}
}
When I'm trying to execute above code, then it shows an error: main method not found. When I changed the signature to
public static void main(String... a)
or
public static void main(String a[])
Then it works. My question is how many different ways we can write legal main method signature? And what does the String... version mean?
Simply because that's the requirement of Java.
A main method/entry point to a program must be a method declared as public static void main(String[] args). Your method that was declared with a String parameter was similar but not compatible.
An array is not the same as a single String - if someone invoked Java with three command-line parameters, the JVM would create a three-element string array, and then how would it pass this into your method that only takes a single string?
So in that case you were trying to launch a Java program based on a class that did not have an main method to act as an entry point.
(The reason why String... works is because this is syntactic sugar for an array parameter, and compiles down to a method with the same signature.)
Finally, i found the answer of my question in Sun Certified Programmer for Java 6 book.
First question was, how many different legal ways of using main
method?
Legal main method signatures are
public static void main(String a[])
public static void main(String[] a)
public static void main(String... a)
what does (String... a) means ??
To declare a method using a var-args parameter, we need to follow with an ellipsis(...) then use space and then name of the array that will hold the parameter received. So, above term known as Variable Argument and which means 0 to many.
And, rules of using variable argument parameters is, must be the last parameter in the method signature and can have only one var-args in a method.
Eg:
void myfunc(String... a) //legal
void myfunc(String a...) //illegal
void myfunc(String a,int... b) //legal
void myfunc(String... a,int b) //illegal
Its default in java. java compiler expects an array of command line arguments. thats why you need to specify string args[] or String...
public static void main(String... a) --> Is a method with a variable argument list, that is internally(in the method) treated as an array.
Legal Main Method Signature:
public static void main(String a[])
static public void main(String a[])
public static void main(String[] a)
static public void main(String[] a)
public static void main(String... a)
static public void main(String... a)
All these are valid/legal declarations of the main function in Java.
public static void main(String[] args) {
// code
}
static public void main(String[] args) {
// code
}
static public void main(String args[]) {
// code
}
public static void main(String[] MarkElliotZuckerberg) {
// code
}
public static void main(String... NewYork) {
// code
}
The points to remember is -
The keywords public and static are interchangeable but mandatory.
The parameter of the main method can take the var-args syntax.
The name can be anything..!
Just for practice.. :P ...These are examples of invalid main method declarations -
static void main(String[] args) {
// public is missing
}
public void main(String args[]) {
// static is missing
}
public static int main(String... Java) {
// return type not void
return 0;
}
public void Main(String args[]) {
// "main" not "Main"
}
public void main(string args[]) {
// "String" not "string"
}
public void main(String.. SayHi) {
// Ellipses is 3 dots !
}
Some give errors, while others simply overload the main method... Hope this helps...! If it did, let me know by commenting..!
Source - Java Tutorials on Theory of Programming
public static void main(String a[]) is the main entry point signature for a typical Java program. So you should get on with this method signature.
Java Runtime tries to find a method with name "main" with argument types "String[]". It is just like using reflection for finding a method with type arguments as String[].
Also String[] are used so that the runtime can pass the program arguments or Command Line arguments that are provided. It is like the runtime tokenizes the arguments with white space characters and then calls this method named "main".
The method main must be declared public, static, and void. It must accept a single argument that is an array of strings. This method can be declared as either
public static void main(String[] args)
or
public static void main(String... args)
You can also refer to Oracle Java specification documentation for more understanding
Chapter 12 Execution - Section 12.1.4 Invoke Test.main
You need exactly the String[] args parameter (it's an array).
The reason is that you need to declare the main() method with a specified signature (and a method signature contains its name, number of its parameters and the types of the parameters).
So if you create a function which a different parameter type (String vs. String array), it is not recognized.

Using ellipsis in main method?

If i use ellipsis in main method would it make any difference?
public static void main(String... args) {
}
No difference. That "ellipsis" syntax is called varargs, whose parameter type is actually an array.
This means there are actually three possible signatures of a valid main() method:
public static void main(String[] args) {}
public static void main(String... args) {}
public static void main(String args[]) {}
It does not make any difference, since the JVM turns the ellipsis (also called "varargs") into an array at "compile" time:
void myMethod(final X... args)
is exactly the same as
void myMethod(final X[] args)
or (less frequent)
void myMethod(final X args[])
It is the same. Given the following class files:
$ cat MainEllipsis.java
public class MainEllipsis {
public static void main(String... args) {}
}
$ cat MainArray.java
public class MainArray {
public static void main(String[] args) {}
}
After compiling (javac MainEllipsis.java MainArray.java), we can check the compiled signatures using javap -s <class>:
> javap -s MainEllipsis
<...snip...>
public static void main(java.lang.String...);
descriptor: ([Ljava/lang/String;)V
and
> javap -s MainArray
<...snip...>
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
[Ljava/lang/String; represents the String[] type, showing that the generated method signatures are the same.
Apart from what others have mentioned, I think this can be useful for writing unit tests of your main() method also.

Categories