String compare question.

Hi all,
I have this code here, and don't understand the result came out. Can someone explain this out come ? Thanks.
String s1 = "Hi";
String s2 = "Hi";
if (s1 ==s2) System.out.println("s1=s2");
String s3 = new String ("Hi");
String s4 = new String ("Hi");
if (s3 ==s4) System.out.println("s3=s4");
Result: It only prints "s1=s2". Why is that ?
Thanks.
Pwing

Hi all,
I have this code here, and don't understand the result
came out. Can someone explain this out come ?
Thanks.
String s1 = "Hi";s1 is created and put in to the string constant pool. When ever a String literal is encountered, the JVM will first check the string constant pool to see if it already contains a String object with the exactly same data(character sequence). If a match is found, a reference to the existing string is returned, and no new object is created.
String s2 = "Hi";string constant pool is checked and a string literal with the character sequence "Hi" already exists.
So, s1 and s2 are both references to the same object.
if (s1 ==s2) System.out.println("s1=s2");when comparing objects the == operation only tests to see if both references point to the same object. This is true since both s1 and s2 point to the same object in the string constant pool.
String s3 = new String ("Hi");
String s4 = new String ("Hi");A string created with the new operartor is not a string literal. The new operator always generates a unique object and returns a reference to that object.
if (s3 ==s4) System.out.println("s3=s4");
if you wish to compare the contents of a object use the .equals method.
Result: It only prints "s1=s2". Why is that ?
Thanks.
Pwing

Similar Messages

  • [svn] 1751: Bug: BLZ-174 - MessageClient.testMessage() is incorrectly doing a string compare for the subtopic header of an inbound message against the subtopic value (which may contain wildcards) that the Consumer is using.

    Revision: 1751
    Author: [email protected]
    Date: 2008-05-15 14:21:43 -0700 (Thu, 15 May 2008)
    Log Message:
    Bug: BLZ-174 - MessageClient.testMessage() is incorrectly doing a string compare for the subtopic header of an inbound message against the subtopic value (which may contain wildcards) that the Consumer is using.
    QA: No - customer verified the fix.
    Doc: No
    Ticket Links:
    http://bugs.adobe.com/jira/browse/BLZ-174
    Modified Paths:
    blazeds/branches/3.0.x/modules/core/src/java/flex/messaging/MessageClient.java
    blazeds/branches/3.0.x/modules/core/src/java/flex/messaging/services/MessageService.java

    If you create a metadatatype with a single metdata block, and you reference that in your vm/cm cell attribute using a *one* based index, Excel seems to see the link and it honors it when saving the spreadsheet.
    So, I ended up with something like:
    <c ... cm="1"/> (I'm dealing with cell metadata, but the concept is equivalente to value metadata)
    <metadataTypes count="1">
      <metadataType name="MyMetaType" .../>
    </metadataTypes>
    <futureMetadata count="1" name="MyMetaType">
      <bk>
        <extLst><ext
    uri="http://example" xmlns:x="http://example"><x:val>87</x:val></ext></extLst>
      </bk>
    </futureMetadata>
    <cellMetadata count="1">
      <bk><rc
    t="1" v="0"/></bk> <!-- this is what gets referenced as cm=1 on the cell -->
    </cellMetadata>
    Hope this helps. 

  • Any bright ideas? (string parsing question)

    Hi,
    I need to put together some static methods for parsing and comparing strings in different formats. I've written the skeleton methods with some nice comments below:
    public class ParsingTools {
        * This method should be able to convert a string that contains
        * a date in an arbitrary format, to a java.util.date.
        * E.G. '10.12.1998 4:15 AM', 'Jan 6th 1984', '1/01/00'
        * '24th Feb 1975 0530hrs'.  The boolean 'usa' parameter indicates
        * whether its usa style dates: mm/dd/yyyy, instead of dd/mm/yyyy.
        * @param inputDate
        * @param usa
        * @return
       public static Date parseStringDate(String inputDate, boolean usa){
          Date outputDate = null;
          return outputDate;
        * This method should be able to convert strings like:
        * "$10,000.45" to the double 10000.45, or even:
        * "'x=$$254,433,344.003'" to 254433344.00.  All kinds of
        * extraneous characters could be received, this method extracts
        * and returns the number part.
        * @param inputString
        * @return
       public static double parseMoneyString(String inputString){
          double outputDouble = 0.0;
          return outputDouble;
        * This method takes two strings, the first of which is compared
        * to the second to see if they are a close enough match.
        * E.G. " exerci$ed_" compared with "EXERCISED" should return
        * true, but "elephant" compared with "EXERCISED" should return
        * false.
        * @param inputString
        * @param compareString
        * @return
       public static boolean matchToString(String inputString,
                                           String compareString){
          boolean matches = false;
          return matches;
    }Ok, the getting the double from the money string one is easy, just search through the string until you find some numbers, and strip out any commas.
    If anyone has any ideas on a clever way of doing the date parsing, and the string compare one, or knows of existing methods to do these, I'd love to hear about it.
    Many long hours of messing around with string operations await me otherwise!
    Thanks

    I need to put together some static methods for
    parsing and comparing strings in different formats.
    I've written the skeleton methods with some nice
    e comments below:Why isn't java.text.DateFormat good enough for you? I'll bet they do it better.
    I'd use Locale for currencies.
    This is a case where stuff that's already available to you should be preferred. Why write your own when someone else has already done it better? You don't have to maintain it, either. JMO, of course.
    >
    public class ParsingTools {
    * This method should be able to convert a string
    ring that contains
    * a date in an arbitrary format, to a
    to a java.util.date.
    * E.G. '10.12.1998 4:15 AM', 'Jan 6th 1984',
    84', '1/01/00'
    * '24th Feb 1975 0530hrs'.  The boolean 'usa'
    usa' parameter indicates
    * whether its usa style dates: mm/dd/yyyy,
    yyy, instead of dd/mm/yyyy.
    * @param inputDate
    * @param usa
    * @return
    public static Date parseStringDate(String
    ing inputDate, boolean usa){
    Date outputDate = null;
    return outputDate;
    * This method should be able to convert strings
    ings like:
    * "$10,000.45" to the double 10000.45, or even:
    * "'x=$$254,433,344.003'" to 254433344.00.  All
    All kinds of
    * extraneous characters could be received, this
    this method extracts
    * and returns the number part.
    * @param inputString
    * @return
    public static double parseMoneyString(String
    ing inputString){
    double outputDouble = 0.0;
    return outputDouble;
    * This method takes two strings, the first of
    t of which is compared
    * to the second to see if they are a close enough
    ough match.
    * E.G. " exerci$ed_" compared with "EXERCISED"
    SED" should return
    * true, but "elephant" compared with "EXERCISED"
    SED" should return
    * false.
    * @param inputString
    * @param compareString
    * @return
    public static boolean matchToString(String
    ing inputString,
    String
    String
    String compareString){
    boolean matches = false;
    return matches;
    }Ok, the getting the double from the money string one
    is easy, just search through the string until you
    find some numbers, and strip out any commas.
    If anyone has any ideas on a clever way of doing the
    date parsing, and the string compare one, or knows of
    existing methods to do these, I'd love to hear about
    it.
    Many long hours of messing around with string
    operations await me otherwise!
    Thanks

  • Using wildcards for String compare

    Hello,
    I want my prog to find out all Strings which start with the letters 'File'. How can I make a String compare by using wildcards ?
    Thanx,
    Findus

    You may use the String method startsWith to find strings beginning with File. eg. filename.startsWith("File")
    for more complicated comparisons you might want to use regular expressions.

  • String Compare

    Hi,
    I want to compare two strings,
    String1 i read from a text file and string two can be a constant.
    After comparing, if string from text file is matching to constant, need to do some processes.
    Anybody please comment on this.
    -mfp.
    Solved!
    Go to Solution.

    Your question is extremely basic. PLEASE read the LabVIEW Help and do the tutorials. It's not a waste of time.
    To learn more about LabVIEW it is recommended that you go through the tutorial(s) and look over the material in the NI Developer Zone's Learning Center which provides links to other materials and other tutorials. You can also take the online courses for free.
    Attachments:
    Example_VI_BD.png ‏2 KB

  • Why string compare is false?

    Hello,
    I've been confused for a while, could you mind helping?
    This small code compare two strings, not know why but always false.
    ==
    String date_zero = "0000-00-00";
    out.println("cs is "+date_claim_set); // print "cs is 0000-00-00" on screen
    out.println("result is "+date_claim_set.equals(date_zero)); // print "result is false" on screen
    if ( ! date_claim_set.equals(date_zero) ) {
    out.println("strings not equal"); // printed
    ==
    why the two strings are not equal?
    Hope you can help, thanks in advance.
    Rgds, Dove

    masijade. wrote:
    Well, most of his questions lately, have been about MySQL, and "0000-00-00" is the way that MySQL (per default) represents invalid dates, and "YYYY-MM-DD" is the toString() pattern for a java.sql.Date instance. ;-)Sorry for keeping your guys waiting, but I've spent sometimes for reading more material as I can. Now the problem fixed.
    The solution is liked this.
    1) MySQL document said '0000-00-00' is a valid value for date in DB, but a wrong value for JDBC.
    Detail:
    http://dev.mysql.com/doc/refman/5.0/en/connector-j-installing-upgrading.html#connector-j-installing-upgrading-3-0-to-3-1
    2) It is recognized as a problem, so it has been fixed. Instead of using old JDBC Connector/J, new version with re-configuration of zeroDateTimeBehavior can solve.
    I configure it to convertToNull, so in Java I see all value 0000-00-00 from DB as null, works fine.
    Many thanks the ideas from all of you.
    Rgds, Dove

  • String a== string b question

    Hi,
    I was told that when compare objects using ==, the reference of the objects are being compared not the data. My question is for the following two strings, why is it (s1==s2) result true. They are two different objects and should have different reference. Therefore, the result should be false. Can anyone advise. Thanks.
    String s1 = "abc";
    String s2 = "abc";

    Actually, the String Object has its own implementation of method equals(), which is different of the default one provided by the Object class.
    The String's equals method returns true if the to args has the same characters.
    That is, if you have
    String one = "abc" ;
    String two = "abc" ;
    String three = one ;
    String four = one + "d" ;
    one.equals(three) will return true,
    one.equals(two) will return true,
    one.equals(four) will return false...

  • Problems with string comparing

    I have a function, getPlayerName() that returns the contents of a text field, but i want the dialog box to check and see if there was anything typed in there, so i have done things like if(this.getPlayerName() != null), if(this.getPlayerName() != "") and if(this.getPlayerName() != " "), and the statement still lets it go by when i dont type anything in. is there something else i'm suppose to do?

    When comparing strings (and any other object for that matter) you must use the equals method. In your case you should probably also trim the string for whitespace before comparing:
    if(!this.getPlayerName().trim().equals("")) In this case you can also use the length method:
    if(this.getPlayerName().trim().length() != 0)

  • Very simple XSLT string replacing question

    Hi,
    This is a really simple question for you guys, but it took me long, and i still couldn't solve it.
    I just want to remove all spaces from a node inside an XML file.
    XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <root insertedtime="2008-05-01T14:03:00.000+10:00" pkid="23421">
       <books>
          <book type='fiction'>
             <author>John Smith</author>
             <title>Book title</title>
             <year>2 0  0 8</year>
          </book>
       </books>
    </root>in the 'year' node, the value should not contain any spaces, that's the reason why i need to remove spaces using XSLT. Apart from removing space, i also need to make sure that the 'year' node has a non-empty value. Here's the XSLT:
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:strip-space elements="*"/>
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="//books/book[@type='fiction']">
            <xsl:copy>
                <xsl:apply-templates select="@*"/>
                <xsl:attribute name="id">101</xsl:attribute>
                <xsl:call-template name="emptyCheck">
                    <xsl:with-param name="val" select="year"/>
                    <xsl:with-param name="type" select="@type"/>
                    <xsl:with-param name="copy" select="'true'"/>
                </xsl:call-template>
                <xsl:value-of select="translate(year, ' ', '')"/>
            </xsl:copy>
        </xsl:template>
        <!-- emptyCheck checks if a string is an empty string -->
        <xsl:template name="emptyCheck">
            <xsl:param name="val"/>
            <xsl:param name="type"/>
            <xsl:param name="copy"/>
            <xsl:if test="boolean($copy)">
                <xsl:apply-templates select="node()"/>
            </xsl:if>
            <xsl:if test="string-length($val) = 0 ">
                <exception description="Type {$type} value cannot be empty"/>
            </xsl:if>
        </xsl:template>
    </xsl:stylesheet>The 'emptyCheck' function works fine, but the space replacing is not working, this is the result after the transform:
    <?xml version="1.0" encoding="utf-8"?>
    <root insertedtime="2008-05-01T14:03:00.000+10:00" pkid="23421">
       <books>
          <book type="fiction" id="101">
             <author>John Smith</author>
             <title>Book title</title>
             <year>2 0 0 8</year>2008</book>
       </books>
    </root>The spaced year value is still there, the no-space year is added outside the 'year' tags'
    anyone can help me, your help is extremely appreciated!
    Thanks!

    You should add a template for 'year' :<xsl:template match="year">
    <year><xsl:value-of select="translate(.,' ','')"/></year>
    </xsl:template>and remove the translate call in the 'book' template.
    It would be better to add a 'priority' attribute at each template so it would be explicit which template to use because match="@*|node()" could be interpreted by another transform engine as the unique template to be used !

  • String comparator

    Hey guys,
    I am having a problem comparing 2 strings in an if statement.
    I have an NSString called picked and a string literal that I want to compare in the if statement. I want to see if those two strings are visually the same (meaning they both say "something" and that I am not trying to compare their addresses or anything.
    I have the following: if(self.picked == @"something") {...
    Of course I realize that "==" is probably comparing their memory addresses. However, when I try to use isEqualToString method, I either am using it wrong, or that method does not apply to this situation because I get errors/warnings.
    Thanks in advance for the help.

    I have the following: if(self.picked == @"something") {...
    I think this is in NSString
    if ([self.picked isEqualToString:@"something"]) {
    NSLog(@"Equal strings");
    Also I believe NSString subclasses NSObjects isEqual method so that it does the same thing so you could use
    if ([self.picked isEqualTo:@"something"]) {
    NSLog(@"Equal strings");

  • How do I view previous strings of questions and answers on FF support?

    I read this response but it really doesn't answer the question.
    "If you are logged on then you see a My Contributions item in the Filter bar at the top that goes to:
    https://support.mozilla.org/questions?filter=my-contributions"
    I don't see the "filter bar" or "my responses" after I log in. I just see "Ask a question" "my log in name" and some other stuff to the right of that and below that.
    So after I log in, how do I look at strings of my previous questions and all responses to them, including new ones?

    I just figured it out!!! Wha-lah. Go to a question and then click on the underlined text in the question. Then a string of the Q and subsequent responses appears.

  • Classes and subclasses given as String input - question

    Hello, I am new in Java so please don't laugh at my question!!
    I have a method as the following and I am trying to store objects of the type Turtle in a vector. However the objects can also be of Turtle subclasses: ContinuousTurtle, WrappingTurtle and ReflectingTurtle. The exact class is determined by the String cls which is input by the user.
    My question is, how can I use cls in a form that I don't have to use if-else statements for all 4 cases? (Imagine if I had 30 subclasses).
    I have tried these two and similar methods so far but they return an error and Eclipse is not of much help in this case.
    Simplified methods:
    //pre:  cls matches exactly the name of a valid Turtle class/subclass
    //post: returns vector with a new turtle of type cls added to the end
    private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
         Turtle t = new cls(...);
         storage.add(t);
         etc.
    private Vector<Turtle> newturtle(Vector<Turtle> storage, String cls){
         Turtle t = new Turtle<cls>(...);
         storage.add(t);
         etc.
    }Thanks for your help.
    p.s.: I didn't know whether to post this question here or under Generics.

    a Factory is atually very simple (100x simpler than reflection).
    example:
    class TurtleFactory
      public Turtle makeTurtle(String typeOfTurtle)
        if (typeOfTurtle.equals("lazy") { return new LazyTurtle(); }
        else if (typeOfTurtle.equals("fast") { return new FastTurtle(); }
        <etc>
    }While at first this doesn't look any better than your original problem, what we've done is made a class that is responsible for all the types of turtles. This will also benefit in case some turtles need initialization or need something passed to their constructor. You encapsulate all that knowledge in one place so you rcode doesn't become littered with it else ladders.

  • String compare problem

    I try to compare 2 strings with compareTo/equalTo, but it's not working, those 2 funcs always return ture.
    public boolean chMark(String name, String test, String newMark)
              boolean flag = false;
              for(int i = 0; i < course.getNumOfStd(); i++)
                   if(course.getStd().getName().compareTo(name)==0)//here is problem;
                        Student tempStd = course.getStd()[i];
                        for(int j = 0; j < tempStd.getMark().getNumOfTests(); j++)
                        if(tempStd.getMark().getTestArray()[j].getTitle().compareTo(test)==0);//here is problem;
                             int mark = Integer.parseInt(newMark);                    }
              return flag;
    Can anybody tell me why?
    REGARDS,
    Elton

    equals() would read more naturally than compareTo()==0. But, in
    either case, use System.out.println() to write the two strings before
    you compare them. This is to check that you are comparing what
    you think you're comparing.System.out.println("name from course is " + course.getStd().getName());
    System.out.println("name is " + name);
    if(course.getStd()[i].getName().compareTo(name)==0)//here is problem;
    System.out.println("name from couse and name compared equal");
    // etc

  • String compare using S .equals() and ==

    When comparing strings, what is the different between using stringx.equals(stringy) and stringx == stringy?
    And what is the different between threads that are created by implement Thread or extends Runnable.
    They both work fine in my application

    When comparing strings, what is the different between
    using stringx.equals(stringy) and stringx ==
    stringy?
    And what is the different between threads that are
    created by implement Thread or extends Runnable.
    They both work fine in my applicationactually the equals method has been overridden to String class so that it gives you true when ever two String object contains the same String value whether the == gives you true only when two objects are same. here I guess two objects are same so you are getting true in both cases.
    for the second answer it is generally depending upon your requirement to adopt one of the ways. Sometimes you are forced to implement runnable because you may have already Extends another class. Personally I felt its more often that we implements Runnable than extending the Thread class
    Message was edited by:
    tanmoy_rajguru
    Message was edited by:
    tanmoy_rajguru

  • Ordering certain keys in TreeMap / comparator question

    I have a TreeMap of currencies. Keys are ("USD", "EUR"...) and each value holds some collection.
    I want to sort the TreeMap so that "GBP", "USD", "CAD" and "EUR" are the first 4 keys in the map and other currencies are in their natural order following these 4 keys. I don't know which currency I'll be getting from a certain operation so it could be that "USD" is encountered last which means it will be the last key in my TreeMap.
    How would I do this using the Comparator and compareTo method?
    Any help would be greatly appreciated.
    Cheers
    Norm.

    Your Comparator's compare() method could have to have a lot of hard-coding in it. Like this:public int compare(Object a, Object b) {
      Thing at = (Thing) a;
      Thing bt = (Thing) b;
      String acurr = a.getCurrency();
      String bcurr = b.getCurrency();
      if (acurr.equals(bcurr)) return 0; // return 0 for equals
      if (acurr.equals("GBP")) return -1; // GBP before everything
      if (bcurr.equals("GBP")) return 1; // GBP before everything
      if (acurr.equals("USD")) return -1; // USD before the rest
      if (bcurr.equals("USD")) return 1; // USD before the rest
      // and so on
    }

Maybe you are looking for

  • Help, itunes wont open and saying it is corrupt

    HELP! I just went to open my itunes and it is coming up with error message saying it is corrupt. It is asking me to reinstall it. If I reinstall it, will I loose all of my music? Please be aware I am useless with computers especially our mac that we

  • Syntax for Update Query?

    Hi I have the following query: update martin_adhoc_pct set adhoc.mbr_oed = mbr.orig_eff_date where adhoc.subs_ssn = mbr.subs_ssn and adhoc.mbr_type = mbr.mbr_type I get an error saying that: ORA-000904 "mbr"."mbr_type" invalid identifier.. I am using

  • SURLError 1005? What's That All About?

    Howdy folks, fairly new mac user here. Everything's been just dandy for the last month but tonight Safari took a few attempts to get going: giving me this error code of 1005. After I finally got it running it seems slower than normal and I'm having a

  • My macbook pro works on any wifi except my house wifi

    Hi, i have been trying every thing so i can connect my mac book air to my house wifi but it doesnt work at allll !!! and the weird thing is that it gets connected with any other wifi but not my houses ,,,,, please any body can help

  • How to specify MIME type handlers in Safari?

    In the old days, it was possible to specify the MIME type handler in web browsers like Netscape, etc. I can't seem to find this functionality in Safari. Is it possible to do this? Specific intended use case: I use a website that includes document att