Java Language Basics

Java 101: Loop, switch, or take a break? Deciding and iterating with Java statements

Learn how to use standby statements like for, while, if-else, and break, then get started with the new switch expressions in Java 12

1 2 3 Page 3
Page 3 of 3
outer:
for (int i = -2; i <= 2; i++)
   for (int j = -2; j <= 2; j++)
      if (i == 0)
         continue outer;
      else
      if (j == 0)
         continue;
      else
         System.out.println(10 / i * j);

This example presents a pair of nested for loops, with each loop variable ranging from -2 through 2. The idea is to divide 10 by the product of the loop variable values. However, division by zero will occur when either variable contains 0.

To prevent division by zero, a chained if-else statement is used to test i's and j's values for 0. If i's value is 0, continue outer; is used to terminate the inner loop and advance the outer loop (with label outer:) past 0. If j's value is 0, continue; is used to quit the current inner loop iteration and advance the inner loop past 0. If neither situation arises, the calculation is performed and its result is output.

Empty statements

There is one final statement to consider, which is the empty statement, a statement consisting solely of the semicolon character. This statement accomplishes nothing, and yet it is useful. Consider the following example:

for (int ch; (ch = System.in.read()) != -1; System.out.print((char) ch));

This example copies the contents of the standard input stream, read via calls to System.in.read(), to the standard output stream, written via calls to System.out.print(), a companion to System.out.println() that doesn't output a line separator. It works best when the standard input stream is redirected from the keyboard to a text file.

When redirected to a file, System.in.read() returns -1 when there is no more input. When not redirected, System.in.read() obtains its input from the keyboard and never returns -1. Instead, when there are no more key codes to return, System.in.read() returns a line separator character -- two calls are needed on Windows to return its \r\n characters, one call is needed on Unix\Linux to return its \n character, and one call is needed on older versions of Mac OS to return its \r character. For more information, check out Newline.

As you can see, all of the work is performed in the for statement's initialize and test sections. The final semicolon refers to the empty statement, which is executed repeatedly.

Be careful with the empty statement because it can be the source of hard-to-find bugs. For example, you might expect the following for statement to output 10 instances of the word Hello:

for (int i = 0; i < 10; i++);
   System.out.println("Hello");

Instead, you will only observe a single instance of this word, because of the empty statement after the for statement's closing parenthesis. for executes the empty statement 10 times, after which the method call is executed once.

Example application: Exploring statements

Now that you've learned about Java's fundamental language features, you have everything you need start writing interesting Java applications. As an example, I've written a game that randomly selects an integer ranging from 0 through 9 and asks you to guess the number. If you guess too high or too low, the game will tell you. It will also tell you when you guess correctly, and it will ask you if you want to play again.

Before I show you the application's source code, I need to introduce several classes and methods you'll see in the code:

  • I use System.in.read() to return either the code of a pressed key (when standard input is not redirected) or an 8-bit value from a file (when standard input is redirected). System.in.read() is capable of throwing an exception, so I had to append "throws Exception" to the main() method header, as in public static void main(String[] args) throws Exception. This prevents the compiler from reporting an error.
  • To obtain a random integer, I need to invoke the random() method member of the standard class library's Math class. random() returns a floating-point value ranging from 0.0 to almost 1.0. An expression converts this number to a more useful integer.

Listing 1 presents the source code for the Guess application.

Listing 1. Example application for guessing in Java (Guess.java)

class Guess
{
   public static void main(String[] args) throws Exception
   {
      outer:
      while (true)
      {
         System.out.println("I'm thinking of a number between 0 and 9.");
         int number = (int) (Math.random() * 10);
         while (true)
         {
            int guessNumber;
            while (true)
            {
               System.out.println("Enter your guess number between 0 and 9.");
               guessNumber = System.in.read();
               while (System.in.read() != '\n');
               if (guessNumber >= '0' && guessNumber <= '9')
               {
                  guessNumber -= '0';
                  break;
               }
            }
            if (guessNumber < number)
               System.out.println("Your guess is too low.");
            else
            if (guessNumber > number)
               System.out.println("Your guess is too high.");
            else
            {
               System.out.println("Congratulations! You guessed correctly.");
               while (true)
               {
                  System.out.println("Press n for new game or q to quit.");
                  int ch = System.in.read();
                  while (System.in.read() != '\n');
                  if (ch == 'n')
                     continue outer;
                  if (ch == 'q')
                     break outer;
               }
            }
         }
      }
   }
}

Guess demonstrates many of the fundamental Java language features presented in the previous four tutorials. The main() method presents a while statement that generates a new number and gives you a chance to guess it. The expression (int) (Math.random() * 10) multiplies random()'s return value by 10 to change the range to 0.0 to almost 10.0, and converts the result to an integer ranging from 0 through 9.

After generating the number, main() executes an inner while statement to handle the guesswork. It repeatedly prompts for a guess, converts the pressed key's Unicode character value to a binary integer value from 0 through 9, and determines whether the user has guessed correctly or not. A suitable message is output. Users who guess correctly are given the chance to play a new game by pressing n, or to quit the application by pressing q.

An interesting part of the source code is while (System.in.read() != '\n');. I use this statement to flush the line separator character(s) (e.g., \r\n on Windows) from the operating system's keyboard buffer. Without this, you would see multiple prompts because each separator character will be interpreted as an attempt to enter a value from 0 through 9 (or n or q). If you're running Java on an older version of Mac OS, you'll probably have to replace \n with \r, which is the Mac's line separator. No changes are necessary when running on Linux or Unix, whose line separator is \n.

Compile Listing 1 as follows:

javac Guess.java

Then run the application:

java Guess

Below is the output from a sample run:

I'm thinking of a number between 0 and 9.
Enter your guess number between 0 and 9.
5
Your guess is too high.
Enter your guess number between 0 and 9.
2
Your guess is too low.
Enter your guess number between 0 and 9.
3
Your guess is too low.
Enter your guess number between 0 and 9.
4
Congratulations! You guessed correctly.
Press n for new game or q to quit.
q

Note that you could make this code portable by working with the standard class library's System class, which offers access to the line.separator property. This task could be good for a future exercise, when you're more comfortable with Java's classes and methods.

Using the Java Shell editor

You might want to create or edit this application using the jshell utility. You'll find the /edit command helpful for this purpose. When you enter /edit, jshell displays an edit window with Cancel, Accept, and Edit buttons:

  • Cancel: Cancel the editor without saving changes.
  • Accept: Save changes without leaving the editor. Java Shell displays a modification message at the prompt when changes are saved.
  • Exit: Save changes and leave the editor. Java shell displays a modification message at the prompt when changes are saved.

Copy Listing 1 into and exit the editor. Then enter Guess.main(null) at the jshell> prompt to run the application. When you finish with the application, enter q and you'll be returned to the jshell> prompt.

Conclusion

Over the past four tutorials, you've learned all about Java's fundamental language features, including expressions, operators, and statements, which are the workhorses of a Java application. Mastering these basic language features gives you a solid foundation for exploring more advanced language features. We'll begin this expansion in the next Java 101 tutorial, which introduces Java classes and objects.

1 2 3 Page 3
Page 3 of 3