Reputation: 1
Hello what i am trying to do here is to recieve the password the User has entered then compare it with the correct password in a if statement.
public void actionPerformed(ActionEvent event)
{
String UsersStoredPassword = "hello";
String UsersEnteredPassword = new String(PasswordField.getPassword());
String Message = "The Password You Have Entered Is Correct";
String Message1 = "You Have Entered The Wrong Password";
if (event.getSource() == PasswordField)
{
if (UsersEnteredPassword == UsersStoredPassword)
{
JOptionPane.showMessageDialog(null, Message);
}
else
{
JOptionPane.showMessageDialog(null, Message1);
}
}
}
However event thought the user typed in the correct password: "hello" it still shows message1: "You Have Entered The Wrong Password. I have tried doing this:
public class TheHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String UsersStoredPassword = "hello";
String UsersEnteredPassword = new String(PasswordField.getPassword());
String Message = "The Password You Have Entered Is Correct";
String Message1 = "You Have Entered The Wrong Password";
if (event.getSource() == PasswordField)
{
JOptionPane.showMessageDialog(null, UsersEnteredPassword);
}
}
}
and it shows UsersEnteredPassword as typed inside.
Upvotes: 0
Views: 2172
Reputation: 159844
You're comparing 2 Strings
using the ==
operator which does not compare String
content but this is not the real issue:
You've created a security vulnerability here.
Explanation: JPassword.getText
was purposely deprecated to avoid using Strings
in favor of using a char[]
returned by getPassword
.
When calling getText
you get a String (immutable object) that may not be changed (except reflection) and so the password stays in the memory until garbage collected.
A char array however may be modified, so the password will really not stay in memory.
Use Array.equals
instead
if (Arrays.equals(usersEnteredPassword.toCharArray()),
passwordField.getPassword()) {
// password match!
}
Aside: Follow Java Naming conventions using a lowercase letter as a the initial letter for variable names as shown above. Read Naming Conventions
Upvotes: 4
Reputation: 12890
Strings shouldn't be compared with '=='
. You should always check equality using .equals(Object)
method for checking equality on any Objects. '==' is used to compare primitive datatype only, not Objects. '==' compares the equality of the physical memory address of the left and right operands. .equals(Object)
checks whether both left and right operands are meaningfully equivalent. Hope this helps
Upvotes: 1
Reputation: 9038
if(UsersEnteredPassword == UsersStoredPassword){
to
if(UsersEnteredPassword.equals(UsersStoredPassword)){
on Objects manipulation
==
means, pointing to the same address? or, its the exactly same object?
equals
compares the content.
Upvotes: 1