本文做equals(),equalsIgnoreCase()和==三种方式的比较
-
import java.util.StringTokenizer;
-
class Play
-
{
-
public static void main(String[] args)
-
{
-
String s1 = new String("I am a student");
-
String s2 = new String("I am a student");
-
String s3 = new String("I AM A STUDENT");
-
String s4 = s1;
-
-
boolean b1 = (s1 == s2);
-
boolean b2 = (s1 == s4);
-
boolean b3 = s1.equals(s2);
-
boolean b4 = s1.equals(s3);
-
boolean b5 = s1.equalsIgnoreCase(s2);
-
boolean b6 = s1.equalsIgnoreCase(s3);
-
-
System.out.println("s1 == s2: " + b1);
-
System.out.println("s1 == s4: " + b2);
-
System.out.println("s1 equals(s2): "+ b3);
-
System.out.println("s1 equals(s3):"+ b4);
-
System.out.println("s1 eqnalsIgnoreCase(s2): "+ b5);
-
System.out.println("s1 equalsIgnoreCase(s3): "+ b6);
-
}
-
}
编译,运行结果:
“==”比较的是内存的位置,不适宜比较字符串,但可以用来比较整型等。equals()比较的字符串内容必须完全一样,equalsIgnoreCase()在忽略大小写的情况下比较字符串。以下附上内存分配的图片
阅读(1157) | 评论(0) | 转发(0) |