0

Can someone explain why the below JAVA multi condition code don't provide the correct Output.

Even if i provide a input Which satisfies the condition it still give a false result. for eg: Input : US 25 Output : Not sure ( It should perform the if condition which it is not doing. I want to know why its not working. for the same program if i use "equals" it is working. but not sure what is Wrong while using the == Operator. import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String country = sc.nextLine(); int age = sc.nextInt(); if ((country=="US"||country=="GB")&&(age>=18 && age<=100)) { System.out.println("Country: "+ country ); System.out.println("Age :"+ age); }else{ System.out.println("Not sure!!"); } } } Working Code : import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String country = sc.nextLine(); int age = sc.nextInt(); if ((country.equals("US")||country.equals("GB"))&&(age>=18 && age<=100)) { System.out.println("Country: "+ country ); System.out.println("Age :"+ age); }else{ System.out.println("Not sure!!"); } } }

29th Jun 2023, 2:28 PM
Abhishek N
Abhishek N - avatar
3 odpowiedzi
+ 4
https://code.sololearn.com/cZms6c3vg2w3/?ref=app
29th Jun 2023, 3:02 PM
A͢J
A͢J - avatar
0
This is because == is operator which match the address reference of object and equals is method which matches the string.. hope this will be helpful..
1st Jul 2023, 10:50 AM
S S
S S - avatar