0

so I try to use a string variable in the if statement but it seems it doesn't work like int and double and other primitive data types, why? Pls help my code:

import java.util.Scanner;
public class Something{
   static void Some(){
      Scanner input = new Scanner(System.in);
      String answer;
      
      System.out.println("Hello Sir, what can I do for you?");
      answer = input.nextLine();
      
      String i = "2";
      
      if(answer == i){
         System.out.println("Sure Sir ");
      }
      
      else{
         System.out.println("Sir, anything?");
      }
   }


   public static void main(String [] args){
      Some();
   }
}

input:2 output: Sir, anything?

I_code
  • 1
  • 1

1 Answers1

0

The == operator compares references in case of strings. To compare values you can use equals() method.

if(a.equals(b)){}