Use Operator == for String Comparison

Hi,
I would like to know more about the impact of using operator == in String Comparison.
From the reference I get, it state this :
"Operator (==) compares two object addresses to see whether it refers to the same object."
I've tested it with 2 codes as below :
Code 1:
          String Pass1 = "cosmo";
          String Pass2 = "cosmo";          
if (Pass1==Pass2)
               System.out.println("1&2:same");
          else
               System.out.println("1&2:not same");
Output : 1&2:same
Code 2:
          String Pass3 = new String("cosmo");
          String Pass4 = new String("cosmo");
          if (Pass3==Pass4)
               System.out.println("3&4:same");
          else
               System.out.println("3&4:not same");
Output : 3&4:not same
Can anyone kindly explain why is the result so? If operator == compares the addresses, isn't it that the 1st code should also have the output :"1&2:not same".

Can anyone kindly explain why is the result so?It's an implementation artifact. Strings are pooled internally and because of that any String literal will be represented by exactly one object reference.
Knowledge of this shouldn't be utilized though. It's safer to follow the basic rule: Use == to compare object references and equals to compare object values, such as String literals.

Similar Messages

  • [svn:bz-trunk] 18053: BLZ-571: Use of wrong operator in string comparison in flex.messaging.VersionInfo. java

    Revision: 18053
    Revision: 18053
    Author:   [email protected]
    Date:     2010-10-07 03:27:37 -0700 (Thu, 07 Oct 2010)
    Log Message:
    BLZ-571: Use of wrong operator in string comparison in flex.messaging.VersionInfo.java
    Updated the code to use the right operator.
    Check-in Tests: PASS
    QA: Yes
    Ticket Links:
        http://bugs.adobe.com/jira/browse/BLZ-571
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/VersionInfo.java

  • Not equal to operator in KQL i.e. for string comparison is not working. Is there any other approach for this?

    In KQL my query is like this,
    refinablestring05<>9c460541-5979-44ec-b0ab-63d1823f922f
    but looks like operator <> not working. It is not throwing error at all and always shows result.
    Any one can help me out for this?

    use NOT operator so it would be "NOT refinablestring:something"
    kashif

  • 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.

  • Using StartsWith for String Comparision in Business rules

    hi,
    I need to compare whether a particular string starts with some pre-defined prefixes. These are bound to change from time to time and hence we wanted to use the business rule engine for this. We declared prefixes using "list of values" vocab and
    defined the set. Now, I hoped to use the String.StartsWith() method but couldn't understand if it can be used.
    As of now, we are creating a method and that will be called with 2 parameters. One the string and other is one of the list of values which we want the string to start with. Is there any better way to do this?
    Praveen Behara
    MCST : BizTalk Server 2006 R2, 2010

    Hi Murugesan,
    I need to match a particular series of numbers... say 12xxx,345xxx,567xxx. I am creating a
    Series as a list and the valid values would be 12, 345, 567. I intend to keep them as prefixes i.e. they are not regular expressions. So, they won't be 12.*, 345.*, 567.*. The idea is to keep the vocab close to requirement
    and away from implementation (typically, for a business user). Now, if I want this setup, how will the implementation with
    Match look like?
    Technically, your above solution would work.. but my way of implementation / thought process is for a different purpose.
    Praveen Behara
    MCST : BizTalk Server 2006 R2, 2010

  • Fuzzy Logic for string comparison

    Hi All
    Thanks for taking the time to read the thread.
    I was wondering if any of you has come accross an algorithim to compare two different strings (or find patterns or degree of similarity) between these strings - Fuzzy type logic
    The reason I ask is because some of our duplicate invoices are created because the poster miss-enters the reference number - e.g. 1234A and 1234B. We would like to report invoices based on the similarity of the reference number.
    I have heard of the Fisher Wagner algorithm that calculates the cost of the differences (based on whether a character is added / omitted or changed) and the Perl algorithm - which finds patterns based on the degree of similarity; but not sure how they are implemented in ABAP or where I can find the open source code
    Your help is very appreciated.
    Thanks,
    Mamdouh

    There are a few function modules provided by SAP which seem to be for fuzzy searches.  ( Look at SE37 ).  For classes, again, there are a few: look in table SEOCOMPO with CMPNAME = *FUZZY* to find the classes and methods.
    These may give you what you need.

  • Using concat for STrings

    I'm trying to concat a specified string, ".jpg", to a string of the form:
    filestring = afile.getName();
    filestring.concat(".jpg");
    Why does it not add the .jpg to the end of what filestring is?

    Cuz Strings are immutable dingbat. If you'd read the api you might notice concat returns a new string with the value you want, but you're chucking it since you didn't assign the result to a variable.
    Options:
    1) filestring = afile.getName() + ".jpg"
    2) filestring = afile.getName().concat(".jpg");
    3) filestring = afile.getName(); filestring = filestring.concat(".jpg");
    3) use StringBuffer instead

  • Using CharAt for String Manipulation

    Hi,
    I am new to Java and am taking a Java class. I am trying to put a social security number in "nnn-nn-nnnn" format where n is a digit 0-9. I don't know if it would work with the charAt method of the String class. Does anyone have any suggestions on how to implement this kind of manipulation.
    It would be greatly appreciated!
    Thanks,
    waggypup99

    You could just create a class for social security number.
    e.g.
    public class SSNum{
        private int _num;
        public SSNum(int number){
          _num = number;
          * take number in the form  nnn-nn-nnnn
        public SSNum(String number){
          StringTokenizer st = new StringTokenizer(number,"-");
          StringBuffer numStringB = new StringBuffer(st.nextToken());
          numStringB.append(st.nextToken());
          numStringB.append(st.nectToken());
         _num = Integer.parseInt(numStringB.toString());
       public String toString(){
          //left as fun exercise
    }

  • Why not use "new" operator  with strings

    why we not use new when declaring a String .because in java String are treated as objects. we use new operator for creating an object in java .
    and same problem wiht array when we declare array as well as initialize .here we are alse not using new for array
    why

    Strings aren't just treated as objects, Strings are Objects.
    As for why not using new for Strings, you can, if you want.:
    String str = "this is a string";
    and
    String str = new String("this is a string");
    do the same thing (nitty-gritty low level details about literals aside). Use whatever you like, but isn't it simpler not to type new String(...) since you still need to type the actual string?
    As for arrays, you can use new:
    int[] ints = new int[10];
    or
    int[] ints = { 0, 1, 2, 3, ..., 9 };
    But the difference here is you are creating an empty array in the first one, the second creates and fills the array with the specified values. But which to you often depends on what you are doing.

  • Problems with string comparison using

    I have a problem using the > and < comparison operators.
    When the xsl:if test uses numeric values the comparison works OK. If the
    test uses string values it always returns a false result.
    The style sheet below shows an example (which should run against any
    XML doc with a root element)
    Note - the spurious
    tags are just for debugging- I write the
    output to an HTML page and IE happens to recognise them
    even though the rest of the HTML tags are missing !!
    <?xml version="1.0" ?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:template match="/">
    <xsl:for-each select="*">
    Starting numeric test :
    <xsl:if test="(1 < 2)">
    In Test, ID= <xsl:value-of select="generate-id()"/>
    </xsl:if>
    Finished numeric test :
    Starting alpha test :
    <xsl:if test="('a' < 'b')">
    In Test, ID= <xsl:value-of select="generate-id()"/>
    </xsl:if>
    Finished alpha test :
    </xsl:for-each>
    </xsl:template>
    </xsl:stylesheet>
    null

    Having looked at the XPath spec I believe what I am trying to do (compare strings with gt and lt type tests) is not supported. The spec indicates that they can only be used for node sets or numerics. Presumably the processor is attempting to convert the values to numbers but evaluating them both as NaN (not a number). Can someone confirm this.
    I find this restriction quite strange, is this a situation where an extension function is required ? If so can someone point me to some (Java) examples.
    null

  • Using bytes or chars for String phonetic algorithm?

    Hi all. I'm working on a phonetic algorithm, much like Soundex.
    Basically the program receives a String, read it either char by char or by chunks of chars, and returns its phonetic version.
    The question is which method is better work on this, treating each String "letter" as a char or as a byte?
    For example, let's assume one of the rules is to remove every repeated character (e.g., "jagged" becomes "jaged"). Currently this is done as follows:
    public final String removeRepeated(String s){
                    char[] schar=s.toCharArray();
              StringBuffer sb =new StringBuffer();
              int lastIndex=s.length()-1;
              for(int i=0;i<lastIndex;i++){
                   if(schar!=schar[i+1]){
                        sb.append(schar[++i]);//due to increment it wont work for 3+ repetions e.g. jaggged -> jagged
              sb.append(schar[lastIndex]);
              return sb.toString();
    Would there be any improvement in this computation:public final String removeRepeated(String s){
              byte[] sbyte=s.getBytes();
              int lastIndex=s.length()-1;
              for(int i=0;i<lastIndex;i++){
                   if(sbyte[i]==sbyte[i+1]){
                        sbyte[++i]=32; //the " " String
              return new String(sbyte).replace(" ","");
    Well, in case there isn't much improvement from the short(16-bit) to the byte (8-bit) computation, I would very much appreciate if anyone could explain to me how a 32-bit/64-bit processor handles such kind of data so that it makes no difference to work with either short/byte in this case.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    You may already know that getBytes() converts the string to a byte array according to the system default encoding, so the result can be different depending on which platform you're running the code on. If the encoding happens to be UTF-8, a single character can be converted to a sequence of up to four bytes. You can specify a single-byte encoding like ISO-8859-1 using the getBytes(String) method, but then you're limited to using characters that can be handled by that encoding. As long as the text contains only ASCII characters you can get away with treating bytes and characters as interchangeable, but it could turn around and bite you later.
    Your purpose in using bytes is to make the program more efficient, but I don't think it's worth the effort. First, you'll be constantly converting between {color:#000080}byte{color}s and {color:#000080}char{color}s, which will wipe out much of your efficiency gain. Second, when you do comparisons and arithmetic on {color:#000080}byte{color}s, they tend to get promoted to {color:#000080}int{color}s, so you'll be constantly casting them back to {color:#000080}byte{color}s, but you have to watch for values changing as the JVM tries to preserve their signs.
    In short, converting the text to bytes is not going to do anywhere near enough good to justify the extra work it entails. I recommend you leave the text in the form of {color:#000080}char{color}s and concentrate on minimizing the number of passes you make over it.

  • Error in SQL Query The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query

    hi Experts,
    while running SQL Query i am getting an error as
    The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator. for the query
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    T2.LineText
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,T2.LineText
    how to resolve the issue

    Dear Meghanath,
    Please use the following query, Hope your purpose will serve.
    select  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price ,
    CAST(T2.LineText as nvarchar (MAX))[LineText]
    from OQUT T0  INNER JOIN QUT1 T1 ON T0.DocEntry = T1.DocEntry LEFT OUTER JOIN
    QUT10 T2 ON T1.DocEntry = T2.DocEntry --where T1.DocEntry='590'
    group by  T1. Dscription,T1.docEntry,T1.Quantity,T1.Price
    ,CAST(T2.LineText as nvarchar (MAX))
    Regards,
    Amit

  • I just installed the Lion operating system, basically to upgrade my iPhone. I didn't realize that my Microsoft Office 2004 application would no longer work. I have been using Word for my writing and I receive most of my emails with Word attachments. I hav

    I just installed the Lion operating system, basically to upgrade my iPhone. I didn't realize that my Microsoft Office 2004 application would no longer work. I have been using Word for my writing and I receive most of my emails with Word attachments. I have been using Apple products for years, always touting their reliability and customer service. I am not a techie, I just want to be able to do what I do on the computer and Apple always fulfilled my needs. Now I am told because of some operating system gobbledygook, I have to go out and purchase new software to use Word. This is despicable. I see no particular benefit to using Lion, but I do see a lot of detriments. Apple now seems to have turned into Microsoft, making software obsolete so they can make more money and to **** with the customer. You can be sure that my next computer will be a PC. I have completely lost confidence in Apple.

    I seem to never tire of saying this. It was for Apple when they first announced 10.7 to disclose this. Yes, it was widely reported -- or rather, rumored -- but not by Apple. And many people who have gotten caught by this assumed that Apple itself would have told them beforehand about the loss of this very important feature which they had come to rely on. As far as I know, not even in fine print, does this appear anywhere on the Lion announcement or any of its links.
    I am not saying Apple had to continue Rosetta in Lion, or forever, just that if it was going to be dropped, it should have been made known.
    As relative "insiders" we should not forget that many people don't have the time, habit or interest to do this kind of research. I think it is a breach of trust that Apple has never directly made this announcement or given people the opportunity to decide beforehand if giving up their PPC apps for a new OS is a worthwhile tradeoff.

  • How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?

    Hi All,
    Hope to you a very happy new year,
    I have two differnt LAP 1300 and 1200 in my network and I need to add theme to the WLC,
    I successed to add one of theme by the option 60 in the DHCP pool at the Core SW,
    So my quetion is below:
    How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?
    Thanks in Advanced,
    Ahmed,

    To add to Scott's post.  Option 60 would be useful if you needed to put certain types of AP on specific controllers.  Otherwise, no real need to use it for the most part.
    Though, I do recall an issue a few years ago that some windows machines had issues getting DHCP if option 43 is being returned.
    Now, on an IOS switch, you can only configure one option 60 per DHCP scope
    HTH,
    Steve
    Please remember to rate useful posts, and mark questions as answered

  • Wat should be the regular expression for string MT940_UB_*.txt to be used in SFTP sender channel in PI 7.31 ??

    Hi All,
    What should be the regular expression for string MT940_UB_*.txt and MT940_MB_*.txt to be used as filename inSFTP sender channel in PI 7.31 ??
    If any one has any idea on this please let me know.
    Thanks
    Neha

    Hi All,
    None of the file names suggested is working.
    I have tried using - MT940_MB_*\.txt , MT940_MB_*.*txt , MT940*.txt
    None of them is able to pick this filename - MT940_MB_20142204060823_1.txt
    Currently I am using generic regular expression which picks all .txt files. - ([^\s]+(\.(txt))$)
    Let me know ur suggestion on this.
    Thanks
    Neha Verma

Maybe you are looking for