Java For Dummies, 8th Edition
Book image
Explore Book Buy On Amazon
You can use nested if statements in Java. 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. You can do the same thing with Java’s if statements. (Talk about fun!)

Check out this code with nested if statements.

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");





Check out several runs of the code below. The main idea is that to log on, you have to pass two tests. (In other words, two conditions must be true.) The first condition tests for a valid username; the second condition tests for the correct password. If you pass the first test (the username test), you march right into another if statement that performs a second test (the password test).

nested if statements
Three runs of the code.

If you fail the first test, you never make it to the second test. Here’s the overall plan.

nested statements
Don’t try eating with this fork.

The code 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. Fourth … well, one could go on and on. The code just isn’t meant to illustrate good username/password practices.

Modify the program so that, if the user clicks Cancel for either the username or the password, the program replies with a Not enough information message.

About This Article

This article is from the book:

About the book author:

Barry Burd, PhD, is a veteran author and educator. At the University of Illinois, he was named five times to the university-wide List of Teachers Ranked as Excellent by their Students. He has written several books on Java and Android development.

This article can be found in the category: