In the above code, two strings are evaluated using the equivalency operator. Why
ID: 3717115 • Letter: I
Question
In the above code, two strings are evaluated using the equivalency operator. Why can this be a problem, and what other methods are offered by Java for working with characters and strings?
import java.util.Scanner; public class TryToCompareStrings public static void main(String[] args) String aName"Carmen"; String anotherName; Scanner input new Scanner(System.in) System.out.print("Enter your name>") anotherNmeinput.nextLineO: if(aNameanothen Name) System.out.println(aNameequals " + anotherName); else System.out.println (aName " does not equal "anotherName);Explanation / Answer
Hi,
equivalency operator compares references not values. Where as equals() compares original values of the string.
String class provides 2 methods
1) equals(Object second) - compare string to the specified object.
2) equalsIgnoreCase(String second) - compares String to second string, by ignoring case
I have written the below java program by using equals.
import java.util.Scanner;
public class CmTest {
public static void main(String[] args) {
String aName = "Carmen";
String anotherName;
Scanner input = new Scanner(System.in);
System.out.println("Enter your name >");
anotherName = input.nextLine();
if (aName.equals(anotherName)) {
System.out.println(aName + " Equals " + anotherName);
} else {
System.out.println(aName + " Not Equals " + anotherName);
}
}
}
Output:
Enter your name >
Carmen
Carmen Equals Carmen
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.