简体   繁体   中英

Boolean st=false; and st also return value

i am going to asking stupid question. can i store value in boolean reference variable like st=rs.next and boolean can return the string value??

public class Valid {
    Public static boolean checkuser(String email, String pass) {
        Boolean st = false; // (why did it user here and what's means)
        try {
            Class.forName("com.mysql.jdbc.driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tst", "root", "mysql"); //Connection established
            PreparedStatement ps = con.prepareStatement("Select * from login where user=? and pass=?");
            ps.setSting(1, eamil);
            ps.setString(2, pass);
            Resultset rs = ps.executeQuery();
            st = rs.next(); //(please brief explain about this line)
        } catch (Exception e) {
            e.printStackTrace();
        }
        return st; //( about this line)
    }
}

i just didn't understand this code specially boolean behavior

boolean can return the string value??

st is a Boolean variable, which returns a Boolean value, not a String. Therefore you can assign to it the boolean value returned by rs.next() .

rs.next() returns true if the executed query returned at least one row. Therefore your method is checking whether a record exists in the login table having the passed email in the user column and the passed password in the pass column.

st is initialized to false , which means your method will return false if any Exception is thrown by the try block.

BTW, I'd change the type of st from Boolean to boolean . There's no point in using the Boolean wrapper type here, since your method can never return null.

Boolean st = false;

This declares a new Boolean variable and assigns it the value false , otherwise it would be null .

st = rs.next();

Here the boolean variable set the return value of next()

return st;

Now two things could have happened: Either the query succeeded and the return value is true if there was a least one row. if the query did not succeed, the return value will be false . AND there is the possibility that an exception is thrown. Then the original value of the Boolean (first line in the method) false is used.

So the method returns true only if there was at least one row. If no row exists or an error occurs, it returns false.

But since the Boolean value is never set to null, the coder could have used boolean instead without problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM