public static void main(String[] args) {
String str1 = null;
String str2 = "test";
System.out.println(str1.equals(str2));//Run 1
System.out.println(str2.equals(str1));//Execution 2
}
Execution 1 throws a java.lang.NullPointerException. The cause of the exception is that I put null in str1 and called the method from the null object. Calling a method from a non-null str2 will no longer raise an exception and will return false.
Writing execution 2 has the advantage that an exception does not occur even if str1 is null, but it has the disadvantage that it is difficult to notice code mistakes if it is implemented without assuming that null will be entered as an abnormal system. I think.
If you are aware of null checking, it may be safer to catch it with exception handling.
public static void main(String[] args) {
String str1 = null;
String str2 = "test2";
try {
System.out.println(str1.equals(str2));
}catch(NullPointerException ex) {
System.out.println("Exception catch");
}
}
public static void main(String[] args) {
String str1 = "test1";
String str2 = "test1";
System.out.println(str1.equals(str2));//Result 1
System.out.println(str1 == str2); //Result 2
}
Result 1 is of course true, but what about result 2? In conclusion, result 2 is also true.
This is because there is a mechanism called a constant pool. Character literals appear frequently in programs. However, if you create an instance of String each time, it will consume a lot of memory.
If the same string literal reappears, the reference to the string instance in the memory space for the constant will be "reused". This is a mechanism called a constant pool.
This constant pool is only valid when using string literals. If you explicitly write to create a new instance using the new operator, an instance will be created each time, and each variable will have a different reference.
public static void main(String[] args) {
String str1 = new String("test");
String str2 = "test";
System.out.println(str1.equals(str2));//true
System.out.println(str1 == str2); //false
}
You won't see it in an actual program, but be careful because it's a common trigger in Java Silver.
You can use the equalsIgnoreCase method to determine equivalence in a case-insensitive manner. However, I think that the frequency of appearance is considerably lower than that of equals.
public static void main(String[] args) {
String str1 = "abc";
String str2 = "ABC";
System.out.println(str1.equals(str2)); //false
System.out.println(str1.equalsIgnoreCase(str2));//true
}
that's all
Recommended Posts