Search code examples
javafinal

Immutable function arguments in java


I am new to java and I've come across this question: in C/C++ we have const modifier which makes function parameters Immutable, Therefore user is confident that the arguments they pass wont change.

But I could not find the same thing in java. Sure final modifier makes the field assignable only once and it works fine to some extent. But what about Objects that I need to modify before sending?(I could make a final copy of the Object but I don't find it good enough. correct me if I'm wrong). what about Object's fields? how we can pass an Object in a way that we would be confident of the integrity of the Object?


Solution

  • In Java immutability is an intrinsic property of the type.

    For instance String is immutable. No need for const. StringBuilder, CharSequence are, or maybe, mutable. So will need a copy. In these cases a quick .toString(). will do the job.

    C++ defaults to an implicit copy for arguments. Copying is in someways a better version of immutability. const & is kind of effectively a way of getting a copy without paying for it. (I'm sure many people will strongly disagree with this paragraph.)