1.7.1 ==
== 比较的是对象的地址,只有两个字符串变量都指向字符串的常量对象时,才会返回 true 。
示例:
package com.github.string.demo20;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class Test {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2); // true
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s3 == s4); // false
System.out.println(s1 == s4); // false
}
}
1.7.2 equals() 方法
public boolean equals(Object anObject){}
示例:
package com.github.string.demo21;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class Test {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
System.out.println(s1.equals(s2)); // true
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s3.equals(s4)); // true
System.out.println(s1.equals(s4)); // true
}
}
1.7.3 equalsIgnoreCase() 方法
public boolean equalsIgnoreCase(String anotherString){}
示例:
package com.github.string.demo22;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class Test {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("HELLO");
System.out.println(s1.equalsIgnoreCase(s2)); // true
}
}
1.7.4 compareTo() 方法
public int compareTo(String anotherString){}
示例:
package com.github.string.demo23;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class Test {
public static void main(String[] args) {
String s1 = "i";
String s2 = "love";
System.out.println(s1.compareTo(s2)); // -3
}
}
1.7.5 compareToIgnoreCase() 方法
public int compareToIgnoreCase(String str){}
示例:
package com.github.string.demo24;
/**
* @author maxiaoke.com
* @version 1.0
*
*/
public class Test {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("Hello");
System.out.println(s1.compareToIgnoreCase(s2)); // 0
}
}