What is the meaning of public static void main(String args[])
?
public
is an access specifier meaning anyone can access/invoke it such as JVM(Java Virtual Machine.static
allows main()
to be called before an object of the class has been created. This is neccesary because main()
is called by the JVM before any objects are made. Since it is static it can be directly invoked via the class.
class demo {
private int length;
private static int breadth;
void output(){
length=5;
System.out.println(length);
}
static void staticOutput(){
breadth=10;
System.out.println(breadth);
}
public static void main(String args[]){
demo d1=new demo();
d1.output(); // Note here output() function is not static so here
// we need to create object
staticOutput(); // Note here staticOutput() function is static so here
// we needn't to create object Similar is the case with main
/* Although:
demo.staticOutput(); Works fine
d1.staticOutput(); Works fine */
}
}
Similarly, we use static sometime for user defined methods so that we need not to make objects.
void
indicates that the main()
method being declared
does not return a value.
String[] args
specifies the only parameter in the main()
method.
args
- a parameter which contains an array of objects of class type String
.