Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

String manipulation - need help

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is the difference b/w these 2 programs...
1)
public class MyClass
{
public static void main (String args[])
{
String str1="Java";

System.out.println(str1 == "Ja"+"va");
}
}



This prints true where as...

2)
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 prints false... what is the difference..???
 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Jayashree,

If you want want to compare the values of two Strings, then you have to use "str1.equals(str2)", not "==".

"==" actually compares whether the two variables are pointing to the same object.

In your first example, the compiler picks up that "Ja" and "va" are constants, and that therefore "Ja" + "va" is also constant. It therefore replaces "Ja" + "va" with a reference to "Java" in a constant-string pool - which happily happens to be the same object used to initialise str1.

In the second example, you have two separate String objects. In this case, the compiler cannot make the same constant assumptions, so the evaluation is left until runtime. This means a temporary result object will be created, which cannot be at the same address as the constant "Java" string.

You probably wanted str3.equals(str1+str2).
 
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rob, I think this was a test of reference comparison this person found in some book and it was deliberately about using ==.
 
Climb the rope! CLIMB THE ROPE! You too tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic