在初学 java 时,可能会经常碰到下面的代码:
String s1 = new String ("hello") ;
String s2 = new String ("hello");
System.out.println(s1==s2); // false
System.out.println(s1.equals (s2)); // true
为什么第 4 行和第五行的输出结果不一样? == 和 equals 方法之间的区别是什么?
一、关系操作符 " == " 到底比较的是什么?
下面这句话是摘自 《 java 编程思想 》一书中的原话:
" 关系操作符生成的是一个 boolean 结果,它计算的是操作数的值之间的关系 "
说简单点,== 就是用来比较值是否相等。
例子:
package com.darksnow.test;
public class Demo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 3 ;
int m = 3 ;
System.out.println(n==m); // true
String s1 = new String("hellom");
String s2 = new String("hellom");
String s3 = new String("hellom");
System.out.println(