-3

Can anyone please explain, why the outputs are printing two different boolean values. why aren't strings being compared not equal in this case. while simply comparing two strings with '==' operator does compare the strings. For example, System.out.print("paper" == "paper") prints true. Thanks in advance. :)

package my_pack;

    import java.util.Objects;
    import java.util.Random;
    import java.util.Scanner;


    public class game {
        public static void main(String[] args) {
            //get the user input get_input()
            Scanner scn = new Scanner(System.in);
            System.out.println("Rock Paper or Scissor? Enter Your choice: ");
            String user_choice = scn.nextLine();
            user_choice = user_choice.toLowerCase();

            //get the random number
            Random rand = new Random();
            int random_num = rand.nextInt(3) + 1;

            //assign the number to specified method
            String comp_choice ="";
            switch (random_num){
                case 1:
                    comp_choice = "rock";
                    break;
                case 2:
                    comp_choice = "paper";
                    break;
                case 3:
                    comp_choice = "scissor";
                    break;
            }
            System.out.println(comp_choice);
            System.out.println(user_choice == comp_choice); //paper == paper (false)
            System.out.println(Objects.equals(user_choice, comp_choice)); //paper == paper (true)

        }

    }
Bigyan Karki
  • 303
  • 2
  • 10

1 Answers1

1

If you came from c++, it will be easier to think as compare by reference(==) and compare by value(equals) .


When you compare two Strings using ==, you are comparing two objects and their references, not their values. When you compare two string literals, such as "paper" == "paper", they are pointing to the same block of memory, therefore the line returns true.

Instead of ==, using yourString.equals(stringToCompare) or .equalsIgnoreCase to ignore differences in capitalization.

  System.out.println("RANDOM CHOICE: " + comp_choice); //display user and comp choice
  System.out.println("USER CHOICE: " + user_choice); 
  System.out.println("USER = COMP? " + user_choice.equalsIgnoreCase(comp_choice));  //compare both choices
codemonkey
  • 58
  • 1
  • 8
Alexander.Furer
  • 1,817
  • 1
  • 16
  • 24
  • I quite did not get what you meant by compare by reference and compare by value. Can you provide me some references? – Bigyan Karki Nov 07 '17 at 04:40