-3
public class x {
    private final String a;

    public void x() {
        a = "Hi";
        System.out.println(a);
    }
}

private final String a; <- this line is showing error that 'a' is not initialized.

I tried private final String a = "";

And a = "Hi";

Then it says I cannot assign a value to final variable.

How do I modify or assign new value to final String in another method?

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Ed Lee
  • 33
  • 3

3 Answers3

3

You have an unwanted keyword "void" in there such that what you think is your constructor is actually a function definition. Just remove the void and all will be well:

public class x {
    private final String a;

    public x() {
        a = "Hi";
        System.out.println(a);
    }
}

As you see, you can set a final variable in a constructor if you didn't give it a value when you defined it.

You talk about modifying a in another method. You can't do that, as others have pointed out in the comments. That's the whole point of final. It declares that the value of a will be set once and will never change once set.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44
0

You can't modify a final value, so if you want to add "Hi" as a string to that final string you should initialize it like: private final String a = "Hi";

or if you want to modify it later you have to remove final.

0

For the final static variable, it is compulsory that you should perform initialization before class loading completion. You can initialize a final static variable at the time of declaration or inside the static block.

class Test {
    final static int x = 10;
    public static void main(String[] args)
    {
        System.out.println(x);
    }
}

OR in static block.

class Test {
    final static int x;
    static
    {
        x = 10;
    }
    public static void main(String[] args)
    {
        System.out.println(x);
    }
}
Jaswinder Singh
  • 731
  • 5
  • 20