There is something wrong in this program(output).Always showing 'invalid user' output. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

There is something wrong in this program(output).Always showing 'invalid user' output.

import java.util.Scanner; public class validuser { public static void main(String[] args){ System.out.println("Enter your name"); Scanner sc = new Scanner(System.in); String st = sc.nextLine(); String name = "KIRAN"; if(st == name){ System.out.println("Welcome"); } else{ System.out.println("Invalid user"); } } }

21st Jul 2016, 7:20 AM
KIRAN JOHNSON
KIRAN JOHNSON - avatar
4 Answers
+ 5
You're putting ==. == compares objects. Even if the strings are the same, theyre different string objects. do if(st.equals(name))
21st Jul 2016, 7:58 AM
James
James - avatar
+ 2
hi, James. i thought the equals sign was exclusively for assigning values to variables.
21st Jul 2016, 8:06 AM
Emmanuel Nankpah Dangata
Emmanuel Nankpah Dangata - avatar
+ 2
one = does. so x = 5 assigns 5 to x. == compares two objects and returns true if they are equal.
21st Jul 2016, 8:12 AM
James
James - avatar
+ 2
This == sign you can used it with nubmbers int double..etc but string you should use ''example''.equals(''example'');
21st Jul 2016, 9:01 AM
Mostafa Abobakr
Mostafa Abobakr - avatar