Performance is a reason. But the MAIN REASON is about SECURITY. Are you surprised about this?
OK I’ll let you know..
Suppose you want to open a secured file which require the user authentication. Let’s say there are two users named huynguyen1 and huynguyen2 and they have their own password files password1 and password2, respectively. Obviously huynguyen2 should not have access to password1 file.
As we know the filenames in Java are specified by using String. Even if you create a File object, passing the name of file as a String only and that String is maintained inside the File object as one of its members.
huynguyen1 could have logged into using his credentials and then somehow could have managed to change the name of his password filename (a String object) from password1 to password2 before JVM actually places the native OS system call to open the file. This would have allowed huynguyen1 to open huynguyen2‘s password file.
Understandably, it would have resulted into a big security flaw in Java. I understand there are so many ‘could have’s here, but you would certainly agree that it would have opened a door to allow developers messing up the security of many resources either intentionally or un-intentionally.
With Strings being immutable, JVM can be sure that the filename instance member of the corresponding File object would keep pointing to same unchanged filename String object. The filename instance member being a final in the File class can anyway not be modified to point to any other String object specifying any other file than the intended one (i.e., the one which was used to create the File object).
Feel free to contact me via email: firstname.lastname@example.org