= = and equals in Java

Source: Internet
Author: User

1,== is used to compare basic data types, and reference types. Equals is a method on an object that can be overridden by a quilt class to determine the consistency of the content.

The most wonderful is that Java basic data type (Byte,short,int,long,float,double,char,boolean), does not contain a string, so you cannot use = = to compare two strings equal.

        string S1 = new String ("abc");        String s2 = "abc";        System.out.println (S1==S2);        System.out.println (s1.equals (S2));

The result of execution is false,true.

In the habit of C # must make a mistake here, C # can be used to compare two strings equal, the advantage is not to judge whether the operands on both sides is null. Although string is not a value type in C #, it does a special deal with = =.

Like what:

        if (S1.equals ("this")) {        //mode 1        }        if ("This". Equals (S1)) {/        /mode 2        }        if (s1.equals (S2)) {        / /Mode 3        }

Both mode 1 and Mode 3 are likely to encounter null, and then the program hangs out. So generally the second way in the program is more.

But if Java also like C # to make string can be compared with = =, will bring great convenience, string class is too common.

        if (S1==S2) {        //This one is enough        }

= = and equals in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.