Dear Mr. I need your help, to understand the following aspect of String in Java. I dont understand, Why when I write: String x, y; x="Mother"; y="Mother"; Java, create a same instance of the String Object. but, when I write x=new String("Mother"); y=new String("Mother"); Java create a diferent instance of the String Object. Thanks for your help Atentamente Carlos A Rodriguez C email@example.com firstname.lastname@example.org [ April 18, 2004: Message edited by: Ernest Friedman-Hill ]
Carlos, You should post these "basic" issues on the beginners forum so others can benefit from the discussion. It has to do with how Java handles literal strings. Literal strings are kept in what we call the "literal string pool". In such a way, you could evaluate x == y and it will be true (first case). In the second case, you are using the "new" keyword, which explicitly creates a new object on the heap. In that case you are actually creating three strings. One (the literal) is placed in the "literal string pool". The other two are created on the heap and just refer to the literal one. At that point, x == y will evaluate false, while x.equals(y) will of course equal true.