Build Nesting Code in Java - dummies

By Barry Burd

You can write nesting code with Java’s if statements. Have you seen those cute Russian Matryoshka nesting dolls? Open one, and another one is inside. Open the second, and a third one is inside it. It’s kind of like that. (Talk about fun!) This listing shows you how.


import static java.lang.System.out;
import java.util.Scanner;
public class Authenticator2 {
    public static void main(String args[]) {
        Scanner keyboard = new Scanner(;
        out.print("Username: ");
        String username =;
        if (username.equals("bburd")) {
            out.print("Password: ");
            String password =;
            if (password.equals("swordfish")) {
                out.println("You're in.");
            } else {
                out.println("Incorrect password");
        } else {
            out.println("Unknown user");

If you pass the first test (the username test), you march right into another if statement that performs a second test (the password test). If you fail the first test, you never make it to the second test. This figure shows the overall plan.


The code in the listing does a good job with nested if statements, but it does a terrible job with real-world user authentication. First, never show a password in plain view (without asterisks to masquerade the password). Second, don’t handle passwords without encrypting them. Third, don’t tell the malicious user which of the two words (the username or the password) was entered incorrectly.