Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback, please email oracle-forums_moderators_us@oracle.com

Final Keyword In Java compile

user-nlz8hMar 27 2023

Using a final keyword in the main method parameter solves the problem. Why is there no compiler error or exception since I updated Java's standard main method?

public class oracle {

    public static void main(final String... args) {
        System.out.println("Hi");

    }
}

Now let's see if I can code:

public class oracle {

    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]);
        }

    }

}

When you execute the programme using the above coding, pass an argument as:

javac oracle Nisrin

The result of my programme is

hi

I have yet to receive a response.

Now repeat the process with the final keyword.

public class oracle {

    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 throws an error saying that the final parameter, args, cannot be assigned.

Because I am now assigning str to args.

This indicates that by including the final keyword in the argument and following this guidance, I made a significant impact by making it a constant in the main method, the very beginning of a Java programme. I'm updating the primary method's signature. So, why am I not receiving any compilation or runtime errors?

Comments
Post Details
Added on Mar 27 2023
3 comments
256 views