==:
属于运算符的一种,比较基本数据类型时比较的是它们的值,对于对象引用类型比较的是对象的内存地址;
equals:
对于字符串来说是比较内容的,对于非字符串来说是比较指向的对象是否相同;
即如果被重写了比较值,没有被重写比较地址;(String,Data,File,包装类等重写了equals);
package com.chai;
public class compare {
public static void main(String args[]) {
float a = 0.1f;
double b = 0.1;
byte c = 1;
int d = 1;
short f = 1;
Integer integer = new Integer(1);
System.out.println(a==b);//float和double的精度不同结果为false;
System.out.println(c == d);//数值等同结果为true;
System.out.println(d == f);//等同结果为true;
System.out.println(integer == f);//不管是new创建的Integer对象,还是通过赋值int值创建的Integer对像,他们与int类型变量通过“==”进行比较时都会自动拆封装变成Int类型,所以Integer对象和Int变量比较的是内容大小;
String str1 = new String("hello");//此时str1存储的不是值本身而是指向的对象在内存中的存储地址;
String str2 = new String("hello");//同str1;
System.out.println(str1==str2);//==运算符在比较非基本数据类型时比较的便是对象在内存中的地址;结果为false
System.out.println(str1.equals(str2));//此时equals方法被String类重写,用来比较指向的字符串对象所存储的字符串是否相等;结果为true
}
}