Write a program in Java to demonstrate the use of 'final' keyword in the field declaration. How it is accessed using the objects.

Here's an example Java program that demonstrates the use of the final keyword in a field declaration and how it is accessed using objects:

Create a Example.java file and write this code in it.

public class Example {
    private final int num1;
    public final String str1;

    public Example(int num1, String str1) {
        this.num1 = num1;
        this.str1 = str1;
    }

    public static void main(String[] args) {
        Example example1 = new Example(10, "Hello");
        Example example2 = new Example(20, "World");

        // Access the final fields using objects
        System.out.println("example1.num1 = " + example1.num1);
        System.out.println("example1.str1 = " + example1.str1);
        System.out.println("example2.num1 = " + example2.num1);
        System.out.println("example2.str1 = " + example2.str1);

        // Attempt to modify the final fields (will result in compilation error)
        // example1.num1 = 30;
        // example1.str1 = "Goodbye";
    }
}


In this example, we have an Example class with two final fields: num1 and str1. The num1 field is set in the constructor and cannot be modified afterwards. The str1 field is also final, but can be set outside of the constructor. Once a final field is set, it cannot be modified.

In the main() method, we create two Example objects and access their final fields using object dot notation. We can see that the final fields are accessible using the objects.

If we attempt to modify the final fields (by uncommenting the last two lines of code), we will get a compilation error. This demonstrates that final fields cannot be modified once they are set.

Comments