1. "Hello, World!"
  2. Variables and Types
  3. Arrays
  4. While, If, For
  5. ...Problem Set 0
  6. Static Methods
  7. Static Fields
  8. String Conversion
  9. Objects
  10. Threading
  11. Strings
  12. ...Problem Set 1.5
  13. Packages
  14. Complex Numbers
  15. Abstract classes
  16. Interfaces
  17. Autoboxing
  18. ...Problem Set 1
  19. enum
  20. Inner Classes
  21. Polymorphism
  22. Tanks!
  23. Callbacks
  24. Exceptions
  25. File I/O
  26. ...Problem Set 2
  27. Regular Expressions

While, If, For

What would be nice is if we could somehow list all the arguments on the command line without having to see those errors.

While.java
1public class While {
2    public static void main(String[] args) {
3        int i = 0;
4        while(i < args.length) {
5            System.out.println(i+"] "+args[i]);
6            i++; // increment by one
7        }
8    }
9}
$ javac While.java
$ java While a
0] a
$ java While a b
0] a
1] b
$ java While a b see
0] a
1] b
2] see

The while command executes everything in between the { }'s until it's condition is true. In this case, as long as the variable "i" is less than the length of args. Each iteration of the loop i is incremented by 1. If you comment out line 6 you'll find that the loop will execute forever.

There are two variations on the ++ operator: the prefix and the suffix. This short example shows how that works:

PlusPlus.java
1public class PlusPlus {
2    public static void main(String[] args) {
3        int a = 1b = 1;
4        System.out.println("a++="+(a++));
5        System.out.println("++b="+(++b));
6        System.out.println("a="+a+", b="+b);
7    }
8}
$ javac PlusPlus.java
$ java PlusPlus
a++=1
++b=2
a=2, b=2

The suffix version increments a, but it evaluates to what a was before the increment. The prefix also increments, but it evaluates to what the variable is after the increment.

There are a number of operations that you can use for comparison inside the parenthesis of a while loop.

operatormeaning
a < btrue if a is less than b
a <= btrue if a is less than or equal to b
a > btrue if a is greater than b
a >= btrue if a is greater than or equal to b
a == btrue if a is equal to b
a != btrue if a is not equal to b
!can be used to mean "not", thus !(a < b) is the same as a >= b

But there is more than one flavor of loop....

For.java
1public class For {
2    public static void main(String[] args) {
3        for(int i=0;i<args.length;i++) {
4            System.out.println(i+"] "+args[i]);
5        }
6    }
7}
$ javac For.java
$ java For a
0] a
$ java For a b
0] a
1] b
$ java For a b see
0] a
1] b
2] see

As you can see, the more concise (and more usual) way of writing this code is with a for loop. Really, the for and while loops written here do exactly the same thing and there is no real reason why you have to use one or the other except taste.

The easiest way that I know of to explain what a for loop does is to say that it does the same thing as the while loop above.

DoWhile.java
1public class DoWhile {
2    public static void main(String[] args) {
3        int i=0;
4        do {
5            System.out.println(i+"] "+args[i]);
6            i++;
7        } while(i<args.length);
8    }
9}
$ javac DoWhile.java
$ java DoWhile
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
	at DoWhile.main(DoWhile.java:5)
$ java DoWhile a b c
0] a
1] b
2] c

The do { } while(); loop is similar to the regular while loop, except it tests for termination only after it's processed the body. This means that the body of the loop will always execute at least once.

Loops allow us to print out each element of args individually, but what if we want to print a special message when no arguments are supplied?

If.java
1public class If {
2    public static void main(String[] args) {
3        if(args.length == 0) {
4            System.out.println(">>No arguments given<<");
5        }
6        for(int i=0;i<args.length;i++) {
7            System.out.println(i+"] "+args[i]);
8        }
9    }
10}
$ javac If.java
$ java If
>>No arguments given<<
$ java If b
0] b
$ java If b see
0] b
1] see

Here we have introduced the if statement. It works like the while loop, but it only ever runs a single time.

If2.java
1public class If2 {
2    public static void main(String[] args) {
3        if(args.length == 0) 
4            System.out.println(">>No arguments given<<");
5        for(int i=0;i<args.length;i++) 
6            System.out.println(i+"] "+args[i]);
7    }
8}
$ javac If2.java
$ java If2
>>No arguments given<<
$ java If2 b
0] b
$ java If2 b see
0] b
1] see

If there is only a single statement (one semi-colon) in the loop or if block, then the {}'s are not necessary. Things look a little more concise this way.

If3.java
1public class If3 {
2    public static void main(String[] args) {
3        if(args.length == 0) 
4            System.out.println(">>No arguments given<<");
5        else
6            System.out.println("Number of args = "+args.length);
7        for(int i=0;i<args.length;i++) 
8            System.out.println(i+"] "+args[i]);
9    }
10}
$ javac If3.java
$ java If3
>>No arguments given<<
$ java If3 b
Number of args = 1
0] b
$ java If3 b see
Number of args = 2
0] b
1] see

This demonstrates the "else." It executes if the if fails.

IfElse.java
1public class IfElse {
2    public static void main(String[] args) {
3        if(args.length == 0) {
4            System.out.println("No args given.");
5        } else if(args.length == 1) {
6            System.out.println("One arg given.");
7        } else if(args.length == 2) {
8            System.out.println("Two args given.");
9        } else {
10            System.out.println("Many args given.");
11        }
12    }
13}
$ javac IfElse.java
$ java IfElse
No args given.
$ java IfElse a
One arg given.
$ java IfElse a b
Two args given.
$ java IfElse a b c
Many args given.

It is common to chain if / else's together.

ContBreak.java
1public class ContBreak {
2    public static void main(String[] args) {
3        for(int i=0;i<10;i++) {
4            if(i == 4)
5                continue;
6            System.out.println("i="+i);
7            if(i == 7)
8                break;
9        }
10    }
11}
$ javac ContBreak.java
$ java ContBreak
i=0
i=1
i=2
i=3
i=5
i=6
i=7

The keyword "continue" means to skip over the remainder of the current loop body and begin the next iteration.

Keyword "break" means to exit the loop altogether.

ContWhile.java
1public class ContWhile {
2    public static void main(String[] args) {
3        int i = 0;
4        while(i<10) {
5            if(i == 4)
6                continue;
7            System.out.println("i="+i);
8            if(i == 7)
9                break;
10            i++;
11        }
12    }
13}
$ javac ContWhile.java

This code would run forever if we tried to execute it. Can you see why?

ArrayInit.java
1public class ArrayInit {
2    public static void main(String[] args) {
3        int[] numbers = new int[6];
4        numbers[0] = 1;
5        numbers[1] = 3;
6        numbers[2] = 8;
7        numbers[3] = 2;
8        numbers[4] = 9;
9        numbers[5] = 3;
10        for(int i=0;i<numbers.length;i++)
11            System.out.println(i+"] "+numbers[i]);
12    }
13}
$ javac ArrayInit.java
$ java ArrayInit
0] 1
1] 3
2] 8
3] 2
4] 9
5] 3

The above code shows a way to create and initialize an array. It is somewhat awkward and verbose. Fortunately, there's a nice shorthand that allows us to do this much more simply:

ArrayInit2.java
1public class ArrayInit2 {
2    public static void main(String[] args) {
3        int[] numbers = new int[]{1,3,8,2,9,3};
4        for(int i=0;i<numbers.length;i++)
5            System.out.println(i+"] "+numbers[i]);
6    }
7}
$ javac ArrayInit2.java
$ java ArrayInit2
0] 1
1] 3
2] 8
3] 2
4] 9
5] 3