[Solved] Java if statements without brackets creates unexpected behaviour


Because this:

if(name.equals("email_stub"))
    if(emailStub == "")
        emailStub = results.getString("text");
else if(name.equals("fax"))
    if(fax == "")
        fax = results.getString("text");

Is actually this:

if(name.equals("email_stub"))
    if(emailStub == "")
        emailStub = results.getString("text");
    else if(name.equals("fax"))
        if(fax == "")
            fax = results.getString("text");

Without the curly brackets, the else will reference the first if before it.


And as @Hovercraft commented:

Avoid if(emailStub == "") and instead do if (emailStub.isEmpty())
or if ("".equals(emailStub)) since you should never compare Strings
with == or !=. Also consider use of trim() here, such as if (emailStub.trim().isEmpty()).

See How do I compare strings in Java?.

3

solved Java if statements without brackets creates unexpected behaviour