• 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

Strings

 
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1)
public class MyClass
{
public static void main (String args[])
{
String str1= "Ja";
String str2= "va";
String str3= "Java";
System.out.println(str3 == str1 + str2);
}
}
This code when compiled and run gives the output false. I don't understand why it is giving false when it should give true.
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Maybe it is because when you add two strings then a newly created object of String is returned.
Try out this one:
class Test{
public static void main(String[] args) {
String s1 = " AB ";
String s2 = "AB";
String s3 = s1.trim();
String s4 = s2.trim();
if (s2 == s3)
System.out.println ("true");
else
System.out.println ("false");
if (s2 == s4)
System.out.println ("true");
else
System.out.println ("false");
}
}
 
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Shabbir,
The result is false because:
"Strings computed at run time are newly created and therefore distinct. " - Java Language Spec 3.10.5
So if you wrote:
String str = str1 + str2;
System.out.println(str == str3);
produces:
true
Since str references from the string pool - it either finds a reference to "Java" or adds it to the pool.
hope that helps,
Yoo-Jin.
 
I think I'll just lie down here for a second. And ponder this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic