Search code examples
javacompiler-errorsfinal

My java code with final keyword has error


// final keyword usage 
package workarea;
    
final class demo {
        
    final int x=10;
    ////compile time exception here because ‘x’ is final type
    System.out.println("hello modified x value is:"+ x);
    final void m1()
    {
        int x=2;
        System.out.println("hello modified x value is:"+x);
    }

    void m2()
    {
        System.out.println("hello modified m2 x value is:"+x);
    }

    public static void main(String abc[])
    {   
        demo df=new demo();
        System.out.println("welcome");
        df.m1();
        df.m2();
    }
}

this is my code and the error is :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

    at workarea.demo.main(demo.java:24)

The error message is for the code line where main is mentioned Help me correct this code


Solution

  • An initializer block may come in handy for you. So where you have:

    final int x=10;
     ////compile time exception here because ‘x’ is final type
    System.out.println("hello modified x value is:"+ x);
    

    instead do (with slight change to string message):

    final int x=10;
    {
        System.out.println("(in initializer block: x value is:"+ x);
    }
    

    This is an alternative to constructors or to supplement them as this code would be used in all constructors (if you were to add any).

    https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html