Author
Strings are immunable - What does this mean?
Thomas Markl
Ranch Hand
Joined: Mar 08, 2001
Posts: 192
posted Oct 14, 2002 14:03:00
0
class Test58 { static int i; public static void main(String args[]) { System.out.println("i "+i); String s1= "Hello"; System.out.println(s1.replace( 'e' , 'e' ) == " Hello ");//String immutability System.out.println(" Hello " . replace ( 'e' , 'e' ) == " Hello "); //Pooling of String } } C:\Java\EigeneJavaProgramme>java Test58 i 0 false true Why does it print out "false" and "true". Why is " Hello " . replace ( 'e' , 'e' ) == " Hello " true and the other replace with s1 false? Thomas
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
Is String s1= "Hello"; correct? Are you sure it's not String s1= " Hello " with two spaces at the front and back?
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted Oct 14, 2002 14:30:00
0
When the replace method does not change a String it returns the same String that the method was passed.
Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted Oct 14, 2002 17:04:00
0
By the way, the word is "immutable".
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
Main Entry: im�mu�ta�ble Function: adjective Etymology: Middle English, from Latin immutabilis, from in- + mutabilis mutable Date: 15th century http://www.m-w.com/cgi-bin/dictionary Synonyms: INFLEXIBLE, constant, fixed, immovable, inalterable, invariable, unalterable, unchangeable, unmodifiable, unmovable
JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
The reason I asked my question about the string "Hello" back up there is because you get a true comparison instead of a false one when you do the s1.replace( 'e' , 'e' ) == " Hello ". -Barry
subject: Strings are immunable - What does this mean?