String Object equals method question

What is the difference between these two lines of code:
     boolean ok = myString.equals(�foo�);
     boolean ok = �foo�.equals(myString);

If myString is null, the first one will throw a NullPointerException, whereas the second one will just evaluate to false.
If you know myString won't be null, I find the first one more natural looking, but that may just be personal preference.
If there's a chance that myString could be null, and it's valid for it to be null and you just want to handle that like any other unequal case, then the second one saves you an explicit null test, since String's equals method does it ayway.
String str = null;
str.equals("foo"); // #1
"foo".equals(str); // #2 Do you understand why #1 throws NullPointer exception and why #2 does not?

Similar Messages

  • Difference between Object equals() method and ==

    Hi,
    Any one help me to clarify my confusion.
    stud s=new stud();
    stud s1=new stud();
    System.out.println("Equals======>"+s.equals(s1));
    System.out.println("== --------->"+(s==s1));
    Result:
    Equals ======> false
    == ------------> false
    Can you please explain what is the difference between equals method in Object class and == operator.
    In which situation we use Object equals() method and == operator.
    Regards,
    Saravanan.K

    corlettk wrote:
    I'm not sure, but I suspect that the later Java compilers might actually generate the same byte code for both versions, i.e. I suspect the compiler has gotten smart enough to devine that && other!=null is a no-op and ignore it... Please could could someone who understands bytecode confirm or repudiate my guess?Don't need deep understanding of bytecode
    Without !=null
    C:>javap -v SomeClass
    Compiled from "SomeClass.java"
    class SomeClass extends java.lang.Object
      SourceFile: "SomeClass.java"
      minor version: 0
      major version: 49
      Constant pool:
    const #1 = Method       #4.#15; //  java/lang/Object."<init>":()V
    const #2 = class        #16;    //  SomeClass
    const #3 = Field        #2.#17; //  SomeClass.field:Ljava/lang/Object;
    const #4 = class        #18;    //  java/lang/Object
    const #5 = Asciz        field;
    const #6 = Asciz        Ljava/lang/Object;;
    const #7 = Asciz        <init>;
    const #8 = Asciz        ()V;
    const #9 = Asciz        Code;
    const #10 = Asciz       LineNumberTable;
    const #11 = Asciz       equals;
    const #12 = Asciz       (Ljava/lang/Object;)Z;
    const #13 = Asciz       SourceFile;
    const #14 = Asciz       SomeClass.java;
    const #15 = NameAndType #7:#8;//  "<init>":()V
    const #16 = Asciz       SomeClass;
    const #17 = NameAndType #5:#6;//  field:Ljava/lang/Object;
    const #18 = Asciz       java/lang/Object;
    SomeClass();
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    public boolean equals(java.lang.Object);
      Code:
       Stack=2, Locals=2, Args_size=2
       0:   aload_1
       1:   instanceof      #2; //class SomeClass
       4:   ifeq    25
       7:   aload_1
       8:   checkcast       #2; //class SomeClass
       11:  getfield        #3; //Field field:Ljava/lang/Object;
       14:  aload_0
       15:  getfield        #3; //Field field:Ljava/lang/Object;
       18:  if_acmpne       25
       21:  iconst_1
       22:  goto    26
       25:  iconst_0
       26:  ireturn
      LineNumberTable:
       line 6: 0
    }With !=null
    C:>javap -v SomeClass
    Compiled from "SomeClass.java"
    class SomeClass extends java.lang.Object
      SourceFile: "SomeClass.java"
      minor version: 0
      major version: 49
      Constant pool:
    const #1 = Method       #4.#15; //  java/lang/Object."<init>":()V
    const #2 = class        #16;    //  SomeClass
    const #3 = Field        #2.#17; //  SomeClass.field:Ljava/lang/Object;
    const #4 = class        #18;    //  java/lang/Object
    const #5 = Asciz        field;
    const #6 = Asciz        Ljava/lang/Object;;
    const #7 = Asciz        <init>;
    const #8 = Asciz        ()V;
    const #9 = Asciz        Code;
    const #10 = Asciz       LineNumberTable;
    const #11 = Asciz       equals;
    const #12 = Asciz       (Ljava/lang/Object;)Z;
    const #13 = Asciz       SourceFile;
    const #14 = Asciz       SomeClass.java;
    const #15 = NameAndType #7:#8;//  "<init>":()V
    const #16 = Asciz       SomeClass;
    const #17 = NameAndType #5:#6;//  field:Ljava/lang/Object;
    const #18 = Asciz       java/lang/Object;
    SomeClass();
      Code:
       Stack=1, Locals=1, Args_size=1
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
      LineNumberTable:
       line 1: 0
    public boolean equals(java.lang.Object);
      Code:
       Stack=2, Locals=2, Args_size=2
       0:   aload_1
       1:   instanceof      #2; //class SomeClass
       4:   ifeq    29
       7:   aload_1
       8:   ifnull  29
       11:  aload_1
       12:  checkcast       #2; //class SomeClass
       15:  getfield        #3; //Field field:Ljava/lang/Object;
       18:  aload_0
       19:  getfield        #3; //Field field:Ljava/lang/Object;
       22:  if_acmpne       29
       25:  iconst_1
       26:  goto    30
       29:  iconst_0
       30:  ireturn
      LineNumberTable:
       line 6: 0
    }

  • String equal method Vs Object equal method.

    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.

    RGEO wrote:
    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.Because "equal" means different things for different objects. For a String, "equal" would mean that both Strings being compared have the exact same characters, in the same sequence. For an Integer, "equals" would mean that both objects have the same integer value.

  • POF object equals() method

    Hi there,
    I have got a compound key that represented with Java object that has three member fields. One of the fields should not be part of the key, so it should not be used when two keys are compared.
    This logic is defined in equals function
         public boolean equals(Object that) {
              CacheFactory.log("Hello from equals: " + this.toString());
              boolean result = false;
              if (this == that) {
                   result = true;
              } else {
                   if (that == null)
                        result = false;
                   else{
                        if (!(that instanceof KeyObject)) {
                             result = false;
                        } else {
                             KeyObject other = (KeyObject) that;
                             if (this.field1.equalsIgnoreCase(other. field1)
                                       && ( (this. field2.equalsIgnoreCase(other. Field2))))
                                  result = true;
                             else
                                  result = false;                    
              CacheFactory.err("Equals result is " + result);
              return result;
    Then I put on Coherence object with the following key {“field1_value”, “field2_value”, “field3_value”}. Then I am removing object from Coherence with the following key {“field1_value”, “field2_value”, “field3__another_value”}.
    According to the defined equals() function, those two keys are equal, but object is not getting removed. To remove it, I had to make all fields equal, even field3.
    Another thing – I do not see any logging from equals() function – I am using CacheFactory.log() to write log entry. Look in all logs files and could not find them – where I should be looking for them or what I should be using for logging from equals() function?

    Hi
    Yes you are correct and this is due to the fact that Coherence will first serialize your Key into a Binary. Which have a slightly more optimized .equals() implementation. Since the Binary is a result of the serialization if you serialize all three fields all three fields will be used for the comparison.
    If you really would like the remove the entries based upon two of the fields in the key I'd suggest a EntryProcessor combined with an
    Filter filter = new AndFilter(new EqualsFilter(new PofExtractor(String.class, ID_1), “field1_value”) , new EqualsFilter(new PofExtractor(String.class, ID_2), “field2_value”))
    This should match all entries with keys that where the first index (ID_1) == "field1_value" and the second index (ID_2) == “field2_value”.
    the you'd execute this filter inside your cache to remove the entries by
    cache.invokeAll(filter, new ConditionalRemove(AlwaysFilter.INSTANCE));
    Hope it helps
    /Charlie

  • Can we use equals method in JSTL

    hia all,
    is there is possible to use equals method in JSTL c:when tag. if so please give me an example or else please tell me some solution.
    regards
    subramanian

    Have you tried it anyway? Where exactly are you talking about with "contents"?
    Remember that the == operator in JSTL isn't the same as the == operator in Java. In JSTL it invokes the Object#equals() method behind the scenes, while in Java it checks the equality of the reference.

  • Use of hashCode and equals method in java(Object class)

    What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.

    You could find that out easily with google, that is a standard junior developer interview question.

  • Question about "java.lang.Object.equals()".

    public class TestEquals {
      private int a;
      private int b;
      public TestEquals(int a,int b) {
        setA(a);
        setB(b);
      public int getA() {
        return a;
      public void setA(int a) {
        this.a = a;
      public int getB() {
        return b;
      public void setB(int b) {
        this.b = b;
      public static void main(String[] args) {
        TestEquals te01 = new TestEquals(1,2);
        TestEquals te02 = new TestEquals(1,2);
        System.out.println("te01 equals to te02: " + te01.equals(te02));
        te01.setA(2);
        System.out.println("te01 equals to te02: " + te01.equals(te02));
    }The result is:
    te01 equals to te02: false
    te01 equals to te02: false
    Why the first case is false?

    You didn't override Object.equals() in your TestEquals class. So, you are calling Object.equals(), which just compares reference values. You need to write your own equals() method (presumably, make sure te01.a==te02.a and te01.b==te02.b). Depending on what you do with your objects, you would want to override Object.hashCode(), too.

  • Object.equals() question.

    Lets say i have a class:
    public class MyClass{
    int x;
    int y;
    int z;
    }And i have two objects: one and two...
    will
    one.equals(two)return true if the fields for both objects hold the same values?
    or return true if they both point to the exact same object?
    Edited by: JamesBarnes on Oct 8, 2008 12:34 PM

    hmm ok, how about this:
    i went to add my own equals method to my class:
    public class Block{
    private int x;
    public boolean equals(Block block){
    if this.x == block.getX(); // <-- Problem
    public int getX(){
    return x;
    }You can probably see what is going on here, i want to pas the equals method an object of type Block, but because the equals method is within Block it would seem that the method block.getX() cannot be used.
    Bizzarrely (im using net beans) although the fields are all private access i can see the fields of the passed "Block block" but not the methods that belong to block.
    I can sort of see the problem, calling accessor methods from within a block, its sort of like delving into it's self, but i cant see how else to check for similar objects.
    I hope i have made the problem clear,
    J

  • How to execute a method from String object?

    I have some methods in String objects, example:
    String methodOne = "someMethod1";
    String methodTwo = "someMethod2";
    public void someMethod1() {
    public void someMethod2() {
    How can i execute that methods, when the method names i have only in String objects?

    You can get the method directly from the name and parameter types if you want to avoid using the loop:public class Foo27 {
      public static void main (String[] args) throws Exception{
        String methodOne = "someMethod1";
        String methodTwo = "someMethod2";
        Object foo = new Foo27();
        Method method1 = foo.getClass().getMethod(methodOne, new Class[]{});
        method1.invoke(foo, null);
        Method method2 = foo.getClass().getMethod(methodTwo, null);
        method2.invoke(foo, null);
      public void someMethod1() {
        System.out.println("someMethod1");
      public void someMethod2() {
        System.out.println("someMethod2");
    }The parameter types are required as there could be more than one method with the same name.
    For somereason when I tried to create a new Method object and invoke it, an exception was thrownThere isn't a public constructor for Method, so how did you create a new one?
    Pete

  • Overriding equals(Object o) method

    hi,
    I have a problem in equals method ..returns true always...
    can anyone suggest whats wrong ?
    thanks for the help
    public  boolean equals(Object NumberC)
                if (NumberC == null) return false;
                 if ( NumberC instanceof Counter)
                      Counter myCr = ( Counter) NumberC;
                     if(this.number == (myCr)
                         return true;
                     }//end if
                 } //end if 
                 return false;
             }// end equals
      

    sorry..yes it always returns true
    here's my code again
    public  boolean equals(Object NumberCounter)
                if (NumberCounter == null) return false;
                 if ( NumberCounter instanceof Counter )
                     Counter myCr = ( Counter ) NumberCounter;
                     if(this.number == (myCr.number))
                         return true;
                     }//end if
                 } //end if 
                 return false;
             }// end equals

  • Why jvm maintains string pool only for string objects why not for other objects?

    why jvm maintains string pool only for string objects why not for other objects? why there is no pool for other objects? what is the specialty of string?

    rp0428 wrote:
    You might be aware of the fact that String is an immutable object, which means string object once created cannot be manipulated or modified. If we are going for such operation then we will be creating a new string out of that operation.
    It's a JVM design-time decision or rather better memory management. In programming it's quite a common case that we will define string with same values multiple times and having a pool to hold these data will be much efficient. Multiple references from program point/ refer to same object/ value.
    Please refer these links
    What is Java String Pool? | JournalDev
    Why String is Immutable in Java ? | Javalobby
    Sorry but you are spreading FALSE information. Also, that first article is WRONG - just as OP was wrong.
    This is NO SUCH THING as a 'string pool' in Java. There is a CONSTANT pool and that pool can include STRING CONSTANTS.
    It has NOTHING to do with immutability - it has to do with CONSTANTS.
    Just because a string is immutable does NOT mean it is a CONSTANT. And just because two strings have the exact same sequence of characters does NOT mean they use values from the constant pool.
    On the other hand class String offers the .intern() method to ensure that there is only one instance of class String for a certain sequence of characters, and the JVM calls it implicitly for literal strings and compile time string concatination results.
    Chapter 3. Lexical Structure
    In that sense the OPs question is valid, although the OP uses wrong wording.
    And the question is: what makes class Strings special so that it offers interning while other basic types don't.
    I don't know the answer.
    But in my opinion this is because of the hybrid nature of strings.
    In Java we have primitive types (int, float, double...) and Object types (Integer, Float, Double).
    The primitive types are consessons to C developers. Without primitive types you could not write simple equiations or comparisons (a = 2+3; if (a==5) ...). [autoboxing has not been there from the beginning...]
    The String class is different, almost something of both. You create String literals as you do with primitives (String a = "aString") and you can concatinate strings with the '+' operator. Nevertheless each string is an object.
    It should be common knowledge that strings should not be compared with '==' but because of the interning functionality this works surprisingly often.
    Since strings are so easy to create and each string is an object the lack ot the interning functionality would cause heavy memory consumption. Just look at your code how often you use the same string literal within your program.
    The memory problem is less important for other object types. Either because you create less equal objects of them or the benefit of pointing to the same object is less (eg. because the memory foot print of the individual objects is almost the same as the memory footpint of the references to it needed anyway).
    These are my personal thoughts.
    Hope this helps.
    bye
    TPD

  • Equals methods

    i'm trying to get the hang of some of the equals methods and i just want to check i'm doing this right
    my question is about the variables that are of type Object.(ob1, ob2)
    String s1 = "water", s2 = "mountain";
    Object ob1 = new String("mountain");
         Object ob2 = new Integer(250);
    System.out.println("ob1.equals(s2): "+ob1.equals(s2));
    System.out.println("ob2.equals(new Integer(250)): "+ob2.equals(new Integer(250)));
    System.out.println("ob2.equals(new Integer(150)): "+ob2.equals(new Integer(150)));
        is it correct that even though ob1 is of type object, it is still calling the equals method of the String class, and not the the equals method of class Object?
    and ob2 is pointing to an Integer object, so the Integer class equals methos gets called?
    i think this is correct but not 100% sure.

    jverd wrote:
    mark_8206 wrote:
    is it correct that even though ob1 is of type object, it is still calling the equals method of the String class, and not the the equals method of class Object?
    and ob2 is pointing to an Integer object, so the Integer class equals methos gets called?Correct.thanks!

  • Scenario in which implement or Write our own hascode and equals method

    Dear All,
    Please let me know in which circumstances we write our own Hashcode method and equals method not the default one provided by java.Kindly give me complete code and scenario.
    Thanks
    Sumit

    Thanks for your reply
    I have one more question.
    When equal method of Object class give the same result as equals we override then why should we override equals.For example see the below code
    public class EqualsTest{
    public EqualsTest() {
         super();
    public static void main(String[] args) {
    Moof one =new Moof(8);
    Moof two =new Moof(8);
    if(one.equals(two))
    System.out.println("one is equals to two");
    class Moof {
    private int moofvalue;
    Moof(int val){
    System.out.println("val inside moof constructor"+val);
    moofvalue=val;
    System.out.println("moofvalue inside moof constructor" +moofvalue);
    public int getMoofValue()
    System.out.println("moofvalue inside getmoffvalue method "+moofvalue);
    return moofvalue;
    public boolean equals(Object o)
    System.out.println("Object o in equals"+o);
    if( (o instanceof Moof) &&(( (Moof)o).getMoofValue()==this.moofvalue))
    System.out.println("true");
    return true;
    else
    System.out.println("false");
    return false;
    Here the output we get is :
    val inside moof constructor8
    moofvalue inside moof constructor8
    val inside moof constructor8
    moofvalue inside moof constructor8
    Object o in equalsMoof@119c082
    moofvalue inside getmoffvalue method 8
    true
    one is equals to two
    The last output "one is equals to two" gives the same result as overridng equals by us.So why should we override equals here.
    Thanks
    Sumit

  • What would be the result if we overrode the equals method properly

    import java.util.*;
    class Nearly{
       String value:
       Nearly(String v){ value = v;}
       public int hashCode(){ return 1;}
       public boolean equals(Nearly n){
       if(value.charAt(0) == n.value.charAt(0)) return true;
       return false;
       public static void mian(String [] sss){
         Nearly n1 = new Nearly("aaa");
         Nearly n2 = new Nearly("aaa");
         String s = "_";
         if(n1.equals(n2)) s += "1";
         if(n1==n2) s += "2";
         Set <Nearly> set = new HashSet <Nearly>();
          set.add(n1);
          set.add(n2);
         System.out.println(s + " " + set.size());
    }Ans: b) -1 2
    Reason: Two different equals() methods are invoked, because the equals() method shown in the code doesn't properly override Object.equals(), which takes an Object
    Ok so what would have been the result if the equals() method was something like this:
    public boolean equals(Object n)
    {I guess my question is about the overriding the equals() method which i am not able to understand

    pksingh79 wrote:
    what would be the result if we overrode the equals method properlyThe result would be a method, the functionality of which would adhere to Object#equals()'s contract:
    public boolean equals(Object obj)
    Indicates whether some other object is "equal to" this one.
    The equals method implements an equivalence relation on non-null object references:
    &#42; It is reflexive: for any non-null reference value x, x.equals(x) should return true.
    &#42; It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and
    only if y.equals(x) returns true.
    &#42; It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and
    y.equals(z) returns true, then x.equals(z) should return true.
    &#42; It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y)
    consistently return true or consistently return false, provided no information used in equals
    comparisons on the objects is modified.
    &#42; For any non-null reference value x, x.equals(null) should return false.

  • String objects' behavior

    Hello,
    I have two classes
    testA
    public class testA {
    public static void main(String args[]) {
    String s1 = "abc";
    String s2 = "abc";
    if(s1 == s2)
    System.out.println(1);
    else
    System.out.println(2);
    if(s1.equals(s2))
    System.out.println(3);
    else
    System.out.println(4);
    testB
    public class testB {
    public static void main(String args[]) {
    String s1 = "abc";
    String s2 = new String("abc");
    if(s1 == s2)
    System.out.println(1);
    else
    System.out.println(2);
    if(s1.equals(s2))
    System.out.println(3);
    else
    System.out.println(4);
    Why is the first test (s1==s2) evaluating to true (haven't we got two string objects here??) and the second evaluating to false?
    Thanks in advance,
    Balteo.

    The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. The JVM can reuse and share string references because strings are immutable and, therefore, by definition thread-safe. In fact string objects will be stored in a pool whenever you create a string object JVM will check if it exists in the pool otherwise it creates. If it exists in the pool then JVM gets it from the pool and there is no harm in doing so, because strings are immutable - can't be changed. When you explicitly create a string object like String str = new String()...It will create a new object (it may or maynot exist in the pool). The equals() method of Object class does the indepth comparison i.e it compares the actual objects unlike the object reference in the case of == operator.
    I would like to tell you to visit the Javaworld site (URL: http://www.javaworld.com/javaqa/2002-09/01-qa-0906-strings.html?#) where similar questions are answered.
    I hope this helps out you better.
    Sree Ramakrishna
    That's a nice design; although a design you must be aware of and treat accordingly.

Maybe you are looking for