0

I have this code snipped which I use for input validation:

public void validaUserID(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException {

        int findAccount = 0;

        if (ds == null) {
            throw new SQLException("Can't get data source");
        }
        // Initialize a connection to Oracle
        Connection conn = ds.getConnection();

        if (conn == null) {
            throw new SQLException("Can't get database connection");
        }

        // Convert Object into String
        int findValue = Integer.parseInt(value.toString()); 

        // With SQL statement get all settings and values
        PreparedStatement ps = conn.prepareStatement("SELECT * from USERS where USERID = ?");
        ps.setInt(1, findValue);
        try {
            //get data from database        
            ResultSet result = ps.executeQuery();
            while (result.next()) {
                // Put the the data from Oracle into Hash Map
                findAccount = result.getInt("USERID");
            }
        } finally {
            ps.close();
            conn.close();
        }

        // Compare the value from the user input and the Oracle data
        if (value.equals(findAccount)) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    value + " Session ID is already in use!", null));
        }
    }

For some reason the input data is not compared properly with the value in Oracle. What is the proper way to compare the two values?

user1285928
  • 1,328
  • 29
  • 98
  • 147

3 Answers3

6

It looks like you're comparing boxed integers. I'd unwrap them (i.e. get them in primitive form) and do == instead of .equals.

user1329572
  • 6,176
  • 5
  • 29
  • 39
1

Objects are compared using .equals(), and String is an object too, so they also have to be compared using .equals().

eg:

Assume s1 and s2 as String.

s1.equals(s2);

Primitive variables are compared using ==, as Wrapper are Objects, you need to compare them with .equals(), but if you want to compare them using ==, then you must first convert them into its Primitive form.

eg:

Integer a = 5;

int i = new Integer(a);

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
1

Well. Answer lies in your code itself.

 if (value.equals(findAccount)) 

you can write it instead this way

  if (findValue == findAccount)) 

as you have already unwrapped your Object Value to primitive findValue .

To be more clear, equals() is called on and passed to only objects. You can't compare objects with primitives or vice-versa.

Ahmad
  • 2,110
  • 5
  • 26
  • 36