Final Keyword In Java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BarryA
    New Member
    • Jun 2022
    • 19

    #1

    Final Keyword In Java

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

    Code:
    public class bytes {
    
        public static void main(final String... args) {
            System.out.println("Hi");
    
        }
    }
    Now let's see if I can code:

    Code:
    public class bytes {
    
        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:

    Code:
    javac bytes Nisrin
    The output of my programme is

    Code:
    hi
    I have yet to receive a response.
    Now repeat the process with the final keyword.

    Code:
    public class bytes {
    
        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.

    As I am following this source https://www.scaler.com/topics/java/f...yword-in-java/, this indicates I have made a significant difference by include the final keyword in the argument and making it constant in the main method. I'm updating the primary method's signature. So, why am I not receiving any compilation or runtime errors?
Working...