Saturday, April 19, 2025

final

A final variable is a variable whose value doesn't change once it has had a value assigned to it. In other words, the variable is a constant. Any variable can be made final by applying the keyword final to its declaration.

    class TestClass{  
      final int x = 10;    
      final static int y = 20;   
      public static void main(final String[] args){    
      final TestClass tc = new TestClass();         
      //tc.x = 30; //will not compile.       
      //y = 40; //will not compile.     
      //args = new String[0]; //will not compile      
      //tc = new TestClass(); //will not compile   
      System.out.println(tc.x+" "+y+" "+args+" "+tc);  
      }
    }
    
 
Observe that in the above code, I have made an instance variable, a static variable, a method parameter, and a local variable final. It prints 10 20 [Ljava.lang.String;@52d1fadb TestClass@35810a60 when compiled and run.
You cannot reassign any value to a final variable, therefore, the four statements that try to modify their values won't compile. Remember that when you make a reference variable final, it only means that the reference variable cannot refer to any other object. It doesn't mean that the contents of that object can't change. For example, consider the following code:
 
      
      class Data{    
        int x = 10; 
      }
      public class TestClass {   
        public static void main(String[] args){ 
        final Data d = new Data();
        //d = new Data(); //won't compile because d is final       
        d.x = 20; //this is fine because we are not changing d here.     
       }
      }
 In the above code, we cannot make d refer to a different Data object once it is initialized because d is final, however, 
 we can certainly use d to manipulate the Data in object to which it points.     
     
      

No comments:

Post a Comment

CompletableFuture

  Welcome back to  our concurrency series ! In our first discussion, we likely touched on the traditional models of threading. Today, we’re ...