final keyword error Java

Discussion in 'App Development' started by Grinda21, Apr 13, 2023.

  1. Grinda21

    Grinda21

    In Java, we use the final keyword with variables to indicate that their values should not be modified. But, I see that you may edit the value in the constructor / methods. If the variable is static, this is another compilation fault.

    The code is as follows:
    Code:
    import java.util.ArrayList;
    import java.util.List;
    
    class Test {
      private final List foo;
    
      public Test()
      {
          foo = new ArrayList();
          foo.add("foo"); // Modification-2
      }
      public static void main(String[] args)
      {
          Test t = new Test();
          t.foo.add("bar"); // Modification-3
          System.out.println("print - " + t.foo);
      }
    }
    The code above is error-free.

    Now make the variable static:

    Code:
    private static final List foo;
    It is now a compilation error. How does this final work in practise?
     
  2. Final does not mean immutable, you still can modify the contents of the collection.

    https://en.wikipedia.org/wiki/Final_(Java)

    What it means is:
    "A final variable can only be initialized once, either via an initializer or an assignment statement".

    You essentially can create only one instance of the object but the contents can be modified.
     
    Grinda21 and Statistical Trader like this.
  3. Make sure that you don't access to private attributes outside the actual class, add a getter and a setter.
    Also define a type for you collections, you don't want the runtime to assign any type it wants.

    Code:
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test {
        private final List<String> fooList;
    
        public void addFoo(String foo) {
            this.fooList.add(foo);   
        }
    
        public List<String> getFoo() {
            return fooList;
        }
    
        public Test() {
            fooList = new ArrayList<String>();
        }
    }
     
    Grinda21 likes this.
  4. I implemented immutability of my objects by using mprotect to mark the section of ram the buffer contents are stored in as read only . This only works for objects backed by native memory
     
    Grinda21 likes this.
  5. Grinda21

    Grinda21

    Thank you for that
     
  6. Grinda21

    Grinda21

    Thanks it helped me
     
  7. Grinda21

    Grinda21

    Got it
     
  8. You could patch the jvm to do it using the same way swap files and memory mapped files are done .. mprotect violation signals a handler to fetch the segment and then return the execution flow to the point the segmentation violation was triggered
     
  9. ph1l

    ph1l