• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

confused with String Equality

 
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got these from

http://www.angelfire.com/or/abhilash/quiz/quiz4.html

1. Read this piece of code carefully

if("String".replace('g','G') == "String".replace('g','G'))
System.out.println("Equal");
else
System.out.println("Not Equal");

Answers

the code will compile an print "Equal".
the code will compile an print "Not Equal".
the code will cause a compiler error
Ans b


2. Read this piece of code carefully

if("String".replace('T','t') == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

Answers

the code will compile an print "Equal".
the code will compile an print "Not Equal".
the code will cause a compiler error
Ans a

3. Read this piece of code carefully

if("String".replace('t','t') == "String")
System.out.println("Equal");
else
System.out.println("Not Equal");

Answers

the code will compile an print "Equal".
the code will compile an print "Not Equal".
the code will cause a compiler error
Ans a

When it gives equal and when not? very much confused with this. Kindly help me.

Thanks
Geeta Vemula
 
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The replace method returns a new string object IF AND ONLY IF there is any change in the actually string.

Look at the replace method implementation.

[ December 31, 2008: Message edited by: James Tharakan ]
 
Ranch Hand
Posts: 54
Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Geetha according to what James had posted I feel that in 2nd and 3rd code blocks there is no change in the String
2nd -because T is not present in String at all,
3rd- since old and new variable are equal.

But any comparison of String's with == is not encouraged instead if you use string1.equals(string2) it will give true results.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic