Blakes 21 Days Chapter 4 Document
- Internal Links
- Chapter 4 pages 095 to 123 | 123 - 95 = 28 pages | reserve
Day 4, Lists, Logic and Loops
- Top
- 095 Today, you learn about three of the most boring features in the Java language:
- How to organize groups of the same class or data type into lists called arrays
- How to make a program decide whether to do something based on logic
- How to make part of a Java program repeat itself by using loops
- You commonly use all three techniques
- software excels at performing repetitive tasks repeatedly
Arrays
- Top
- 096 At this point, you have dealt with only a few variables in each Java program.
- In some cases, it's manageable to use individual variables to store information, but what if you had 20 items of related information to track ?
- These objects, which also are called instances, are self-contained elements of a program with related features and data.
- You could create 20 different variables and set up their initial value, but that approach becomes progressively more cumbersome as you deal with larger amounts of information.
- What if there were 100 items, or even 1,000 ?
- 096 Arrays are a way to store a list of items that have the same primitive data type, the same class, or a common parent class.
- Each item on the list goes into its own numbered slot so that you can easily access the information.
- 096 Arrays can contain any type of information that is stored in a variable, but after the array is created, you can use it for that information type only.
- For example, you can have an array of integers, an array of String objects, or an array of arrays, but you can't have an array that contains both String objects and the primitive type integers.
- 096 There is one way around this prohibition: An array can hold a class and any of its subclasses.
- So an array of the Object class could contain any object in Java, including the classes that represent the same values as primitive types.
- 096 Java implements arrays differently than other languages - as objects treated like other objects
- 096 To create an array in Java, you must do the following:
- Declare a variable to hold the array
- Create a new array object and assign it to the array variable.
- Store information in that array
Declaring Array Variables
- Top
- 096 The first step in array creation is to declare a variable that will hold the array.
- Array variables indicate the object or data type that the array will hold and the array's name.
- To differentiate from regular variable declarations, a pair of empty brackets [] is added to the object or data type, or to the variable name:
- The following statements are examples of array decarations:
- String[] requests;
- Point[] targets;
- float[] donations;
- You also can declare an array by putting the brackets after the variable name instead of the information type, as in the following statements:
- String requests[];
- Point targets[];
- float donations[];
- Top
- NOTE: The choice of which style to use is a matter of personal preference.
- The sample programs in this book place the brackets after the information type rather than variable name,
- which is the more popular convention among Java programmers.
Creating Array Objects
- Top
- 097 After you declare the array variable, the next step is to create an array object and assign it to the variable.
- To do this:
- Use the new operator
- Initialize the contents of the array directly.
- 097 Because arrays are objects in Java, you can use the new operator to create a new instance of an array, as in the following statement
- String[] players = new String[10];
- 097 This statement creates a new array of strings with 10 slots that can contain String objects.
- When you create an array object by using new, you must indicate how many slots the array will hold.
- This statement does not put actual String objects in the slots, you must do that later.
- 097 Array objects can contain primitive types, such as integers or Booleans, just as they can contain objects:
- int[] temps = new int[99];
- 097 When you create an array object using new, all its slots automatically are given an intial value:
- 0 for numeric arrays
- false for Booleans
- '\0' for characters arrays
- null for objects
- 097 NOTE: The Java keyword null refers to a null object (and can be used for any object reference). It is not equivalent to 0 or the '\0' character as the NULL constant is in C.
- Top
- 098 Because each object in an array of objects has a null reference when created, you must assign an object to each array element before using it.
- The following example creates an array of three Integer objects and then assigns each element an object:
- Integer[] series = new Integer[];
- series[0] - new Integer(10);
- series[1] - new Integer(3);
- series[2] - new Integer(5);
- 098 You can create and initialize an array at the same time by enclosing the array's elements inside braces, separated by commas:
- Point[] markup = { new Point(1,5), new Point(3,3), new Point(2,3) };
- Each of the elements inside the braces must be the same type as the variable that holds the array.
- When you create an array with initial values in this manner, the array is the same size as the number of elements you include within the braces.
- The preceding example creates an array of Point objects named markup that contains three elements.
- Because String objects can be created and initialized without the new operator, you can do the same when creating an array of strings:
- String[] titles = { "Mr.", "Mrs.", "Ms.", "Miss", "Dr." };
- The preceding statement creates a five-element array of String objects named titles.
- All arrays have an instance variable named length that holds a count of the number of elements in the array.
- Extending the preceding example, the variable titles.length contains the value 5.
- The first element of an array has a subscript of 0 rather than 1. So an array with five elements has array slots accesed using subscripts 0 to 4
Accessing Array Elements
- Top
- 098 After you have an array with initial values, you can retrieve, change, and test values in each slot of that array.
- The value in a slot is accessed using the array name followed by a subscript enclosed in square brackets.
- This name and subscript can be put into expressions, as in the following:
- testScore[40] = 920;
- This statement sets the 41st element of the testScore array to a value of 920, since element numbering begins at 0.
- The testScore part of this expression is a variable holding an array object, although it also can be an expression that results in an array.
- The subscript expression specifies the slot to access within the array.
- Top
- 099 All array subscripts are checked to make sure that they are inside the array's boundaries as specified when an array was created.
- In Java, it is impossible to access or assign a value to an array slot outside the array'e boundaries.
- This avoids the problems that result from over-running the bounds of an array in other languages.
- Note the following two statements:
- float[] rating = new float[20];
- rating[20] = 3.22F;
- Typing these statements into NetBeans would produce an error because the rating array does not have a slot numbered 20, it has 20 slots that begin with 0 and end at 19.
- The Java compiler would fail with an ArrayIndexOutOfBoundsException error.
- 099 The Java Virtual Machine (JVM) also notes an error if the array subscript is calculated when the program is running and the subcript is outside the array's boundaries.
- You learn more about errors, which are called exceptions, on Day 7, "Exceptions and Threads."
- One way to avoid accidentally overrunning the end of an array in your programs is to use the length instance variable.
- The following statement displays the number of elements in the rating array:
- System.out.println("Elements: " + rating.length);
Changing Array Elements
- Top
- 099 As you saw in the previous examples, you can assign a value to a specific slot in an array by putting an assignment statement after the array name and subsript, as in the following:
- temperature[4] = 85;
- day [0] = "Sunday";
- manager[2] = manager[0];
- 099 it's important to remember that an array of objects in Java is an array of references to those objects.
- When you assign a value to a slot in that kind of array, you are creating a reference to that object.
- When you move around values inside arrays, you are reassigning the reference rather than copying a value from one slot to another.
- Arrays of a primitive data type, such as int and float, do copy the values from one slot to another, as do elements of a String array, even though they are objects.
- 100 Arrays are simple to create and modify, and they provide an enormous amount of functionality in Java.
- The HalfDollars application, shown in Listing 4.1, creates, initializes, and displays elements of three arrays.
- Create a new empty Java file in NetBeans called HalfDollars in the com.java21days package, and enter the listing's source code.
Listing 4.1
- Top | Back to Third Program
- page 100
package com.java21days;
class HalfDollars {
public static void main(String[] arguments) {
int[] denver = {1_700_000, 4_600_000, 2_100_000 };
int[] philadelphia = new int[denver.length];
int[] total = new int[denver.length];
int average;
philadelphia[0] = 1_800_000;
philadelphia[1] = 5_000_000;
philadelphia[2] = 2_500_000;
total[0] = denver[0] + philadelphia[0];
total[1] = denver[1] + philadelphia[1];
total[2] = denver[2] + philadelphia[2];
average = (total[0] + total[1] + total[2]) / 3;
System.out.print("2012 production: ");
System.out.format("%,d%n", total[0]);
System.out.print("2013 production: ");
System.out.format("%,d%n", total[1]);
System.out.print("2014 production: ");
System.out.format("%,d%n", total[2]);
System.out.print("Average production: ");
System.out.format("%,d%n", average);
}
}
Listing 4.1 (screenshot from NetBeans) goes here
- Note: I forgot to add the first line:
- but it still ran using the default package
- Top
- 100 The HalfDollars application uses three integer arrays to store production totals for U.S. half-dollar coins produced at the Denver and Philadelphia mints.
- When you run the program, it displays the output shown in Figure 4.1
- 100 The class created here, HalfDollars, has three instance variables that hold arrays of integers.
- The first, which is named denver, is declared and initialized on Line 5 to contain three integers:
- 1_700_000 in element 0
- 4_600_000 in element 1
- 2_100_000 in element 2
- Top
- 101 These figures are the total half-dollar production at the Denver mint for three years.
- The integers use an underscore character _ after every three digits to make the numbers more human-readable.
- The compiler ignores the underscores.
Figure 4.1 (the output pane) goes here
- Top
- 101 The second and third instance variables, philadelphia and total, are declared in lines 6 and 7.
- The philadelphia array contains the production totals for the Philadelphia mint, and total is used to store the overall production totals.
- 101 No initial values are assigned to the slots of the philadelphia and total arrays in lines 6 and 7.
- For this reason, each element is given the default value for integers: 0.
- 101 The denver.length variable is used to give both of these arrays the same number of slots as the denver array.
- Every array contains a length variable that you can use to keep track of the number of elements it contains.
- 101 The rest of the main() method of this application does the following:
- Line 8 creates an integer variable called average.
- Lines 10 - 12 assign new values to the three elements of the philadelphia array.
- Lines 14 - 16 assign new values to the elements of the total array.
- In line 14, total element 0 is given the sum of denver element 0 and philadelphia element 0.
- Similar expressions are used in lines 15 and 16.
- Line 17 sets the value of the average variable to the avaerage of the three total elements.
- Because average and the three total elements are integers, the average is expressed as an integer rather than a floating-point number.
- Lines 19 - 26 display the values stored in the total array and the average variable,
- using the System.out.format() method to display the numeric values in a more readable form using commas.
- Top
- 101 This application handles arrays inefficiently.
- The statements are almost identical, except for the subscripts that indicate the array element to which you are referring.
- If the HalfDollars application were being used to track 100 years of production totals instead of three, this approach would require a lot of redundant statements.
- 102 When dealing with arrays, you can use loops to cycle through an array's elements instead of dealing with each element individually.
- This makes the code a lot shorter and easier to read.
- When you learn about loops later today, you see a rewrite of the current example.
Multidimensional Arrays
- Top
- 102 Arrays can be multidimensional, containing more than one subscript to store information in multiple dimensions.
- A common use of a multidimensional array is to represent the data in an (x,y) grid of array elements.
- Java supports this by enabling an array to hold arrays as each of its elements.
- Those arrays can also contain arrays, and so on, for as many dimensions as needed.
- For example, consider a program that needs to accomplish the following tasks:
- Record an integer value each day for a year.
- Organize those values by week.
- One way to organize this data is to create a 53-element array in which each element contains a 7-element array:
- int[][] dayValue = new int[53][7];
- This array of arrays contains a total of 371 integers, enough room for each day of the year (plus a few extra).
- You could set the value for the first day of the 10th week with the following statement:
- dayValue[9] [0] = 14200;
- Remember that array indexes start at 0 instead of 1, so the 10th week is at element 9 and the first day at element 0.
- You can use the length instance variable with these arrays as you would any other.
- The following statement contains a three-dimensional array of integers and displays the number of elements in each dimension:
- int[][][] cen = new int[100][52][7];
- System.out.println("Elements in 1st dimension: " + cen.length);
- System.out.println("Elements in 2nd dimension: " + cen[0].length);
- System.out.println("Elements in 3rd dimension: " + cen[0][0].length);
Block Statements
- Top
- 103 Statements in Java are grouped into blocks.
- The beginning and ending boundaries of a block are noted with brace characters - an opening brace { for the beginning and a closing brace } for the ending.
- You have used blocks to hold the variables and methods in a class definition and define statements that belong in a method.
- Blocks also are called block statements because an entire block can be used anywhere a single statement could be used.
- Each statement inside the block then is executed from the top to bottom.
- You can put blocks inside other blocks, just as you do when you put a method inside a class definition.
- An important thing to note about using a block is that it creates a scope for the local variables created inside the block.
- Scope is the part of a program where a variable exists and can be used.
- If you try to use a variable outside its scope, an error occurs.
- In Java, the scope of a variable is the block in which it was created.
- When you can declare and use local variables inside a block, those variables cease to exist after the block is finished executing.
- For example, the following method contains a block:
void testBlock() {
int x = 10;
{ // start of block
int y = 40;
y = y + x;
} // end of block
}
- Two variables are defined in this method: x and y.
- The scope of the y variable is the block it's in, which is marked by the comments // start of block and // end of block.
- The variable can be used only within that block.
- An error would result if you tried to use the y variable in another part of the method.
- The x variable was created inside the method but outside the inner block, so it can be used anywhere in the method.
- You can modify the value of x anywhere within the method.
- Block statements are used in class and method definitions and the logic and looping structures you learn about next.
- The way the preceding example uses the inner block is not common.
If Conditionals
- Top
- 104 A key aspect of any programming language is how it enables a program to make decisions.
- This is handled through a type of statement called a conditional, a statement executed only if a specific condition is met.
- 104 The most basic conditional in Java is if.
- The if conditional uses a Boolean expression to decide whether a statement should be executed.
- If the expression produces a true value, the statement is executed.
- 104 Here's a simple example that displays the message "Not enough arguments" only if the value of an instance variable is less than 3:
if (arguments.length < 3) {
System.out.println("Not enough arguments");
System.exit(-1);
}
- 104 If you want something else to happen when an if expression is not true, you can use the else keyword.
- 104 The following example uses both if and else:
String server;
int duration;
if (arguments.length < 1) {
server = "localhost";
} else {
server = arguments[0];
}
- 104 The if conditional executes different statements based on the result of a single Boolean test.
- 104 NOTE: A difference between if conditionals in Java and those in other languages is that Java conditionals produce only Boolean values (true or false). In C and C++, the test can return an integer.
- 104 Using if, you can incluse only a single statement as the code to execute if the test expression is tru and another statement if the expression is false.
- However, as you learned earlier today, a block can appear anywhere in Java that a single statement can appear.
- If you want to do more than one thing as a result of an if statement, you can enclose those statements inside a block.
- Note the following code, which was used on Day 1, "Getting Started with Java":
int speed;
String status;
if (temperature < -60) {
status = "returning home";
speed = 5;
}
- 105 The if statement in this example contains the test expression temperature < -80.
- If the temperature variable contains a value less than -80, the block statement is executed, and two things occur:
- The status variable is given the value "returning home."
- The speed variable is set to 5.
- If the temperature variable is equal to or greater than -80, the entire block is skipped, so nothing happens.
- All if and else statements use Boolean tests to determine whether statements are executed.
- You can use a boolean variable itself for this test, as in the following:
String status;
boolean outOfGas = true;
if (outOfGas) {
status = "inactive";
}
- The preceding example uses a boolean variable called outOfGas. It functions exactly like the following:
if (outOfGas == true) {
status = "inactive";
}
Switch Conditionals
- Top
- 105 A common programming practice is to test a variable against a value, and if it doesn't match, test it again against a different value, and so on.
- This approach can become unwieldy if you're using only if statements, depending on how many different values you have to test.
- For example, you might end up with a set of if statements something like the following:
if (operation == '+')
add(object1, object2);
else if (operation == '-')
subtract(object1, object2);
else if (operation == '*')
multiply(object1, object2);
else if (operation == '/')
divide(object1, object2);
- Top
- 106 This use of if statements is called a nested if statement because each else statement contains another if until all posible tests have been made.
- A better way to handle this situation in Java is by grouping actions with the switch statement.
- The following example demonstrates switch usage:
char grade = 'D';
switch (grade) {
case 'A':
System.out.println("Great job!");
break;
case 'B':
System.out.println("Good job!");
break;
case 'C':
System.out.println("You can do better!");
break;
default:
System.out.println("Consider cheating!");
}
- A switch statement is built on a test variable.
- In the preceding example, the variable is the value of the grade variable, which hold a char value.
- The test variable can be the primitive types byte, char, short, or int or the class String.
- Top
- 106 The following code uses the value of a String object named command to decide which method to call:
String command = "close";
switch (command) {
case "open":
openFile();
break;
case "close":
closeFile();
break;
default:
System.out.println("Invalid command");
}
- Top
- 107 The test variable is compared in turn with each case value.
- If a match is found, the statement or statements after the test are executed.
- If no match is found, the default statement or statements are executed.
- Providing a default statement is optional.
- If it is omitted and there is no match for any of the case statements, the switch statement might complete without executing anything.
- The test cases in a switch statement are limited to primitive types that can be cast to an int, such as char or strings.
- You cannot use larger primitive types such as long or float or test for any relationship other than equality.
- The following is a revision of the nested if example shown previously.
- It has been rewritten as a switch statement:
switch (operation) {
case '+':
add(object1, object2);
break;
case '-':
subtract(object1, object2);
break;
case '*':
multiply(object1, object2);
break;
case '/':
divide(object1, object2);
break;
}
- Top
- 107 After each case, you can include a single result statement or as many as you need.
- Unlike if statements, multiple statements don't require a block statement.
- 107 The break statement included with each case section determines when to stop executing statements in response to a matching case.
- Suppose a case section has no break statement.
- After a match is made, the statements for that match and all the statements further down the switch are executed until a break or the end of the switch is found.
- 107 In some situations, this might be exactly what you want to do.
- Otherwise, you should include break statements to ensure that only the right code is executed.
- The break statement, stops execution at the current point.
- Then it jumps to the statement after the closing brace that ends the switch statement.
- 107 One handy use of falling through without a break occurs when multiple values need to execute the same statements.
- To accomplish this task, you can use multiple case lines with no result, the switch executes the first statement it finds.
- Top
- 108 For example, in the following switch statement, the string " x is an even number" is printed if x has a value of 2, 4, 6, or 8.
- All other values of x cause the string "x is an odd number" to be printed.
int x = 5;
switch (x) {
case 2:
case 4:
case 6:
case 8:
System.out.println("x is an even number");
break;
default:
System.out.println("x is an odd number");
}
Second Program
- Top | Back to Exercises
- 108 The next project for today, the DayCounter application in Listing 4.2 takes a month and a year as arguments and displays the number of days in that month.
- A switch statement, if statements, and else statements are used.
- Create this application in NetBeans as an empty Java file in the com.java21days package.
- reserve
New Empty Java File window
Source Code
Files pane
Listing 4.2
- Top
- page 108-109
package com.java21days;
class DayCounter {
public static void main(String[] arguments) {
int yearIn = 2016;
int monthIn = 1;
if(arguments.length > 0)
monthIn = Integer.parseInt(arguments[0]);
if(arguments.length > 1)
yearIn = Integer.parseInt(arguments[1]);
System.out.println(monthIn + "/" + yearIn + " has "
+ countDays(monthIn, yearIn) + " days.");
}
static int countDays(int month, int year) {
int count = 1;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
count = 31;
break;
case 4:
case 6:
case 9:
case 11:
count = 30;
break;
case 2:
if (year % 4 == 0)
count = 29;
else
count = 28;
if ((year % 100 == 0) & (year % 400 != 0))
count = 28;
}
return count;
}
}
- I pressed the Save All button after entering the code & fixing errors (typos).
(Running the Program) Command-line arguments
- Top
- 109 This application uses command-line arguments to specify the month and year to check.
- The first argument is the month, which should be expressed as a number from 1 to 12.
- The second argument is the year, which should be expressed as a full four-digit year.
- 109 If the application is run without setting the arguments, it uses 1 as month and 12 as the year, displaying the output in Figure 4.2
Figure 4.2 (screenshot from NetBeans Output pane) goes here
run:
1/2016 has 31 days.
BUILD SUCCESSFUL (total time: 0 seconds)
Setting Command-line arguments
- Top
- 109 To set command-line arguments in NetBeans, choose Run, Set Project Configuration, Customize.
- The Project Properties dialog opens, as shown in Figure 4.3
- 109 In the Main Class field, enter the name of the class that contains the main() method that will be run: com.java21days.DayCounter.
- In the Arguments field, enter the command-line arguments separted by spaces, such as 9 2016.
- Click OK to save this configuration.
Run, Run Project
- 109 To run the application with these arguments in NetBeans, choose Run, Run Project (instead of Run, Run File).
- When run with 9 and 2016 arguments, the output is that shown in Figure 4.4
Figure 4.3 (screenshot from NetBeans) goes here
- 110 Setting command-line arguments for the application in NetBeans.
Figure 4.4 goes here
- 110 Using switch-case to handle numerous conditionals.
Explanation of Program
- Top
- 110 The DayCounter application uses a switch statement to count the days in a month.
- This statement is part of the countDays() method in lines 15 - 42 of Listing 4.2
- 110 The countDays() method has two int arguments: month and year.
- The number of days is stored in the count variable, which is given the value of -1 that is replaced by the correct count later.
- 110 The switch statement that begins on line 17 uses month as its conditional value.
- The number of days in the month is easy to determine for 11 months of the year.
- January, March, May July, August, October, and December have 31 days.
- April June, September, and November have 30 days.
- Top
- 110 The count for these 11 months is handled in lines 18 - 32 of Listing 4.2
- Months are numbered 1 (January) to 12 (December).
- When one of the case statements has the same value as month, every statement after that is executed until break or the end of the switch statement is reached.
- 110 February is more complex and is handled in lines 33 - 39.
- Every leap year has 29 days in February, where as other years have 28.
- A leap year must meet either of the following conditions:
- The year must be evenly divisible by 4 and not evenly divisible by 100.
- The year must be evenly divisible by 400.
- Top
- 111 As you learned on Day 2, "The ABC's of programming," the modulus operator % returns the remainder of a division operation.
- This is used with several if-else statements to determine how many days there are in February, depending on what year it is.
- 111 The if-else statements in lines 34-37 sets count to 29 when the year is evenly divisible by 4 and sets it to 28 otherwise.
- 111 The if statement in lines 38 - 39 uses the & operator to combine two conditional expressions:
- year % 100 == 0
- and year % 400 != 0
- If both these conditions are true, count is set to 28.
- 111 The countDays method ends by returning the value of count in line 41.
- 111 When you run the DayCounter application, the main() method in lines 4 - 13 is executed.
- Top
- 111 In all Java applications, command-line arguments are stored in an array of String objects.
- This array is called arguments in DayCounter.
- The first command-line argument is stored in argument[0], the second in argument[1], and upward until all arguments have been stored.
- If the application is run with no arguments, the array is created with no elements.
- 111 Lines 5 and 6 create yearIn and monthIn, two integer variables to store the year and month that should be checked.
- The if statement in Line 7 uses arguments.length to make sure that the arguments array has at least one element.
- If it does, line 8 is executed.
- 111 Line 10 calls parseInt(), a class method of the Integer class, with arguments[0] as an augument.
- This method takes a String object as an argument, and if the string could be a valid integer, it returns that value as an int.
- This converted value is stored in monthIn.
- A similar thing happens in line 10: parseInt() is called with arguments[1], and this is used to set yearIn,
- and the value returned by this method is displayed.
- Top
- 112 NOTE: At this point, you might want to know how to connect input from a user in a program rather than using command-line arguments to receive it.
- There isn't a method comparable to System.out.println() that receives input.
- Instead, you must learn a bit more about Java's input and output classes before you can receive input in a program without a graphical user interface.
- This topic is covered during Day 15, "Working with Input and Output."
The Ternary Operator
- Top
- 112 An alternative to using the if and else keywords in a conditional statement is to use the ternary operator, also called the conditional operator.
- This operator is ternary because it has three operands (the word "ternary" refers to anything with three parts).
- This operator is an expression, meaning that it returns a value - unlike the more general if, which can result in only a statement or block being executed.
- The operator is most useful for short or simple conditions and takes the following form:
- test ? trueResult : falseResult;
- The test is an expression that returns true or false, just like the test in the if statement.
- If the test is true, the conditional operator returns the value of trueResult.
- If the test is false, the conditional operator returns the value of falseResult.
- For example, the following conditional tests the values of myScore and yourScore and sets the variable ourBestScore equal to one of them:
- int ourBestScore = myScore > yourScore ? myScore : yourScore;
- In this statement, the larger value of myScore and yourScore is copied to ourBestScore.
- This use of the ternary operator is equivalent to the following if-else code:
int ourBestScore;
if (myScore > yourScore) {
ourBestScore = myScore;
} else {
ourBestScore = yourScore;
}
- The ternary operator has low precedence.
- Usually it is evaluated only after all its subexpressions have been evaluated.
- The only operators lower in precedence are the assignment operators.
- For a refresher on operator precedence, refer to Table 2.6 in Day 2.
- Top
- 113 NOTE: The ternary operator is of primary benefit to experienced programmers creating complex expressions.
- Because its functionality is duplicated in simpler use of if-else statements, there's no need to use this operator while you're beginning to learn the language.
- The main reason it's introduced in this book is because you'll encounter it in source code of other Java programmers.
- reserve
For Loops
- Top
- 113 A for loop is used to repeat a statement until a condition is met.
- Although for loops frequently are used for simple iteration in which a statement is repeated a certain number of times, for loops can be used for just about any kind of loop.
- The for loop in Java has the following structure:
for (initialization; test; increment) {
statement;
}
- Top
- 113 The start of the for loop has three parts:
- the initialization
- the test
- the increment
- The initialization is an expression that initialize the start of the loop.
- If you have a loop index, this expression might declare and initialize it, such as int i = 0.
- Variables that you declare in this part of the for loop are local to the loop itself.
- They cease to exist after the loop is finished executing.
- You can initialize more than one variable in this section by separating each expression with a comma.
- The statement int i = 0, j = 10 in this section would declare the variables i and j, and both would be local to the loop.
- The test is the test that occurs before each pass of the loop.
- The test must be a Boolean expression or a function that returns a boolean value, such as i < 10.
- If the test is true, the loop executes.
- When the test is false, the loop stops executing.
- The increment is any expression or method call.
- Commonly, the increment is used to change the value of the loop index to bring the state of the loop closer to returning false and stopping the loop.
- The increment takes place after each pass of the loop.
- Similar to the initialization section, you can put more than one expression in this section by separating each expression with a comma.
- Top
- 114 The statement part of the for loop is the statement that is executed each time the loop iterates.
- As with if, you can include either a single statement or a block statement.
- The previous example used a block because that is more common.
- The following example is a for loop that sets all slots of a String array to the value of "Mr.":
String[] salutation = new String[10];
int i; // the loop index variable
for (i = 0; i < salutation.length; i++) {
salutation[i] = "Mr.";
}
- In this example, the variable i serves as a loop index, it counts the number of times the loop has been executed.
- Before each trip through the loop, the index value is compared with salutation.length, the number of elements in the salutation array.
- When the index is equal to or greater than salutation.length, the loop is exited.
- Top
- 114 The final element of the for statement is i++.
- This causes the loop index to increment by 1 each time the loop is executed.
- Without this statement, the loop would never stop.
- 114 The statement inside the loop sets an element of the salutation array equal to "Mr.".
- The loop index is used to determine which element is modified.
- Top
- 114 Any part of the for loop can be an empty statement,
- in other words, you can include a semicolon with no expression or statement, and that part of the for loop is ignored.
- Note that if you do use an empty statement in your for loop, you might have to initialize or increment any loop variables or loop indexes yourself elsewhere in the program.
- You also can have an empty statement as the body of your for loop if everything you want to do is in the first line of that loop.
- For example, the following for loop finds the first prime number higher than 4,000.
- (It assumes the existance of a method called notPrime() that returns a Boolean value to indicate when i is not prime.)
- for (i = 4001; notPrime(i); i += 2);
- The semicolon at the end of the for statement indicates that the loop has no statements in its body.
- A common mistake in for loops is to accidently put a semicolon at the end of the line that includes the for statement.
int x = 1;
for (i = 0; i < 10; i++);
x = x * 1; //this line in not inside the loop
- In this example, the semicolon outside the parentheses in the for statement ends the loop without executing x = x * 1 as part of the loop.
- The x = x * 1line is executed only once because it is outside the for loop.
- Be careful not to make this mistake in your Java programs.
Third Program
- Top
- 115 The next project you unertake is a rewite of the HalfDollar application that uses for loops to remove redundant code.
- The original application (First Program) works with an array that is only three elements long.
- The new version shown in Listing 4.3, called HalfLooper, is shorter and more flexible and returns the same output.
- 115 Create an empty Java file with that class name and package name com.java21days in NetBeans.
- note: I'm missing the Empty File window that we type the package name into.
Listing 4.3
- Top
- page 115
package com.java21days;
class HalfLooper {
public static void main(String[] arguments) {
int[] denver = { 1_700_000, 4_600_000, 2_100_000 };
int[] philadelphia = { 1_800_000, 5_000_000, 2_500_000 };
int[] total = new int[denver.length];
int sum = 0;
for (int i = 0; i < denver.length; i++) {
total[i] = denver[i] + philadelphia[i];
System.out.format((i + 2012) + " production: %,d%n",
total[i]);
sum += total[i];
}
System.out.format("Average production: %,d%n",
(sum / denver.length));
}
}
- Screenshot taken after saving the file
- 115 The output is the same as Figure 4.1
- which was created by running the "First Program's Output pane from NetBeans
- note its original name HalfDollars
Figure 4.1 From the First Program, HalfDollars
Screenshot from NetBeans after successfully running the program
The explanation
- Top
- 115 Instead of going through the elements of the three arrays one by one, this example uses a for loop.
- The following things take place in the loop, which is contained in lines 10-15:
- Line 10 The loop is created with an int variable called i as the index
- The index increments by 1 for each pass though the loop and stops when i is equal to or greater than denver.length, the total number of elements in the denver array.
- Line 11-12 The value of one of the total elements is set using the loop index
- and then is displayed with some text identifying the year.
- Line 14 The value of a total element is added to the sum variable, which is used to calculate the avaerage yearly production.
- 116 Using a more general-purpose loop to iterate over an array enables you to use the program with arrays of different sizes and still have it assign correct values to the elements of the total array and display those values.
- 116 NOTE: Java also includes a for loop that can be used to iterate through all the elements of data structures, such as array lists, linked lists, hash maps, and other collections.
- This loop is covered along with those structures on Day 8, "Data Structures."
While and Do Loops
- Top
- 116 The remaining types of loops are while and do, which also enable a block of Java code to be executed repeatedly until a specific condition is met.
While Loops
- Top
- 116 The while loop repeats a statement for as long as a particular condition remains true.
- Here's an example:
while (i < 13) {
x = x * i++; //the body of the loop
}
- 116 The condition that accompanies the while keyword is a Boolean expression: i < 13 in the preceding example.
- If the expression returns true, the while loop executes the body of the loop and then tests the condition again.
- This process repeats until the condition is false.
- 116 Although the preceding loop uses opening and closing braces to form a block statement, the braces are unneeded because the loop contains only one statement: x = x * i++.
- Using the braces does not create any problems, though, and the braces will be required if you add another statement inside the loop later.
Fourth Program
- Top
- 116 The ArrayCopier application in Listing 4.4 uses a while loop to copy the elements of an array of integers (array1) to an array of float variables (array2),
- casting each element to a float as it goes.
- The one catch is that if any of the elements in the first array is 1, the loop immediately exits at that point.
- Top
- 117 Create an empty Java file in NetBeans with the class name ArrayCopier and package com.java21days. Enter Listing 4.4 as the source code.
Listing 4.4 - The Full Text of ArrayCopier.java
- Top
- page 117
package com.java21days;
class ArrayCopier {
public static void main(String[] arguments) {
int[] array1 = = { 7, 4, 8, 1, 4, 1, 4 };
float[] array2 = new float[array1.length];
System.out.print("array1: [ ");
for (int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + " ");
}
System.out.println("array2: [ ");
System.out.print("]");
int count = 0;
while ( count < array1.length && array1[count] != 1) {
array2[count] = (float) array1[count];
System.out.print(array2[count++] + " ");
}
System.out.print("]");
}
}
the Ouput pane
- Top
- 117 The output is shown in Figure 4.5
the Explanation
- Top
- 117 Here's is what's going on in the main() method:
- Lines 5 and 7 declare the arrays, array1 is an array of integers, which are initialized to some suitable numbers.
- array2 is an array of floating-point numbers the same length as array1
- Lines 8 - 12 iterate through array1 using a for loop to print its values.
- Lines 14 - 20 assign the values of array2 (converting the numbers to floating-point numbers along the way) and print them.
- You start with a count variable, which keeps track of the array index elements.
- The test in the while loop keeps track of the two conditions for exiting the loop,
- where those two conditions are running out of elements in array1 or encountering a 1 in array1.
- You can use logical conditional && operator to keep track of the test,
- remember that && makes sure that both conditions are true before the entire expression is true.
- If either one is false, the expression returns false, and the loop exits.
- Top
- 118 The program's output shows that the first four elements in array1 were copied to array2, but a 1 in the middle stopped the loop from going further.
- Without the 1, array2 should end up with all the same elements as array1.
- If the while loop's test initially is false the first time it is tested (for example,
- if the first element in that first array is 1), the body of the while loop will never be executed.
- If you need to execute the loop at least once, you can do one of two things:
- Duplicate the body of the loop outside the while loop.
- Use a do loop (which is described in the following section).
- 118 The do loop is considered the better solution.
Do-While Loops
- Top
- 118 The do loop is like a while loop, with one major difference, the place in the loop where the condition is tested.
- 118 A while loop tests the condition before looping, so if the condition is false the first time it is tested, the body of the loop never executes.
- 118 A do loop executes the body of the loop at least once before testing the condition.
- So if the condition is false the first time it is tested, the body of the loop already will have executed once.
- 118 The following example uses a do loop to keep doubling the value of a long integer until it is larger than 3 trillion:
long i - 1;
do (
i *= 2;
System.out.print(i + " ");
} while (i < 3_000_000_000_000L);
- 118 The body of the loop is executed once before the test condition, i < 3_000_000_000_000 is evaluated.
- Then, if the test evaluates as true, the loop runs again.
- If it is false, the loop exits.
- Keep in mind that the body of the loop executes at least once with do loops.
- 119 The for, while, and do loops all accomplish the same purpose in slightly different ways
- When writing your own code, you may have trouble deciding which one to use.
- There's often no wrong answer.
- Whether you use for, while, or do loop is largely a matter of prefrence.
Breaking Out of Loops
- Top
- 119 All loops end when a tested condition is met.
- There might be times when something occurs during the execution of a loop, and you want to exit the loop early.
- In that case, you can use the break and continue keywords.
- 119 You already have seen break as part of the switch statement, break stops execution of the switch statement, and the program continues.
- The break keyword, when used with a loop, does the same thing, it immediately halts execution of the current loop.
- If you have nested loops within loops, execution picks up with the next outer loop.
- Otherwise, the program continues executing the next statement after the loop.
- 119 For example, recall the while loop from the ArrayCopier application in Listing 4.4
- It copied elements from an integer array into an array of floating-point numbers until either the end of the array or a 1 was reached.
- You can test for the latter case inside the body of the while loop and then use break to exit the loop:
int count = 01;
while (count < array1.length) {
if (array1[count] == 1) [
break;
}
array2[count] = (float) array2[count++];
}
- 119 The continue keyword starts the loop over at the next iteration.
- For do and while loops, this means that the execution of the block statement starts over again,
- with for loops, the increment expression is evaluated,
- and then the block statement is executed.
- 119 The continue keyword is useful when you want to make a special case out of elements within a loop.
- With the previous example of copying one array to another,
- you could test for whether the current element is equal to 1
- and use continue to restart the loop after every 1 so that the resulting array never contains 0.
- Note that because you're skipping elements in the first array, you now have to keep track of two different array counters:
int count = 01;
int count2 = 01;
while (count++ <= array1.length) {
if (array1[count] == 1) [
continue;
}
array2[count++] = (float) array1[count];
}
Labeled Loops
- Top
- 120 Both break and continue can have an optional label that indicates where to resume execution of the program.
- Without a label, break jumps outside the nearest loop to an enclosing loop or to the next statement outside the loop.
- The continue keyword restarts the loop it is enclosed within.
- Using break and continue with a label enables you:
- to use break to go to a point outside a nested loop or
- to use continue to go to a loop outside the current loop.
- To use a labeled loop, add the label before the initial part of the loop with a colon between the label and the loop.
- Then, when you use break or continue, add the name of the label after the keyword itself, as in the following:
out: for (int i = 0; i , 10; i++) {
for (int j = 0; j < 50; j++) {
if (i * j > 400) [
break out;
}
}
}
- In this code snippet, the label out labels the outer loop.
- Then, inside the for loops, when a particular condition is met, a break causes the execution to break out of both loops.
- Without the label out, the break statement would exit the inner loop and resume execution with the outer loop.
- Labeled loops are used infrequently in Java.
- There's usually another way to accomplish the same thing.
Summary
- Top
- 121 Now that you have been introduced to lists, loops, and logic, you can make a computer decide whether to repeatedly display the contents of an array
- 121 You've learned how to
- declare an array variable,
- assign an object to it,
- and access and change elements of this array.
- 121 With the if and switch conditional statements, you can branch to different parts of a program based on a Boolean test.
- 121 You learned about the for, while and do loops, and you learned that each enables a portion of a program to be repeated until a given condition is met.
Q & A
- Top (Page 121)
- Q I declared a variable inside a block statement for an if. When the if was done, the definition of that variable vanished. Where did it go ?
- A In technical terms, block statements form a new lexical scope
- This means that if you declare a variable inside a block, it's visible and usable only inside that block.
- When the block finishes executing, all the variables you declared go away.
- It's a good idea to declare most of your variables in the outermost block in which they'll be needed, usually at the top of a block statement.
- The exception might be simple variables, such as index counters in for loops, where declaring them in the first line of the for loop is an easy shortcut.
- Q Why can't I use switch with strings ?
- A You can. If it isn't working in NetBeans, you must make sure that you have a current version of Java installed and your development environment has been set up to use it.
- In NetBeans, to see whether the current project is set up for Java 8, choose File, Project Properties to open the properties dialog. Choose Libraries in the Categories pane, then set Java Platform to JDK 8 if it isn't already. Click OK to save the change and exit the dialog.
Quiz - Questions
- Top (Page 122)
- Review today's material by taking this three-question quiz.
- What kind of loop is used to execute the statements in the loop at least once before the conditional expression is evaluated?
- do-while
- for
- while
- Which of the following cannot be used as the test in a case statement ?
- characters
- strings
- objects
- Which instance variable of an array is used to find out how big it is ?
- size
- length
- MAX_VALUE
Answers
- Top | Note A is 1, B is 2, and C is 3
- A. In a do-while loop, the while conditional statement appears at the end of the loop. Even if it is initially false, the statement in the loop are executed once.
- C. It use to be true that strings could not be used as a test, but that is no longer the case.
- B. The length variable is an integer that returns the array's size. (how many elements are in the array)
Certification Practice
- Top
- 122 The following question is the kind of thing you could expect to be asked on a Java programming certification test. Answer it without looking at today's material or using the Java compiler to test the code.
- The answer is available on the book's website at www.java21days.com
- Given:
public class Cases {
public static void main(String[] arguments) {
float x = 9;
float y = 5;
int z = (int)(x / y);
switch (z) {
case 1:
x = x + 2;
case 2:
x = x + 3;
default:
x = x + 1;
}
System.out.println("Value of x: " + x);
}
}
- What will the value of x when it is displayed ?
- 9.0
- 11.0
- 15.0
- The program will not compile.
Exercises
- Top
- 123 To extend your knowledge of the subjects covered today, try the following exercises:
- Using the countDays() method from the DayCounter application, (Second Program)
- create an application that displays every date in a given year in a sigle list from January 1 to December 31.
- Create a class that takes words for the first 10 numbers ("one" to "ten") and convert them into a single long, integer.
- Use a switch statement for the conversion and command-line arguments for the words.
Reserve