简体   繁体   中英

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

System.out.println("hello modified x value is:"+ x);

If you delete on the this line code your app will succesfully run

Using function call to System.out.println("hello modified x value is:"+ x); is causing you the problem.

Because you are not allowed to do that in Class level scope. And it should happen in a block or other methods.

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

For compile-time exception, It's good create and run the programms using any Java IDE's -Eclipse,STS,Netbeans and IntelliJ for earlier compile detections. In above code,printing statement
System.out.println("hello modified x value is:"+ x); should be in block or in a method.

The problem you are facing here is in here you are trying to write a statement purely in the class body without having a method or instance initializer. In Java you can't do that. So please include the below statement inside a method or a instance initlalizer.

System.out.println("hello modified x value is:"+ x);

Alternative 1 (Using a method):

public void sampleMethod(){

   System.out.println("hello modified x value is:"+ x);

}

Alternative 2 (Using an instance initialaizer):

{

   System.out.println("hello modified x value is:"+ x);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM