4
Directing values
This chapter demonstrates how to direct data values using various Java programming constructs.
Casting type values
Handling values in Java programming requires correct data typing to be closely observed to avoid compiler errors. For example, sending a float type value to a method that requires an int type value will produce a compiler error. This means it is often necessary to convert a value to another data type before it can be processed.
Numeric values can be easily “cast” (converted) into another numeric data type using this syntax:
( data-type ) value
Some loss of precision will occur when casting float floating point values into an int data type, as the number will be truncated at the decimal point. For example, casting a float value of 9.9 into an int variable produces an integer value of nine.
Interestingly, character values of the char data type can automatically be used as int values because they each have a unique integer representation. This is their numeric code value in the ASCII character set, which is supported by Java. The uppercase letter A, for instance, has the code value of 65.
Numeric values can be converted to the String data type using the toString() method of that value’s data type class. This takes the numeric value as its argument, within the parentheses. For example, convert an int num variable to a String with Integer.toString(num). Similarly, convert a float num variable to a String with Float.toString(num). In practice, this technique is not always required because Java automatically converts concatenated variables to a String if any one of the variables has a String value.
More frequently, you will want to convert a String value to a numeric data type so the program can use that value arithmetically. A String value can be converted to an int value using the Integer.parseInt() method. This takes the String value as its argument, within the parentheses. For example, convert a String msg variable to an int with Integer.parseInt(msg). Similarly, convert a String msg variable to a float with Float.parseFloat(msg). When converting a String value to a numeric data type, the String may only contain a valid numeric value, or the compiler will report an error.
All numeric classes have a parse... method and a toString method allowing conversion between String values and numeric data types.
Start a new program named “Convert” containing the standard main method
class Convert
{
public static void main ( String[] args ) { }
}
Convert.java
Inside the main method, declare and initialize a float variable and a String variable
float daysFloat = 365.25f ;
String weeksString = “52” ;
Cast the float value into an int variable
int daysInt = (int) daysFloat ;
Convert the String value into an int variable
int weeksInt = Integer.parseInt( weeksString ) ;
Perform arithmetic on the converted values and display the result
int week = ( daysInt / weeksInt ) ;
System.out.println( “Days per week: “ + week ) ;
Save the program as Convert.java then compile and run the program to see the output
Creating variable arrays
An array is simply a variable that can contain multiple values – unlike a regular variable that can only contain a single value.
The declaration of an array first states its data type, using one of the data type keywords, followed by square brackets [ ] to denote that it will be an array variable. Next, the declaration states the array variable name, adhering to the normal naming conventions.
An array can be initialized in its declaration by assigning values of the appropriate data type as a comma-delimited list, enclosed within curly brackets. For example, the declaration of an integer array variable initialized with three values might look like this:
int[ ] numbersArray = { 1, 2, 3 } ;
The array is created of the length of the assigned list, allowing one “element” per value – in this case, an array of three elements.
Stored values are indexed starting at zero, and each value can be addressed by its element index position. The syntax to do so requires the array name to be followed by square brackets containing the element index. For instance, numbersArray[0] would address the first value stored in the example above (1).
Although the values stored in each element can be changed as simply as those of regular variables, the size of an array is determined by its declaration and cannot be changed later. Usefully, the total number of elements in an array is stored as an integer in the length property of that array. The syntax to address this figure just tacks a period and “length” onto the array name. For example, numbersArray.length would return the size of the array in the example above – in this case, the integer 3.
Arrays can also be declared without assigning a list of initial values by using the new keyword to create an empty array “object” of a specified size. The number of required empty elements is stated in the assignment within square brackets after the appropriate data type. For example, the declaration of an empty integer array variable with three elements might look like this:
int[ ] numbersArray = new int[3] ;
The elements are assigned default values of zero for int and float data types, null for String data types, \0 for char data types, and false for boolean data types.
Remember that array indexing starts at zero. This means that index[2] addresses the third element in the array, not its second element.
Start a new program named “Array” containing the standard main method
class Array
{
public static void main ( String[] args ) { }
}
Array.java
Inside the main method, declare and initialize a String array with three elements
String[] str = { “Much ”, “More”, “ Java” } ;
Declare an empty integer array with three elements
int[] num = new int[3] ;
Assign values to the first two integer array elements
num[0] = 100 ;
num[1] = 200 ;
Assign a new value to the second String array element
str[1] = “Better” ;
Output the length of each array and the content of all elements in each array
System.out.println( “String array length is “ + str.length ) ;
System.out.println( “Integer array length is “+ num.length) ;
System.out.println( num[0] + ”,” +num[1]+ ”,”+num[2] ) ;
System.out.println( str[0] + str[1] + str[2] ) ;
Save the program as Array.java then compile and run the program to see the output
String values need to be enclosed within quotes.
Passing an argument
The standard Java code that declares the program’s main method includes an argument within its parentheses that creates a String array, traditionally named “args”:
public static void main( String[] args ) { }
The purpose of the args[] array is to allow values to be passed to the program when it is called upon to run. At the command line, a value to be passed to the program is added after a single space following the program name. For example, the command to pass the String “Java” to a program named “Run” would be Run Java.
A single value passed to a program is automatically placed into the first element of the args[] array, so it can be addressed by the program as args[0].
It is important to recognize that the args[] array is of the String data type – so a numeric value passed to a program will be stored as a String representation of that number. This means that the program cannot use that value arithmetically until it has been converted to a numerical data type, such as an int value. For example, Run 4 passes the number four to the program, which stores it as the String “4”, not as the int 4. Consequently, output of args[0]+3 produces the concatenated String “43”, not the sum 7. The argument can be converted with the Integer.parseInt() method so that Integer.parseInt( args[0])+3 does produce the sum 7.
A String containing spaces can be passed to a program as a single String value by enclosing the entire String within double quotes on the command line. For example, Run “Java In Easy Steps”.
Passing an argument to a program is most useful to determine how the program should run by indicating an execution option. The option is passed to the program as a String value in args[0] and can be evaluated using the String.equals() method. The syntax for this just tacks a period and “equals()” onto the array name, with a comparison String within the parentheses. For example, args[0].equals(“b”) evaluates the argument for the String value “b”.
Start a new program named “Option” containing the standard main method
class Option
{
public static void main ( String[] args ) { }
}
Option.java
Inside the main method, write an if statement to seek an argument of “-en”
if ( args[0].equals( “-en” ) )
{
System.out.println( “English option” ) ;
}
Add an else alternative onto the if statement to seek an argument of “-es”
else if ( args[0].equals( “-es” ) )
{
System.out.println( “Spanish option” ) ;
}
Add another else alternative onto the if statement to provide a default response
else System.out.println( “Unrecognized option” ) ;
Save the program as Option.java then compile and run the program to see the output
This example will throw an ArrayIndexOutOfBounds exception if you attempt to execute the program without any argument. See here for details on how to catch exceptions.
Passing multiple arguments
Multiple arguments can be passed to a program at the command line, following the program name and a space. The arguments must be separated by at least one space and their values are placed, in order, into the elements of the args[] array. Each value can then be addressed by its index number as with any other array – args[0] for the first argument, args[1] for the second argument, and so on.
The program can test the length property of the args[] array to ensure the user has entered the appropriate number of arguments. When the test fails, the return keyword can be used to exit the main method, thereby exiting the program:
Start a new program named “Args” containing the standard main method
class Args
{
public static void main ( String[] args ) { }
}
Args.java
Inside the main method, write an if statement to output advice and exit the program when there are not the required number
of arguments – in this case, three
if ( args.length != 3 )
{
System.out.println( “Wrong number of arguments” ) ; return ;
}
Below the if statement, create two int variables – initialized with the values of the first argument and third argument
respectively
int num1 = Integer.parseInt( args[0] ) ;
int num2 = Integer.parseInt( args[2] ) ;
Add a String variable, initialized with a concatenation of all three arguments
String msg = args[0] + args[1] + args[2] + “=” ;
The return keyword exits the current method. It can also return a value to the point where the method was called. See here for more details.
Add this if else statement to perform arithmetic on the arguments and append the result to the String variable
if ( args[1].equals(“+”) ) msg += (num1 + num2);
else if ( args[1].equals(“-”) ) msg += (num1 - num2) ;
else if ( args[1].equals(“x”) ) msg += (num1 * num2) ;
else if ( args[1].equals(“/”) ) msg += (num1 / num2) ;
else msg = “Incorrect operator” ;
Insert this line at the end of the main method to display the appended String
System.out.println( msg ) ;
Save the program as Args.java then compile and run the program with three arguments – an integer, any arithmetical
symbol + - x /, and another integer
Now, run the program with an incorrect second argument and with the wrong number of
arguments
This program will report an error if non-numeric values are entered. See here for details on how to catch errors.
Looping through elements
All types of loop can be used to easily read all the values stored inside the elements of an array. The loop counter should start with the index number of the first element then proceed on up to the final index number. The index number of the last element in an array will always be one less than the array length – because the index starts at zero.
It is useful to set the array length property as the loop’s conditional test determining when the loop should end. This means that the loop will continue until the counter value exceeds the index number of the array’s final element.
Start a new program named “Loops” containing the standard main method
class Loops
{
public static void main ( String[] args ) { }
}
Loops.java
Inside the main method, write an if statement to test whether any argument values have been entered into the args[] array from the command line
if ( args.length > 0 ) { }
Insert a for loop inside the curly brackets of the if statement to output the value stored in each element
for ( int i = 0 ; i < args.length ; i++ )
{
System.out.println( “args[“ +i+ “] is | “+ args[i] ) ;
}
Save the program as Loops.java then compile the program and run it with the arguments Java in easy steps
Edit Loops.java to add a String array and a while loop to output the value stored in each element
String[] htm = { “HTML5”, “in”, “easy”, “steps” } ;
int j = 0 ;
while ( j < htm.length )
{
System.out.println( “htm[“ +j+ “] is | “ + htm[j] ) ;
j++ ;
}
Save the changes, then recompile and re-run the program
Edit Loops.java to add another String array and a do while loop to output the value stored in each element
String[] xml = { “XML”, “in”, “easy”, “steps” } ;
int k = 0 ;
if ( xml.length > 0 ) do
{
System.out.println( “\t\txml[“+k+“] is | “+xml[k] ) ;
k++ ;
} while ( k < xml.length ) ;
Save the changes, then recompile and re-run the program
Notice that the do statement is preceded by a conditional test to ensure the array is not empty before attempting to output the value of the first element.
Changing element values
The value stored in an array element can be changed by assigning a new value to that particular element using its index number. Additionally, any type of loop can be used to efficiently populate all the elements in an array from values stored in other arrays. This is especially useful to combine data from multiple arrays into a single array of totaled data.
Start a new program named “Elements” containing the standard main method
class Elements
{
public static void main ( String[] args ) { }
}
Elements.java
In the main method, add initialized int arrays representing monthly kiosk sales from all four quarters of a year
int[] kiosk_q1 = { 42000 , 48000 , 50000 } ;
int[] kiosk_q2 = { 52000 , 58000 , 60000 } ;
int[] kiosk_q3 = { 46000 , 49000 , 58000 } ;
int[] kiosk_q4 = { 50000 , 51000 , 61000 } ;
Add initialized int arrays representing monthly outlet sales from all four quarters of a year
int[] outlet_q1 = { 57000 , 63000 , 60000 } ;
int[] outlet_q2 = { 70000 , 67000 , 73000 } ;
int[] outlet_q3 = { 67000 , 65000 , 62000 } ;
int[] outlet_q4 = { 72000 , 69000 , 75000 } ;
Now, create an empty int array of 12 elements in which to combine all the monthly sales figures and an int variable in which to record their grand total value
int[] sum = new int[ 12 ] ;
int total = 0 ;
Add a for loop to populate each element of the empty array with combined values from the other
arrays
for ( int i = 0 ; i < kiosk_q1.length ; i++ )
{
sum[ i ] = kiosk_q1[i] + outlet_q1[i] ;
sum[i+3] = kiosk_q2[i] + outlet_q2[i] ;
sum[i+6] = kiosk_q3[i] + outlet_q3[i] ;
sum[i+9] = kiosk_q4[i] + outlet_q4[i] ;
}
Next, add a second for loop to output each of the combined monthly sales totals, and to calculate their
grand total
for ( int i = 0 ; i < sum.length ; i++ )
{
System.out.println( “Month “+ ( i+1 ) + ” sales:\t” + sum[i] ) ;
total += sum[i] ;
}
Insert a final statement at the end of the main method to output the grand total
System.out.println( “TOTAL YEAR SALES\t” + total ) ;
Save the program as Elements.java then compile the program and run it to see the output
The counter number gets increased by one to produce the month numbers 1-12.
Adding array dimensions
Arrays can be created to store multiple sets of element values, each having their own index dimension. Individual values are addressed in a multi-dimensional array using the appropriate index numbers of each dimension. For example, num [1] [3].
A two-dimensional array might be used to record an integer value for each day of a business year, organized by week. This requires an array of 52 elements (one per week) that each have an array of seven elements (one per day). Its declaration looks like this:
int[][] dailyRecord = new int [52] [7] ;
Avoid using more than three dimensions in arrays – it will be confusing.
This “array of arrays” provides an element for each business day. Values are assigned to a multi-dimensional array by stating the appropriate index numbers of each dimension. With the example above, for instance, a value can be assigned to the first day of the sixth week like this:
dailyRecord [5] [0] = 5000 ;
Each array has its own length property that can be accessed by specifying the dimension required. For the example above, the syntax dailyRecord.length returns a value 52 – the size of the first dimension. To access the size of the second dimension, the syntax dailyRecord[0].length returns the value of seven.
Two-dimensional arrays are often used to store grid coordinates, where one dimension represents the X axis and the other dimension represents the Y axis. For example, point[3][5].
Three-dimensional arrays can be used to store XYZ coordinates in a similar way, but it can be difficult to visualize point[4][8][2].
Nested loops are perfectly suited to multi-dimensional arrays, as each loop level can address the elements of each array dimension.
Start a new program named “Dimensions” containing the standard main method
class Dimensions
{
public static void main ( String[] args ) { }
}
Dimensions.java
In the main method, create a two-dimensional array to store Boolean flats relating
to XY coordinates
boolean[][] points = new boolean[5][20] ;
Define one Y point on each X axis
points[0][5] = true ;
points[1][6] = true ;
points[2][7] = true ;
points[3][8] = true ;
points[4][9] = true ;
Add a for loop to iterate through the first array index, adding a newline character at the
end of each iteration
for ( int i = 0 ; i < points.length ; i++ )
{
System.out.print( “\n” ) ;
}
Within the curly brackets of the for loop, insert a second for loop to iterate through the second array index
for ( int j = 0 ; j < points[0].length ; j++ ) { }
Within the curly brackets of the second for loop, insert a statement to output a character for each element according to that
element’s Boolean value
char mark = ( points[i][j] ) ? ‘X’ : ‘-’ ;
System.out.print( mark ) ;
Save the program as Dimensions.java then compile and run the program to see the output
Boolean variables are false by default.
Catching exceptions
A program may encounter a runtime problem that causes an “exception” error, which halts its execution. Often, this will be created by unexpected user input. A well-written program should, therefore, attempt to anticipate all possible ways the user might cause exceptions at runtime.
Code where exceptions might arise can be identified and enclosed within a try catch statement block. This allows the program to handle exceptions without halting execution and looks like this:
try
{
statements where an exception may arise
}
catch( Exception e )
{
statements responding to an exception
}
The parentheses following the catch keyword specify the class of exception to be caught and assign it to the variable “e”. The top-level Exception class catches all exceptions. Responses can be provided for specific exceptions, however, using multiple catch statements to identify different lower-level exception classes.
The most common exceptions are the NumberFormatException, which arises when the program encounters a value that is not of the expected numeric type, and the ArrayIndexOutOfBoundsException, which arises when the program attempts to address an array element number that is outside the index size. It is helpful to create a separate response for each of these exceptions to readily notify the user about the nature of the problem.
Optionally, a try catch statement block can be extended with a finally statement block, containing code that will always be executed – irrespective of whether the program has encountered exceptions.
The e.getMessage() method returns further information about some captured exceptions.
Start a new program named “Exceptions” containing the standard main method
class Exceptions
{
public static void main ( String[] args ) { }
}
Exceptions.java
Inside the main method, write a try statement to output a single integer argument
try
{
int num = Integer.parseInt( args[0] ) ;
System.out.println( “You entered: “+ num ) ;
}
Add a catch statement to handle the exception that arises when the program is run without an
argument
catch( ArrayIndexOutOfBoundsException e )
{ System.out.println( “Integer argument required.” ) ; }
Add a catch statement to handle the exception that arises when the program is run with a non-integer
argument
catch( NumberFormatException e )
{ System.out.println( “Argument is wrong format.” ) ; }
Add a finally statement at the end of the program
finally { System.out.println( “Program ends.” ) ; }
Save the program as Exceptions.java then compile and run the program, trying to cause exceptions
Summary
•Numeric values can be converted to other numeric data types by casting, and to the String type using the toString() method.
•A String value can be converted to an int value using the Integer.parseInt() method, and to a float using Float. parseFloat().
•An array is a variable that can contain multiple values, initialized as a list within curly brackets in its declaration.
•An empty array object can be created using the new keyword.
•The length property of an array stores an integer, which is the number of elements in that array.
•Each element of an array can be addressed by its index number.
•A program’s main method creates a String array, traditionally named “args”, to store command line arguments.
•The first command line argument gets automatically stored in the args[0] element – as a String data type.
•Multiple arguments being passed to a program from the command line must each be separated by a space.
•Loops are an ideal way to read all the values stored within array elements.
•Data from multiple arrays can be combined to form a new array of totaled data in each element.
•Multi-dimensional arrays can store multiple sets of element values, each having their own index dimension.
•A try catch statement block is used to anticipate and handle runtime exceptions that may arise.
•The Exception class catches all exception errors, including NumberFormatException and ArrayIndexOutOfBoundsException.
•A try catch statement can be extended with a finally statement block, containing code that will always be executed.