Please kindly guide? Adding a final keyword in the java main method parameter doesn't give any compile error / exception?
Nisrin Dhoondia
Data Scientist | Machine Learning | Deep Learning | Software Development | Fresher Robotics Programmer |
Adding a final keyword in the main method parameter works fine. Why it does 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 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 same thing with 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]);
}
}
}
Gives me an error: 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 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 I am not getting any compile error or exception?
Please kindly guide?
Development Team Lead at LTI - Larsen & Toubro Infotech
5 年And you can compile a class without main method , so you didnt get error at compile but if you run this program JVM first check main method which has standard and jvm could not found main nethid then it will give run time error
Development Team Lead at LTI - Larsen & Toubro Infotech
5 年Because nisrin we cant overload main so jvm only can accept String arg rather then final . So didnt write any non modifiers keyword as a paranthisis