1 2 Previous Next 15 Replies Latest reply: Jun 13, 2010 1:57 AM by YoungWinston RSS

    clarification on strings

    843789
      hi all

      I have two string

      String blank ="";
      String sometext = "test";

      when i use

      "".equals(blank) ---> returning true
      "" == blank ---> returning false

      this is working as expected but when i am using

      *"" != blank ---->returning false*
      *"" != sometext --->returning true -----> dono the reason why?*

      Cansome explain me the reason/behaviour of the text in bold

      Thanks
      diana
        • 1. Re: clarification on strings
          843789
          Use .equals to compare the contents of strings. == shows whether they're the same exact string object, which almost always isn't what you want.
          Diana12 wrote:
          "" != blank ---->returning false
          "" != sometext --->returning true -----> dono the reason why?
          Why are you surprised that "" and "test" are unequal?
          • 2. Re: clarification on strings
            3004
            Diana12 wrote:
            String blank ="";
            String sometext = "test";
            "".equals(blank) ---> returning true
            "" == blank ---> returning false
            I think you'd better look again.

            Run this, study it closely, and post again if you're still confused.
            public class Strings {
              public static void main(String[] args) throws Exception {
                String s1 = "";
                String s2 = new String ("");
                String s3 = "abc";
                String s4 = new String ("abc");
            
                System.out.println("\"\" == \"\": " + ("" == ""));
                System.out.println("\"\" == s1: " + ("" == s1));
                System.out.println("\"\" == s2: " + ("" == s2));
            
                System.out.println("");
            
                System.out.println("\"abc\" == \"abc\": " + ("abc" == "abc"));
                System.out.println("\"abc\" == s3: " + ("abc" == s3));
                System.out.println("\"abc\" == s4: " + ("abc" == s4));
            
                System.out.println("");
            
                System.out.println("\"\" != \"\": " + ("" != ""));
                System.out.println("\"\" != s1: " + ("" != s1));
                System.out.println("\"\" != s2: " + ("" != s2));
            
                System.out.println("");
            
                System.out.println("\"abc\" != \"abc\": " + ("abc" != "abc"));
                System.out.println("\"abc\" != s3: " + ("abc" != s3));
                System.out.println("\"abc\" != s4: " + ("abc" != s4));
            
              }
            }
            • 3. Re: clarification on strings
              843789
              Diana12 wrote:
              Cansome explain me the reason/behaviour of the text in bold
              In Java Strings are objects really but they have been given extra language support to behave almost like primitives. This can be confusing. The best approach in my view is to simply consider Strings as objects.

              Now that Java has gone to such great lengths to hide the object nature of String it may seem strange to largely ignore that and view them as objects but in my view it helps with the understanding.

              So view "" (and "test" or whatever String literal) as an object. If you do the following cases follow what you would expect for any object.

              Case 1 (reference comparision using ==):
              String s = ""; // s is assigned the "" object reference
              if (s=="") // the object reference held in s is compared with the "" object reference
              Case 2 (content comparision using equals):
              String s = ""; // s is assigned the "" object reference
              if (s.equals("")) // the content of the object referenced by s is compared with
                              // the content of the object referenced by the "" object reference (and that content is "")
              • 4. Re: clarification on strings
                843789
                hi

                if i use == object reference is compared
                if use .equals content in the objects are compared

                thn String blank = "";
                String sometext = "zyz";



                blank != "" --> object references will be different
                sometext != "" --> object references will be different

                both of them shd give me same results. why is this not happening

                please correct me if i am wrong
                Diana
                • 5. Re: clarification on strings
                  3004
                  Diana12 wrote:
                  hi

                  if i use == object reference is compared
                  Yes.
                  if use .equals content in the objects are compared
                  For Strings, yes, because String overrides the equals() method. For Object and any class that does not override equals(), it's the same as ==.
                  thn String blank = "";
                  String sometext = "zyz";



                  blank != "" --> object references will be different
                  Incorrect. If you had run the code I provided, as I suggested, you would see that == evaluates to true here. This is because of the constant pool.
                  sometext != "" --> object references will be different
                  Of course. Since the contents are different, the references must be different.
                  please correct me if i am wrong
                  Because String constants are shared via the constant pool.
                  class Foo () {
                    String s1 = "abc";
                    String s2 = "abc";
                    String s3 = new String("abc");
                    String s4 = s3.intern();
                  When this class is compiled, the String constant "abc" is stored in the class file. When the JVM loads the class, that String is loaded into the constant pool. Any reference to that string literal has the same value--refers to the same object in the constant pool. Every String literal expression "abc" evaluates to the same reference in the constant pool.

                  Thus, s1 == s2 is true, since both s1 and s2 refer to the single "abc" String object in the constant pool.

                  When we execute the s3 line, however, the literal "abc" on the RHS still evaluates to the same reference in the constant pool, but the new operator means we are creating a new object based on that one. So s1 == s3 will be false.

                  When we get to the fourth line we call s3.intern, which places the String in the constant pool if there's not already one there with the same contents (which there is in this case) and returns a reference to the one in the constant pool--either the one that was already there or the new one put there if it wasn't there previously. s4 == s1 will therefore be true, since there was already an "abc" in the constant pool.
                  • 6. Re: clarification on strings
                    843789
                    Ecellent.....!!!

                    Thanks a ton for the help.

                    is this the same with string object's and how does intern() react with objects

                    String strNull1 = new String("xyz");
                    String someText1 = new String("xyz");
                    System.out.println(someText == strNull1);
                    System.out.println(someText.equals(strNull1));

                    Thanks again,
                    Diana
                    • 7. Re: clarification on strings
                      3004
                      Diana12 wrote:
                      Ecellent.....!!!

                      Thanks a ton for the help.

                      is this the same with string object's and how does intern() react with objects
                      I don't understand your question. All Strings are objects.
                      String s1 = "abc";
                      String s2 = new String("xyz");
                      This code has two String literals in it, abc" and "xyz". Therefore, when the class is loaded, two String objects will be created in the constant pool, one for "abc" and one for "xyz".

                      When we hit the first line of code, the RHS evaluates to the reference to the "abc" in the constant pool, so that reference value is copied into s1. The reference variable s1 now holds a reference that points to the String object "abc" in the constant pool.

                      When we hit the second line, the new operator tells us to create a new String object. It's the constructor that takes a reference to an existing String object. In this case that reference evaluates to the refer to the String object "xyz" in the constant pool. A new String is created, and its contents are copied from the one in the constant pool. The new operator returns a reference to that String object, and that reference value is copied into s2. The reference variable s2 now holds a reference that points to a String object "xyz" that is not in the constant pool.

                      There are now 3 String objects--"abc" and "xyz" in the constant pool, and "xyz" in the normal part of the heap, not in the constant pool. They're all String objects, and they're all the same except for where in memory they live and which characters they hold.

                      There are 2 reference variables, s1 and s2, that hold references pointing to 2 of those String objects.

                      If we call "abc".intern(), "xyz".intern(), s1.intern(), or s2.intern(), nothing happens. Three of those references point to a String object already in the pool, and the last one, s2, points to an object that's not in the pool, but has the same contents as one in the pool, so nothing is done.
                      String s3 = s1 + s2;
                      String s4 = s3.intern();
                      This creates a brand new String, one whose contents are not already in the constant pool. The s4 line make a copy of that string, "abcxyz" in the pool, returns a reference to that new String object, and sticks that reference in s4. Note that the s3 variable and the non-pooled "abcxyz" String object it refers to are both unaffected by the s4 line.
                      • 8. Re: clarification on strings
                        YoungWinston
                        Diana12 wrote:
                        is this the same with string object's and how does intern() react with objects
                        The only thing I'd add to the excellent advice already given is that if you're planning on using intern() simply so that you can use '==' rather than equals() -- DON'T.

                        It's a false economy and basically bad programming practise. Strings are objects, so use the method provided for comparing them. Also, I suspect if you were to look at the String.equals() code, you'd find that the very first thing it does is to check if the two Strings it's been passed are '==', so the only thing you'll gain by doing it yourself is a method call (and possibly not even that).

                        Winston
                        • 9. Re: clarification on strings
                          843789
                          this is wat i got confused

                          String strNull1 = new String("xyz");
                                    String someText1 = new String("xyz");
                                    System.out.println(someText == strNull);
                                    System.out.println(someText.equals(strNull));
                                    String someText2 = someText1.intern();
                                    System.out.println(someText1 == strNull1);
                                    System.out.println(someText1.equals(strNull1));
                                    System.out.println(someText2 == someText1);

                          The bold statements returned false buth their contents are same.
                          • 10. Re: clarification on strings
                            843789
                            "xyz" is probably interned so presumably this would print true:
                            String a = "xyz";
                            String b = "xyz";
                            System.out.println(a == b);
                            But that doesn't apply when you're telling the JVM to create a new object, so I'd expect this to print false:
                            String a = "xyz";
                            String b = new String("xyz");
                            System.out.println(a == b);
                            • 11. Re: clarification on strings
                              843789
                              Diana12 wrote:
                              The bold statements returned false buth their contents are same.
                              That's because == compares object references, not object content. See my previous post.

                              Each time you use the new operator a new object is created and its reference returned,

                              String strNull1 = new String("xyz");

                              Here you pass the "xyz" object reference to a String constructor. Returned is a new reference pointing at the newly created object with the same content as the object which the reference you passed to the constructor, namely the "xyz" object.
                              • 12. Re: clarification on strings
                                3004
                                Diana12 wrote:
                                this is wat i got confused

                                String strNull1 = new String("xyz");
                                          String someText1 = new String("xyz");
                                          System.out.println(someText == strNull);
                                          System.out.println(someText.equals(strNull));
                                          String someText2 = someText1.intern();
                                          System.out.println(someText1 == strNull1);
                                          System.out.println(someText1.equals(strNull1));
                                          System.out.println(someText2 == someText1);

                                The bold statements returned false buth their contents are same.
                                == doesn't look at contents. It looks at references. In the first case, someText1 and strNull1 (bad name that, as that variable is definitely not null) both point to Strings created with "new." Since "new" always creates a new object (hence the name), it is a given that the references will be different.

                                In the second case, someText2 is a reference to the constant-pool copy of the String pointed to by someText1. But since you didn't do someText1 = someText1.intern(), someText1 is still pointing to the String that's not in the constant pool.
                                • 13. Re: clarification on strings
                                  843789
                                  Hi,

                                  Soory giving you a late response.

                                  I have read your post many times(all in this thred). is there a way i can kanow more abt constant pool and normal heap you were talking about.

                                  I want to know wich action/object will go to whic memory.

                                  Could you please give me an insight, that would be great.

                                  Thanks
                                  Diana
                                  • 14. Re: clarification on strings
                                    843789
                                    Diana12 wrote:
                                    I want to know wich action/object will go to whic memory.
                                    To be honest I think everything has been said and done now.

                                    Why don't you just use String and stop wondering about what happens behind the scene. It's all just a chimery anyway.

                                    The only thing you need to know is that a String really is an object althougt it may look like a primitive.

                                    Have that in mind and you'll be fine.

                                    You'll gain deeper knowledge in due time when you're ready for it.
                                    1 2 Previous Next