0

I am confused. I tried using

final String usr;

and trying to change its value never worked, but when I used an array final String[] usr = {"", ""};, it worked. I even accessed it from this

sgnup.addActionListener(new ActionListener(){
     public void actionPerformed(ActionEvent e){
         user[0] = sUsr.getText();
      }
 });

I find it very confusing because my understanding of final is that a variable declared with final and add a value to it, the value never changes. But why did an array with final work? I can even set a text to one of those arrays.

Dici
  • 25,226
  • 7
  • 41
  • 82
rexendz
  • 3
  • 1
  • 1
  • 5

2 Answers2

1

Yes, because you don't change the reference of usr but what it contains. final block you from doing something like usr = new String[5]; (change the usr to another array) but the content of the array can be changed without problems.

final String[] a = new String[5];
a = new String[3]; // illegal

final String[] a = new String[5];
a[0] = "Hello"; // legal, i don't change a but what is inside a[0]
Marco Acierno
  • 14,682
  • 8
  • 43
  • 53
0

In Java, a variable of any object type (including any array) actually is a reference to an object, not the object itself. When you declare a variable to be final, it means that the reference will not change, meaning that the object it references will always be the same object. However, if the internal state of the object can still change without the final modifier, then adding final won't prevent the internal state of the referenced object from changing. In particular for a final array, the array reference itself cannot be reassigned, but the array elements can still change.

In your situation, you can avoid using an array by simply eliminate the final modifier from the String variable.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521