aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strings aren't objects? 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 "Strings aren Watch "Strings aren New topic
Author

Strings aren't objects?

Bret Waldow
Ranch Hand

Joined: Aug 04, 2000
Posts: 59
This is from the JQuest exam, presented as question 1.
It must be late. I am not thinking straight or something.
I could have sworn that Strings were objects, just like arrays, and hence the reference is passed, providing a reference back to the original object, but this code seems to say otherwise:
Please, what am I missing here? Thanks for any help.
public class q1 {
public static void main( String arg[] ) {
String name[] = {"Killer", "Miller" };
String name0 = "Killer";
String name1 = "Miller";
swap( name0, name1 );
System.out.println( name0 + "," + name1 );
swap(name);
System.out.println( name[0] + "," + name[1]);
}

public static void swap( String name[] ) {
String temp;
temp = name[0];
name[0] = name[1];
name[1] = temp;
}

public static void swap( String name0, String name1 ) {
String temp;
temp = name0;
name0 = name1;
name1 = temp;
}
}
deekasha gunwant
Ranch Hand

Joined: May 06, 2000
Posts: 396
Hi Bret,
String are Objects only.and may be to your surprise but this program is behaving perfectly.
when u pass an Object (in ur case String) to a function then actually a copy of that reference is passed
to that function.
now this reference copy can change the value of the original object. but if u somehow change this reference to point to some other object inside your function. still the original reference in the caller function is pointing to the same object as it was pointing earlier.
this is what is happening in your example.
i know that i've not explined it properly. but there is a place which will explain ur doubt surely.
just go through this page. http://javaranch.com/campfire/StoryPassBy.html
regards
deekasha


Bret Waldow
Ranch Hand

Joined: Aug 04, 2000
Posts: 59
Thanks. Your reply actually says it well enough.
Let me try saying it back:
The name0, name1 in the scope of the swap() method are different reference holders than the ones in the main body (ok, I already knew that), although they hold the same values at first.
The values they hold are references to the actual strings.
Changing the value of these local reference holders to point to different strings doesn't affect the original reference holders in the main body.
If strings were objects that could be changed, these local reference holders could be used to change the actual strings, as they do point to them. (Of course, strings can't be changed.)
What do you think?
regards,
Bret
 
wood burning stoves
 
subject: Strings aren't objects?