Differences between == and .equals

I'm rather new to Java programming and have learned that == can only be used to compare primitive types in Java (for example when comparing to int) and when comparing objects, one should use the .equals-method (that should be overloaded from the one in Object). This is because == compare the object's reference adress (is this correct?) For example:
Vector v1 = new Vector();
Vector v2 = new Vector();
v1.add("hello");
v2.add("hello");
System.out.println(v1 == v2);This program should print false, since v1 and v2 are different objects.
System.out.println(v1 == v1);should print true.
OK, so far so good. However, an experiment I've made clearly shows that there's an exception to this rule. When comparing objects of type String, you don't need to use .equals, == works perfectly. My question is why?

When comparing objects of type String, you
don't need to use .equals, == works perfectly. My
question is why?It doesn't work perfectly at all.
String literals
Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same character sequence), use equals(), e.g. if (str1.equals(str2))...
Example:String s1 = "foo";
String s2 = new String("foo");
System.out.println("s1 == s2: " + (s1 == s2)); // false
System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus ==

Similar Messages

  • Difference between == and .equals

    How do they differ in functionality?
    Thanks in advance

    hi javanovice33,
    simply put:
    == tests if two object references point to the same and only one object
    and
    .equals() tests if two object references contain identical contents
    Illustration A:
    String hello1 = "Hello";
    String hello2 = "Hello";
    is hello1==hello2?
    answer: TRUE
    reason: both object references point to the same and only one
    object "Hello". Note that literal String "Hello" is immutable and
    can no longer be changed. JVM memory heap will try to look
    first for the existence of the same value if another object reference
    is initialized to the same literal String "Hello". Therefore, in this case,
    the declaration and initialization above can be rewritten as hello2=hello1.
    is hello1.equals(hello2)?
    answer: TRUE
    reason: both object references contain identical contents "Hello"
    Illustration B:
    String hellow1 = new String("Hello");
    String hellow2 = new String("Hello");
    is hellow1==hellow2?
    answer: FALSE
    reason: each object reference points to distinct object in memory
    thus, they are not equal
    Is hellow1.equals(hellow2)?
    answer: TRUE
    reason: both object references contain identical contents "Hello"
    Regards,

  • What is difference between == and equals ??? i wanna know in detain example

    Hi
    1) String s1 = new String("abs");
              String s2 = s1;
              System.out.println(s1==s2);
              System.out.println(s1.equals(s2));
    Output:
    true
    true
    2)
    String s1 = new String("abs");
              String s2 = s1;
              s2 = "abs";
              System.out.println(s1==s2);
              System.out.println(s1.equals(s2));
    output:
    false
    true
    i m not getting that here s1 is object and its assigned to s2 object so both are point to same memory location...but while assinging s2 = "abs" which is same as s1 then its behave like different object y?

    but while assinging s2 = "abs" which is same as s1 then its behave like different object"abs" is "the same as" s1 in the sense that it represents the same characters in the same order. But it is also different from s1 in that it refers to a different object. It's the same distinction as you get comparing two $20 notes: they are equal but, since there are two of them they cannot be identical.
    With Java reference variables this equal/indentical distinction is represented by equals()/==.
    In general each class defines its own equals(). (Much as there will be a legal definition what what counts as being equal to $20.) This realationship is generally what you mean and hence the rule "when comparing objects use equals()".

  • Difference between and != operators

    Hi All,
    My question may be very basic to you all
    Please let me know the difference between <> and != operators
    Thanks in advance

    user609996 wrote:
    Sorry to all,
    the operator "<>" is not printed
    I want the difference between "<>" and "!=" operators.And as you've already been told there is no difference between the &lt;&gt; and != operators. They mean the same thing, but are just different representations of it.
    The only difference is that the Oracle forum can't display &lt;&gt; if it is just typed in normally. To show it we have to type &lt and &gt with a ";" after each.

  • Difference between & and && operater   and  difference between and

    what is difference between & and && oprater in java
    and what is difference between << and <<< operater

    i am sorry i dont know about << ,<<<< There isn't a <<< operator.
    However I presume the operator being referred to is >>>
    They are bit shifting operators.
    In fact its the [url http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html]very next page of the tutorial linked to above.
    << == left shift
    == right shift,
    == right shift (unsigned)
    Cheers,
    evnafets

  • Difference between " " and ' ' in oracle

    Hi
    What is the difference between " " and ' ' in oracle

    Generally, single quotes ' are used as string delimiters. Double quotes are NOT string delimters in SQL, but are used to preserve the precise representation of what's enclosed - for instance, "abc" would be recognized as lowercase in situations where SQL would automatically translate them into upper case. Thus, something like
    SQL> select dummy as "dummy"
      2    from dual;
    d
    Xmeans to select the dummy column but preserve the name in lower case where normally the 'd' in the column name (cut off) would be 'D'
    Using empty strings to represtent nulls has already been discussed on this thread. Remember that spaces are NOT nulls. I personally find the replace-null-with-space method a bit clunky, but a lot of mainframe-to-oracle conversions use it.

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

  • Please tell basic difference between "" and null  for String  variable.

    1.What is difference between String strRemitInfo = "" and String strRemitInfo = null?
    2. Which one is good practice while coding ?

    1.What is difference between String strRemitInfo = ""
    and String strRemitInfo = null?Emptry string and nul reference
    >
    2. Which one is good practice while coding ?Depends on what you want to do.

  • Whats the difference between and Album and a Smart Album

    OK, just upgraded.... So, whats the difference between an Album and a Smart Album?  
    Also, I like to organise my stuff, so if I create a folder for each year, and then a project within that year, why is it that the photos are always in both - and then again if I chose to create an album specific to a project, they are there again.
    So it might look:
              Folder (2012 Equine Photography)
                   Project - Specific Events
                        Album - Big Barn Dressage May
    Does this mean the individual photo is stored 3 times and using 3 times the space?
    Thanks guys!

    Mrsthebraggster wrote:
    So it might look:
              Folder (2012 Equine Photography)
                   Project - Specific Events
                        Album - Big Barn Dressage May
    Does this mean the individual photo is stored 3 times and using 3 times the space?
    No. Conceptually the Master only lives lives in the single (time based) Project you import it into. Albums are just collections of pointers that point to  images in various Projects.
    "Big Barn Dressage May" could be a Project, but only if it is only one day and a limited number of image files; otherwise an Album. "2012 Equine Photography" should be an album or a Folder of Albums. "Specific Events" could be an Album or a Folder of Albums.
    A Project should not be used as a Folder.
    From an earlier post of mine:
    Folders are indeed flexible organizational tools but IMO often overused. Folders can effectively hide contents from view and therefore require users to remember how folders are nested and what is inside them. Folders were the only way to deal with single-original film, but are IMO limiting to image database thinking.
    The way I look at it conceptually:
    Aperture is a database (DB), and each image file lives in one Project.
    Albums are just collections of Pointers that point to individual image files living in one or more Projects. Since they just contain pointers, albums can be created or deleted at will without affecting image files. Very powerful. And Albums of pointers take up almost zero space, so they are fast and do not make the Library size grow.
    Keywords can be applied to every image separately or in batches. Keywords are hugely powerful and largely obviate the need for folders. Not that we should never use folders, just that we should use folders only when useful organizationally - - after first determining that using keywords and albums is not a better approach.
    As one example imagine the keyword "flowers."  Every image of a 100,000 images Library that has some flowers in it has the keyword flowers. Then say we want to put flowers in an ad, or as background for a show of some kind, or to print pix for a party, or even just to look for an image for some other reason. We can find every flower image in a 100k-image database in 2 seconds, and in another few seconds create an Album called "Flowers" that points to all of those individual images.
    Similarly all family pix can have a keyword "family" and all work pix can have a key word "work." Each individual pic may have any number of keywords. Such pic characteristics (work, family, flowers, etc.) should not be organized via folders.
    So by using keywords and albums we can have instant access to every image everywhere, very cool. And keywords and albums essentially take up no space in the database.
    Another approach is to use a folder "Family" for family pix, a folder "Flowers" for flowers pix and another folder "Work" for work pix. IMO such folders usage is a very poor approach to using an images database (probably stemming from old paper or film work practices). Note that one cannot put an image with family in a field of flowers at a work picnic in all three folders; but it is instant with keywords.
    HTH
    -Allen

  • Difference between and lock and eneque in oracle

    Please give the difference between a lock and eneque in oracle
    Naveen

    Here is what Oracle defines an Enqueue to be in the 9.2 Glossary >>
    enqueue
    Shared memory structures that serialize access to database resources. Enqueues are local to one instance if Real Application Clusters is not enabled. When you enable Real Application Clusters, enqueues can be local or global to a database. (See also: latch, lock, and resource.)
    <<
    There is also a type of enqueue associated with Advanced Queueing. Similar concept but different specialized purpose.
    Generally speaking Locks on the other hand serialize access to row data. Oracle actually records row locks in the data blocks.
    Enqueues, Locks, and Latches are perform the same basic function: serialize access but the methods are implemented differently and applied to different functional areas of the rdbms.
    HTH -- Mark D Powell --

  • Difference between ';' and '/' in the SQL scripts

    Hi All,
    Could anyone please let me know the difference between placing ';' and '/' in the sql scripts.
    I am placing couple of insert statements in a textfile with .sql extension and running it from the sql prompt.
    Which one( ';' or '/') should be keep at the end of each statement in the script.
    SQL> SELECT SYSDATE FROM DUAL;
    SYSDATE
    12-MAY-13
    SQL> SELECT SYSDATE FROM DUAL
      2  /
    SYSDATE
    12-MAY-13Thanks,

    968217 wrote:
    My doubt is how it understands or the difference b/w the below two view statements one with ';' and another one with '/'. Sorry if i am unclear.They are identical in SQL*Plus. These characters mean "+send entered/buffered text to Oracle to parse and execute+".
    So - SQL*Plus sends "+create or replace view ev1 as select ename , sal from emp+" to the server (via a cursor execute):
    create or replace view ev1 as select ename , sal from emp
    /And again, SQL*Plus sends "+create or replace view ev1 as select ename , sal from emp+" to the server (via a cursor execute):
    create or replace view ev2 as select ename , sal from emp;These are identical statements.
    As I mentioned in the post I referred you to. Oracle also uses the ";" character in the PL/SQL language. So when you enter PL/SQL code in SQL*Plus, you do not want SQL*Plus to send each line of PL/SQL code to the server. Instead, you want it to wait till the last statement has been entered and then send the the whole block to the server to be parsed and executed,
    SQL*Plus has a basic parser itself. It uses that to figure out what you have entered, and whether a ";" you enter is an instruction from you to it, to send the text to the server - or when you enter a ";", it is part of the text for the server and that it should not react to it.
    Thus when you enter the following, SQL*Plus recognises that you are using the SQL language, and as this language does not use ";" characters, a ";" character when entered means that it needs to send the text to the server to be parsed and executed:
    SQL> select * from emp;
    // ; character instructs SQL*Plus to create and execute cursor "select * from emp"When you enter PL/SQL code, SQL*Pus recognises that and knows that ";" characters entered indicates end-of-statement for PL//SQL and that it should not act on that,
    SQL> begin
      2    null;
      3  end;
      4  /
    // SQL*Plus ignores the ";" character - and the "/" character is used to
    // instruct SQL*Plus to create and execute cursor"begin<LF>null;><LF>end;"

  • Difference between * and ALL field values?

    Greetings to all,
    Here is an intresting question. For a particular authorization object of a role, I see that it has a field value of ALL for a specific field. Is this same as * or is there any subtle difference between the two. This is in ECC 5.0.I would greatly appreciate a discussion. Thanks.

    i have also seen the value ALL in some roles in my org...
    Object:C_PRPS_USR (PS: Model for User Field Authorization for WBS elements)
    Field:USR10_1 (User field with 10 characters)
    Value: ALL
    If ALL means value ALL then what is the significance of it in the above field?
    Pls throw some light...
    thankx
    Sachin

  • Difference between ' and " in tags

    I see some people posting code with tag library tags using ' (single quote) around attributes sometimes. Is there a functional difference between the 2 styles like in Perl, or is it like Javascript where it doesn't matter, or is this just typing mistakes?

    Yes, yes, that's like Javascript/HTML, so things aren't confused. But what is this action, cuz the taglib tags would be pulled out on the server before the browser sees it...
    Are you meaning (taglib in plain HTML):
    <form action="<bean:write name='beanname' property='propname' />">...</form>
    or are you meaning you can do this (nested taglib tags):
    <html:form action="<bean:write name='beanname' property='propname' />">...</html:form>
    ?? Cuz I've do this with no problems:
    <form action="<bean:write name="beanname" property="propname" />">...</form>

  • Difference  between the equals() and == operator

    Hi.....
    I was new to the java. I need a clear explanation of equals and == .
    As of now ..i know this difference
    1) == operator is used to verify whether the object references are equal or not.Depending on which it returns boolean.
    2) equals() --> which in turn implicitly overrides the hashCode() .checks whether both the objects values are equal or not.
    plz kindly practically this with an example.
    thank U
    Aditya V

    1) == operator is used to verify whether the object
    references are equal or not.Depending on which it
    returns boolean.Yes.
    2) equals() --> which in turn implicitly overrides
    the hashCode()No, it does not. If you override equals, you need to override hashCode. One method does not override another one of a different name.
    .checks whether both the objects
    values are equal or not.Well, it can do whatever you want. In the case of Object, it just calls ==. If you decide to override it, then, yes, you SHOULD do some sort of comparison of the obects' fields to determine if the objects are "equal" according to your semantics.

  • What's the difference between | and ||

    I have three strings and if even one of them is null (s1 == null), I need to do something. So I have this:
    if( s1 == null | s2 == null | s3 == null)
       //action code
    }Yet the action code is occuring even if none of the strings are null.

    Try to run this code:
    public static void main(String[] args) {
      String s = null;
      if (s == null || s.equals("blah"))
        System.out.println("without exception");
    }And now try this:
    public static void main(String[] args) {
      String s = null;
      if (s == null | s.equals("blah"))
        System.out.println("with exception");
    }Try to understand why these two cases are different, and what�s going on.

Maybe you are looking for