This question has already been answered:

Good day.

There was one question. There is a condition for the input value:

private boolean isValid() { String message; //если < 10 if (Integer.parseInt(jtxtInput.getText()) < 10) message = "Минимальное значение: 10"; else return true; JOptionPane.showMessageDialog(frame, message, "Ошибка", JOptionPane.WARNING_MESSAGE); return false; } 

Remembering that String objects are immutable, I decided to check this and initialized the message:

  String message = "test"; 

However, no error occurred. The question is why, because in fact we got a variable String?

Thank you.

Reported as a duplicate by pavlofff members, Community Spirit Jul 25 '16 at 4:10 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    You did not change the object, you reassigned the variable. - etki
  • But speaking of variables, we do not mean primitives, such as int, boolean, etc.? - Dmitry08
  • I do not understand what the primitives are about, but when you reassign a variable containing a primitive, you do nothing with the original value in the same way, but simply write a new one into the variable. - etki
  • Yes, I understand what you are saying, thank you. - Dmitry08

1 answer 1

You did not change the message object, you assigned a value to it, the String immutability is expressed in that the assigned value "test" cannot be changed, there are no methods for this, you can only assign a new value to the message reference, but this will be a completely different object. In order that message cannot be assigned another value, it must be declared as final.

  • Yes, I completely agree, thank you. - Dmitry08