String Comparison in Java

In Java, there are two ways to compare strings: using the “==” operator and using the “equals()” method.

  1. Using the “==” operator: The “==” operator compares the memory address of two objects. When comparing two strings using the “==” operator, you are checking if both strings are located in the same memory location. Here’s an example:
javascript
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");

if (str1 == str2) {
System.out.println("str1 and str2 are the same object");
}

if (str1 == str3) {
System.out.println("str1 and str3 are the same object");
}

In this example, str1 and str2 are both pointing to the same memory location, while str3 is pointing to a different location. So, the first if statement will print “str1 and str2 are the same object”, while the second if statement will not print anything.

  1. Using the “equals()” method: The “equals()” method compares the content of two objects. When comparing two strings using the “equals()” method, you are checking if both strings have the same sequence of characters. Here’s an example:
vbnet
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");

if (str1.equals(str2)) {
System.out.println("str1 and str2 have the same content");
}

if (str1.equals(str3)) {
System.out.println("str1 and str3 have the same content");
}

In this example, all three strings have the same content, so both if statements will print “str1 and str2 have the same content” and “str1 and str3 have the same content”.

Note that when comparing strings, it’s generally recommended to use the “equals()” method instead of the “==” operator, since the “==” operator may give unexpected results due to the way Java handles string literals.