Java basics - comparison operation

comparison operation

  • Double equal sign == Compare basic data types, only compare values, regardless of precision and type
  • Double equal sign == compares reference data types, compares memory addresses, and does not apply
  • You can use the .equals method to compare strings, which compares the contents of strings
  • The double equal sign == comparing the wrapper class also compares the memory address. If it is a value reserved in the cache, there is no need to create a new wrapper object, and the wrapper objects with equal values ​​are compared to true with a double equal sign. If the value exceeds the cache, the wrapper will automatically create a new wrapper object, and the values ​​​​are equal at this time Wrapper class objects with double equal signs compare to false
  • In order to avoid this singularity, the comparison of wrapper class objects generally uses the .equals method
String s1 = "abc"; // java做了优化,这样声明会将对象放在字符串常量池中,如果有一样的字符串,和它公用一块内存
String s2 = "abc"; // 两个"abc"是相同的内存地址
System.out.println(s1 == s2); // 结果为true
String s3 = new String("abc"); // 这样声明一个新对象,与s1不在同一个内存中
System.out.println(s1 == s3); // 结果为false
System.out.println(s1.equals(s3)); // 结果为true,equals方法比较的是字符串的内容
Integer i1 = 128; // 简易写法,实际上调用了valueOf方法
Integer i2 = Integer.valueOf(128); // 完整写法,valueOf方法中有缓存操作,范围-128~127
System.out.println(i1 == i2); // 结果为false,因为128超出了缓存范围,创建了新的包装类对象
System.out.println(i1.equals(i2)); // 结果为true,比较的是内容

Guess you like

Origin blog.csdn.net/weixin_46838605/article/details/129873839