Search Java Programs

Thursday, January 7, 2010

Conditionals and Loops

Conditionals perform the core logic switching of your application. Java uses the standard and, or operator syntax for comparison, and (&&) ... or (||) Operators along with equals (==) and not equals (!=). Unlike some languages you cannot compare strings with == or != except to check nullness. To check if 2 strings are equal check stringOne.equals("String to match").

if ... else

The if ... else statement is the base of the conditional.
Create a new file IfElseEx1.java

class IfElseEx1 {
public static void main(String[] args) {
if (args[1].contains(args[0])) {
System.out.println(args[0] + " is contained in " + args[1]);
} else {
System.out.println(args[0] + " is not contained in " + args[1]);
}
}
}
The if ... else example checks if the first argument passed is contained in the second argument passed.
Create a new file IfElseEx2.java
class IfElseEx2 {
public static void main(String[] args) {
String s = "this is a string";
if (s == null) {
System.out.println("String is null");
} else if (s.equals("will this match?")) {
System.out.println("I guess it did");
} else if (s.equals("this is a string")) {
System.out.println("this is a string matched");
} else {
System.out.println("no match");
}
}
}


This example demonstrates how to find if two strings match. Strings also have a method equalsIgnoreCase that is a non case sensitive match. Also demonstrated is the if else syntax that allows an if statement to have multiple conditions to attempt to match.

switch ... case

The switch statement is a conditional similar to if, but if used to check one variable for a series of conditions. The switch checks the variable against each case. A case is terminated by a break statement. If a break statement is missing the code will fall through and execute the next case until a break statement is reached. The default case is executed if no other case checks match
Create the file SwitchCaseEx.java

class SwitchCaseEx {
public static void main(String[] args) {
switch(args.length) {
case 1:
System.out.println("One command line argument");
break;
case 2:
System.out.println("Two command line arguments");
break;
case 3:
System.out.println("Three command line arguments");
break;
case 4:
System.out.println("Four command line arguments");
break;
case 5:
System.out.println("Five command line arguments");
break;
default:
System.out.println("0 or more than 5 command line arguments");
break;
}
}
}

This isn't the most creative way to show a switch statement but it clearly displays the syntax. In instances where a switch can replace an if/else block it probably should as this is much cleaner, easier to read code. Switch statements in Java can only be applied to integer style types (byte, short, int), char, and enumerated types (not covered in this tutorial). If there are no command line arguments passed or more than 5 command line arguments the default case is called, otherwise the proper case statement is executed.

Loops

Loops are used to conditionally repeat blocks of code. Java implements the common while, for, and foreach loops along with a do ... while loop.

While

Repeat the block of code while the condition is true.
Create the file WhileEx.java

class WhileEx {
public static void main(String[] args) {
int i = 0;
int j;
while (i <= 5) {
j = i * 5;
System.out.println(i + " * 5 = " + j);
i++;
}
}
}

This loop will iterate 6 times. When executing a while statement like this it is important to remember to increment the conditional variable.

do ... while

A while loop with the iterate conditional at the end of the loop block. Do while loops will always iterate once since the check is after the code block.
Create the file DoWhileEx.java

class DoWhileEx {
public static void main(String[] args) {
int i = 0;
int j;
do {
j = i * 5;
System.out.println(i + " * 5 = " + j);
i++;
} while (i <= 5);

}
}

This code performs exactly as with the While loop example. The only difference is that the conditional is checked after the code block is executed.

For

For loops are used to iterate through a loop a number of times. The iteration conditional in a for loop has 3 parts, the counter initialization, the conditional to check, the increment syntax. The increment syntax is executed each time through the loop.
Create the file ForEx.java

class ForEx {
public static void main(String[] args) {
int j;
for (int i=0; i < 10; i++) {
j = i * i;
System.out.println(i + " squared is: " + j);
}
}
}

This simple for loop squares the counter variable. Notice that even though the increment is listed at the top of the code it isn't executed until after the first iteration.

Foreach

Foreach loops are used to iterate through a list of values. In Java a foreach loop uses the for statement with different syntax to declare how to iterate.
Create the file ForeachEx.java
class ForeachEx {
public static void main(String[] args) {
String[] sArray = {"This", "is", "an", "array", "of", "strings" };
for (String s : sArray) {
System.out.println(s);
}
}
}


Loop through the array of strings displaying each to the screen.

No comments:

Post a Comment

Website Design by Mayuri Multimedia