Java中的字符.equals() 方法及示例
Java.lang。 字符 .equals()是Java中的一个函数,用于将此对象与指定对象进行比较。如果参数不为 null,则结果为 true,并且是一个字符对象,表示与该对象相同的 char 值。
句法:
public boolean equals(Object obj)
参数:该函数接受一个参数obj ,它指定要与之比较的对象。
返回值:函数返回一个布尔值。如果对象相同,则返回 true,否则返回 false。
下面的程序说明了上述方法:
方案一:
// Java program to demonstrate the function
// Character.equals() when two objects are same
import java.lang.*;
public class gfg {
public static void main(String[] args)
{
// assign values to c1, c2
Character c1 = new Character('Z');
Character c2 = new Character('Z');
// assign the result of equals method on c1, c2 to res
boolean res = c1.equals(c2);
// print res value
System.out.println(c1 + " and " + c2 + " are equal is " + res);
}
}
输出:
Z and Z are equal is true
方案二:
// Java program to demonstrate function
// when two objects are different
import java.lang.*;
public class gfg {
public static void main(String[] args)
{
// assign values to c1, c2
Character c1 = new Character('a');
Character c2 = new Character('A');
// assign the result of equals
// method on c1, c2 to res
boolean res = c1.equals(c2);
// prints the res value
System.out.println(c1 + " and " + c2 + " are equal is " + res);
}
}
输出:
a and A are equal is false
参考:https: Java/lang/ 字符.html#equals(Java.lang.Object)