Why do you need a main method to use class methods in a class?
I can do it:
import java.util.ArrayList;
public class Array {
public static void main(String args[]){
ArrayList<String> myList = new ArrayList<String>();
myList.add("S");
}
}
However, I CAN'T do this:
import java.util.ArrayList;
public class Array {
ArrayList<String> myList = new ArrayList<String>();
myList.add("S");
}
Why should I include the main method?
source to share
Because Java classes are made up of methods and blocks. You cannot have an expression like
myList.add("S");
Finally, your application requires an entry point , and the Java virtual machine starts with a call main()
as described in JLS -12.1.4. InvokeTest.main
Finally, after completing the initialization for the class
Test
(for which there could be another subsequent loading, binding and initialization), the method is calledmain
ofTest
.The main feature of the method must be declared
public
,static
andvoid
. It must specify a formal parameter ( Β§8.4.1 ) of which the declared type is an arrayString
.
source to share