Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

If you run the following program and enter the character “a” at the first prompt

ID: 3596406 • Letter: I

Question

If you run the following program and enter the character “a” at the first prompt and the character “b” at the second prompt the message “a not = b” will appear. However if you run it again and enter the character “a” at both prompts, it will also print the message “a not = a”. Explain why in detail and explain how to re-code to correct it.

public class BadStringCompare public static void main(Stringl] args) Scanner keyboard- new Scanner(System.in); System.out.println("Enter first letter..."); String string1- keyboard.nextLine(); System.out.println("Enter second letter..."); String string2 keyboard.nextLine); if (string1 string2) System.out.println (string1-"string2); else System.out.println (string1 " notstring2);

Explanation / Answer

Explanation:

== operator is a reference comparison, i.e. both objects point to the same memory location
.equals() method evaluates to the comparison of values in the objects

BadStringCompare.java

import java.util.Scanner;

public class BadStringCompare {

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

System.out.println("Enter first letter: ");

String string1 = keyboard.nextLine();

System.out.println("Enter second letter: ");

String string2 = keyboard.nextLine();

if(string1.equals(string2)) {

System.out.println(string1+" = "+string2);

} else {

System.out.println(string1+" not = "+string2);

}

}

}

Output:

Enter first letter:
a
Enter second letter:
a
a = a

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote