3

Possible Duplicate:
Java String.equals versus ==

I'm trying to make a simple user/password system in Java. My code is:

Scanner sc  =  new Scanner (System.in); 
System.out.println("Enter Username :");
String username = sc.nextLine(); 
System.out.println("Enter Password :");
String password = sc.nextLine(); 
if (username == "a" && password == "b"){
System.out.print("ok");
}

Or

if (username == 'a' && password == 'b') 

I want to make a simple login with user a and pass b but it doesn't work.

Community
  • 1
  • 1
user1808537
  • 19
  • 1
  • 1
  • 6

2 Answers2

4

To mask the password, prefer java.io.Console.readPassword() class to Scanner :

String username = null;
String password = null;
Console console = System.console();

System.out.print( "Username: " );
username = console.readLine();

System.out.print( "Password: " );
password = new String( console.readPassword());

System.out.println( "Username = " + username );
System.out.println( "Password = " + password );
if (username.equals( "a" ) && password.equals( "b" )) {
   System.out.print( "ok" );
}

Another advice to enforce security: the password variable should be locale to be garbaged.

console.readPassword() returns an array of char, you may compare char by char without allocating a String, it's more secure even if it's more code to write (it's because the sample code I provided use a String).

Aubin
  • 14,617
  • 9
  • 61
  • 84
1

always check for string equality using equals() method

  if (username == "a" && password == "b"){

should be

if (username.equals("a") && password.equals("b")){

use == operator to check if two primitives have the same value and two object references point to the same reference.

use .equals() method to check if two objects are meaningfully equal

PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • are you really so greedy for rep that you constantly submit incomplete and sub-par answers and then slowly try to add content to them via edits? congratulations, you've answered his question, but he does not understand why one must use .equals() instead of ==. – Alex Lynch Nov 08 '12 at 11:41
  • @AlexLynch greedy of what 100 billion $'s?? .. lol – PermGenError Nov 08 '12 at 11:42