Adding a final keyword in the main method parameter works fine. Why does it not give any compiler error / exception since I have modified the standard main method of Java?
public class StackOverFlow {
public static void main(final String... args) {
System.out.println("Hi");
}
}
Now see if I code:
public class StackOverFlow {
public static void main (String... args) {
String[] str = {"I ", "haven't ", "received ", "my ", "answer." };
args[0] = "hi";
System.out.println(args[0]);
args =str;
for(int i=0; i<args.length; i++) {
System.out.print(args[i]);
}
}
}
For the above coding when you run the program by passing an argument as:
javac StackOverFlow Nisrin
My program output is
hi
I haven’t received my answer.
Now the same thing with the final
keyword
public class StackOverFlow {
public static void main (final String... args) {
String[] str = {"I ", "haven't ", "received ", "my ", "answer." };
args[0] = "hi";
System.out.println(args[0]);
args =str;
for(int i=0; i<args.length; i++) {
System.out.print(args[i]);
}
}
}
It gives me an error: the final parameter, args
, may not be assigned.
Because now I am assigning str
to args
.
This means I have done a big difference by adding the final
keyword in the parameter and making it constant in the main method, the very entry-point of a Java Program. I am changing the signature of the main method. Then why am I not getting any compile error or runtime error?