The difference between = = and. Equals () in Java

Source: Internet
Author: User

In Java, we use the = = and. Equals () When comparing two data types, but what is the difference between the two? Let's look at some examples below.

Package Test;public class Test {public static void main (string[] args) {//TODO auto-generated method stubstring A = "1"; S Tring B = "1";//int a = 1;//int B = 1;if (A = = b) {System.out.println ("= =");} if (A.equals (b)) {System.out.println (". Equal ()");}}}

both = = and. Equals () are output, but when we change the data type of AB to String, the. Equals () method will give an error. What is this for?

For the basic data type (Byte,short,char,int,long,float,double,boolean), it is necessary to use = = To determine whether the two variables are equal.

For non-basic data types, the. Equals () and = = can be used essentially to compare the same reference for two objects. Just. Equals () is overridden in these classes by string,integer,date to determine whether the specific storage content is equal, not the memory address.

The difference between = = 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.