File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes File doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "File doubt" Watch "File doubt" New topic

File doubt

sun par
Ranch Hand

Joined: Oct 03, 2002
Posts: 257
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change
This is what the API says...
But when I run a program with lines like these
File f3=f.createTempFile("suni",null);
f3=f.createTempFile("suni",null,new File("."));
it does not complain... Can anyone please explain then what immutable means?

Sunita<br />SCJP 1.4
Kem Bro

Joined: Oct 17, 2001
Posts: 25
Hi Sunita,
It's probably easier to explain the concept of how some objects are immutable by using this simple example.
If I create a string like this:
String s = "Hello";
I can *never* change this String. If I do something
s = s.concat("World");
A new string is created and assigned to the reference s, the original String is not changed.
AFAIK other objects that are immutable are the wrapper classes for primitive objects.
sun par
Ranch Hand

Joined: Oct 03, 2002
Posts: 257
Hai Kem,
Thanks.. But we create file objects using one of the constructors... So we will always be able to assign something else to it.. So what is the significance of the instances of the file class being immutable?
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Let's look at this another way:
File f3=File.createTempFile("suni",null);
File f4=File.createTempFile("suni",null,new File("."));
Clearly we have created 2 separate File objects. In your example you have also created two separate File objects but you only saved a pointer to one of them.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
sun par
Ranch Hand

Joined: Oct 03, 2002
Posts: 257
Thanks Thomas ... File class does not have methods to change the abstract path name like the String class.. so I guess that way it stays imuttable
I agree. Here's the link:
subject: File doubt
It's not a secret anymore!