What We Will Cover
Continuations
Homework Questions?
Where to Place the File Comment Block
Questions from last class?
Which of the following can be an argument in a method call?
- Constants
- Variables
- Expressions
- All of the above
Given a single Java class, which of the following methods can it have?
foo(int a)
foo(int a, int b)
foo(double a)
foo(double a, double b)
foo(int b)
^ top
7.1: Overloading Method Names
Objectives
At the end of the lesson the student will be able to:
- Code overloaded methods
- Describe how Java resolves method calls
- Describe when to overload methods
|
^ top
7.1.1: About Overloading
- You can have several methods with the same name in a class
- Need different parameter set (i.e. signature) for each method
- Number of parameters
- Parameter types
- Order of parameters
- Return type is not part of the signature
- Cannot be used to distinguish between two methods with the same name and signature
For Example
public class SquareTypes {
public static void main(String[] args) {
System.out.println(square(6.5));
System.out.println(square(5));
}
static double square(double x) {
System.out.print("Using type double: ");
return x * x;
}
static int square(int x) {
System.out.print("Using type int: ");
return x * x;
}
}
First call to square uses method with a double signature
Second call uses method with an int signature
Using type double: 42.25
Using type int: 25
^ top
7.1.2: Overloading Resolution
- Method call resolution:
- Looks for exact signature
- Looks for 'compatible' signature
- First: looks for exact signature
- Because no argument conversion required
- Second: looks for 'compatible' signature
- Where automatic type conversion is possible:
- Recall that Java automatically converts types as follows:
byte => short => int => long => float => double
/
char =/
For Example
- Given following methods:
void f(int n, double m) {}
void f(double n, int m) {}
void f(int n, int m) {}
- Making these calls:
f(98, 99); => Calls 3
f(5.3, 4); => Calls 2
f(5, 4.2); => Calls 1
f(4.3, 5.2); => Compiler error
^ top
7.1.3: Automatic Type Conversion and Overloading
- Typically you should make numeric formal parameters of type
double
- Allows for any numeric type
- Any narrower data type automatically is promoted to wider types
byte => short => int => long => float => double
/
char =/
Avoids overloading because of different numeric types
For Example
double mpg(double miles, double gallons) {
return (miles / gallons);
}
Example method calls:
mpgComputed = mpg(5, 20);
- Converts 5 and 20 to doubles, then passes them to the method
mpgComputed = mpg(5.8, 20.2);
mpgComputed = mpg(5, 2.4);
- Converts 5 to 5.0, then passes the values to the method
^ top
7.1.4: Overloading for Default Arguments
- You can use overloading to omit some arguments
- For example:
void showVolume(int length, int width, int height) {
// Do something
}
Want to provide default values for the last 2 arguments
Create 2 additional method calls
Each method calls the full method with default values
void showVolume(int length, int width) {
showVolume(length, width, 1);
}
void showVolume(int length) {
showVolume(length, 1, 1);
}
Possible calls:
showVolume(1, 2, 3); // All arguments supplied
showVolume(1, 2); // height defaulted to 1
showVolume(1); // width & height defaulted to 1
^ top
7.1.5: Summary
- A programmer can declare many methods using the same name
- However, the parameter list must be different between each method
- Useful when you want to have the same method operate on different data types
- However, you can avoid overloading by relying on automatic type conversion
- Java automatically promotes values from narrow to broad types
- By making your numeric types double, you can use promotion instead of overloading
- Another use of overloading is for default arguments
- Allows method calls with default arguments
^ top
Exercise 7.1
With a partner, if needed, take 5 minutes to complete the following:
- Start a text file named exercise7.txt.
- Prepare the exercise header as described in the HowTo on submitting exercises
- Label this exercise: Exercise 7.1
- Submit all exercises for this lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in exercise7.txt.
Specifications
- Suppose you have two methods:
double score(double time, double distance) {}
double score(double points) {}
Which method would be used in the following method call? Why?
double finalScore = score(95.7);
- Suppose you have two methods:
double answer(double data1, double data2) {}
double answer(double time, int count) {}
Which method would be used in the following method call? Why?
int y = 5;
double x = answer(y, 6.0);
^ top
7.2: Input Validation
Objectives
At the end of the lesson the student will be able to:
- Validate user input
- Handle input exceptions
|
^ top
7.2.1: Validating User Input
- Well-constructed programs validate user input
- You need to ensure that programs do not crash due to unexpected input
- Referred to as robust or "bullet-proof" programs
- To demonstrate, let us create a program to sum two numbers
- We will need three dialog boxes:
- Enter first number
- Enter second number
- Display results
- Here is a first draft of a program:
import javax.swing.*;
public class SumOf2Dialog {
public static void main(String[] args) {
double num1, num2;
String input, output;
input = JOptionPane.showInputDialog("First number:");
num1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("Second number:");
num2 = Double.parseDouble(input);
output = "" + num1 + " + " + num2 + " = "
+ (num1 + num2);
JOptionPane.showMessageDialog(null, output);
System.exit(0);
}
}
- When you run it, you will notice several errors
- Pressing the Cancel button produces a
NullPointerException
- You can prevent a
NullPointerException by testing the input string
if (input == null) {
// do something about the error
}
However, we can generate other error conditions as well
Pressing the Enter key before typing any input produces an error
Entering letters instead of numbers produces an error as well
These errors are more difficult to detect using conditional statements
Instead, you can use a Java mechanism known as exception handling
^ top
7.2.2: Errors and Exceptions
- Java handles errors quite differently than older high-level languages
- Traditional approach is to require each method to return error codes
- Must return specific values to indicate failures
- Many possible problems with this approach:
- Requires the programmer to check for the error code to find if an error occurred
- Error handling becomes intermixed with normal processing code
- Becomes more difficult to understand how the codes is supposed to work
- Error conditions must be the same type as the normal code return type
- Error code must be a special value
- All these problems can be solved
- More elegant approach is to use exception handling
Terminology
- Exception: an error condition that changes the normal flow of a program
- Throw an exception: either the Java runtime or your code signals that something unusual happened
- Catch an exception: take appropriate action to deal with an exception
- Exception handler: the code that processes an exception
Exception Handling Program Flow
- When an error occurs while a method is executing:
- Method stops processing at the failures point
- Creates and object with the error information
- Passes the exception object to the JVM
- JVM tries to locate the exception handling code
- If code cannot be found, the general exception handler is used
- General exception handler produces an error messages on the console
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:394)
at java.lang.Integer.parseInt(Integer.java:476)
at DivideDialog.main(DivideDialog.java:10)
- Note that the purpose of exception handling is not to reduce debugging time
- Purpose of exception handling is to simplify the code for normal circumstances
- However, general exception handler does provide information about where an error occurred
Types of Exceptions
- Two types of exceptions in Java
- Checked Exception: programmer must write code to deal with the exception
- Compiler "checks" to make sure you process the exception
- Unchecked Exception: programmer decides whether or not to deal with the exception
- No checks are made by the compiler
^ top
7.2.3: Throwing an Exception
- Easiest way to deal with an exception is to throw the exception to the caller
- Throwing an exception is like passing the buck
- Requires the calling method to deal with the exception
- The calling method can also throw the exception
- Eventually some method should catch it
- Otherwise the general exception handler is used
- General syntax for throwing an exception:
returnType methodName(parameterList) throws Exception1,... {
// method body
}
- Can also throw an exception from the
main method
public static void main(String[] args) throws IOException
- Throwing from
main() invokes the general exception handler
- Produces an ugly (but useful to programmers) error message
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:394)
at java.lang.Integer.parseInt(Integer.java:476)
at DivideDialog.main(DivideDialog.java:10)
For Example
- Recall our LineInput program from lesson 4.1.3:
import java.io.*;
public class LineInput {
public static void main(String[] args) throws IOException {
// set up for basic input stream
InputStreamReader isr = new InputStreamReader(System.in);
// need to use readLine()
BufferedReader br = new BufferedReader(isr);
System.out.print("Type a line and press Enter: ");
String data = br.readLine();
System.out.println("You entered: " + data);
}
}
- Note the
throws IOException clause
- Allows us to run the program without having to handle the exception
^ top
7.2.4: Handling Exceptions
- Another way to deal with an exception is to write exception handling code
- Using exception handling, you can correct errors without ending your program
- Handling exceptions means you need to code
try-catch statements
General Code Organization:
try {
// One or more statements at least one of which
// must be capable of throwing an exception
} catch (Exception e) {
// Exception handling code
// Can have many catch blocks
}
Programming style: note the placement of the curly braces
Try Block
- Keyword
try identifies the start of an exception handling block
- Must have at least one statement that could generate exceptions
Catch Block
- A
try block must be followed by one or more catch blocks
- Executes only if an exception is thrown
- The type of the exception is the type shown in the error messages
For Example
- Adding exception handling to the
SumOf2Dialog program
import javax.swing.*;
public class SumOf2Dialog2 {
public static void main(String[] args) {
double num1, num2;
String data, output;
try {
data = JOptionPane.showInputDialog(
"First number:");
num1 = Double.parseDouble(data);
data = JOptionPane.showInputDialog(
"Second number:");
num2 = Double.parseDouble(data);
output = "" + num1 + " + " + num2 + " = "
+ (num1 + num2);
JOptionPane.showMessageDialog(null, output);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"You must enter a number",
"Input Data Error",
JOptionPane.ERROR_MESSAGE);
} catch (NullPointerException e) {
JOptionPane.showMessageDialog(null,
"You pressed the Cancel button",
"Program Termination",
JOptionPane.ERROR_MESSAGE);
}
System.exit(0);
}
}
- What types of exceptions do we catch in the above code?
^ top
7.2.5: Validating Input
- Even though the above program is robust, we can still make improvements
- One thing it does not do is allow users to correct their errors
- User-friendly programs should give users a chance to correct errors
- One way to accomplish this is use a loop
- Following code adds a retry loop to the
SumOf2Dialog program
import javax.swing.*;
public class SumOf2Dialog3 {
public static void main(String[] args) {
double num1, num2;
String data, output;
boolean tryAgain = true;
while (tryAgain == true) {
try {
data = JOptionPane.showInputDialog(
"First number:");
num1 = Double.parseDouble(data);
data = JOptionPane.showInputDialog(
"Second number:");
num2 = Double.parseDouble(data);
output = "" + num1 + " + " + num2 + " = "
+ (num1 + num2);
JOptionPane.showMessageDialog(null, output);
tryAgain = false;
} catch (NullPointerException e) {
JOptionPane.showMessageDialog(null,
"You pressed the Cancel button",
"Program Termination",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"You must enter a number",
"Input Data Error",
JOptionPane.ERROR_MESSAGE);
}
}
System.exit(0);
}
}
- Condition for the loop uses the variable
tryAgain
- Shorthand for
tryAgain == true
- Note that
tryAgain is set to true before entering the loop
tryAgain is set to false only when you do not want the user to try again
- In this example, user has to enter both numbers when trying again
- This is inconvenient for the user
- A better way is to use a method for the input
^ top
7.2.6: Input Validation Methods
- We can still improve the previous code
- Some problems that remain are:
- The main method is very long
- The code is not portable easily from one program to another
- The user has to reenter data for all the inputs
- Two solve these problems, we put our data entry code into a separate method
- Notice how much shorter the main method has become
import javax.swing.*;
public class SumOf2Dialog4 {
public static void main(String[] args) {
double num1, num2;
String output;
num1 = inputDouble("First number:");
num2 = inputDouble("Second number:");
output = "" + num1 + " + " + num2 + " = "
+ (num1 + num2);
JOptionPane.showMessageDialog(null, output);
System.exit(0);
}
public static double inputDouble(String prompt) {
String data;
double num = 0.0;
boolean tryAgain = true;
while (tryAgain) {
try {
data = JOptionPane.showInputDialog(prompt);
if (data == null) {
JOptionPane.showMessageDialog(null,
"You pressed the Cancel button",
"Program Termination",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
num = Double.parseDouble(data);
tryAgain = false;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"You must enter a number",
"Input Data Error",
JOptionPane.ERROR_MESSAGE);
}
}
return num;
}
}
- Note that the code separates the input validation from the main processing
- Makes the code easier to read and understand
^ top
7.2.7: Summary
- Well-constructed programs validate user input
- Can detect many conditions using conditional statements
if (data == null) {
// do something about the error
}
Not all conditions are easy to check
Java provides a more elegant solution known as exception handling
Code to check is placed in a try block
Error handling code is placed in a catch block
try {
// One or more statements at least one of which
// should be capable of throwing an exception
} catch (Exception e) {
// Exception handling code
// Can have many catch blocks
}
Input validation may need both exception handling and condition checking
When to use each depends on the types of error conditions that are possible
Placing input handling code in a method can make the main code easier to understand
^ top
Exercise 7.2
- Label this exercise: Exercise 7.2
- Complete the following and record the answer to any questions in your
exercise4.txt file.
Specifications
- Using the input methods we reviewed above, write a program that asks for two
double values and displays their product. The product is the number obtained by multiplying two numbers together.
- Submit your final program along with your exercise7.txt file.
- Record answers to the following questions in exercise7.txt.
Q1: What happens when a user enters the words "bad data" rather than a number?
You can use the following code to get started.
import javax.swing.*;
public class SumOf2Dialog4 {
public static void main(String[] args) {
double num1, num2;
String output;
num1 = inputDouble("First number:");
num2 = inputDouble("Second number:");
output = "" + num1 + " + " + num2 + " = "
+ (num1 + num2);
JOptionPane.showMessageDialog(null, output);
System.exit(0);
}
public static double inputDouble(String prompt) {
String data;
double num = 0.0;
boolean tryAgain = true;
while (tryAgain) {
try {
data = JOptionPane.showInputDialog(prompt);
if (data == null) {
JOptionPane.showMessageDialog(null,
"You pressed the Cancel button",
"Program Termination",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
num = Double.parseDouble(data);
tryAgain = false;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"You must enter a number",
"Input Data Error",
JOptionPane.ERROR_MESSAGE);
}
}
return num;
}
}
^ top
7.3: Arrays
Objectives
At the end of the lesson the student will be able to:
- Declare and allocate memory for arrays
- Write code to initialize arrays
- Access array elements
|
^ top
Array: a single name for a collection of identically-typed data values
- Arrays are a type of data structure
-- a way to organize data
- An array is used to process a collection of data of the same type
- Why do we need arrays?
- Imagine keeping track of 5 test scores, or 100, or 1000 in memory
- How would you name all the variables?
- How would you process each of the variables?
- Arrays provide a convenient solution to these problems
- Entire array referred to by a single identifier
- Each element uniquely identified by an index number
For Example
- One-dimensional array is like single row of data in spreadsheet or table
score[0] |
score[1] |
score[2] |
score[3] |
score[4] |
| 90 |
95 |
87 |
89 |
98 |
- Top row shows the indices for an array named "
score"
- Individual items are referenced by the index (a.k.a. subscript)
- All the values are of the same type:
int
- Array length is 5
^ top
7.3.2: Declaring and Allocating Arrays
- Consider an array named
score containing 5 values
- You declare and allocate memory for this array like this:
int[] score; // declaration
score = new int[5]; // allocation
Which is equivalent to:
int[] score = new int[5]; // Java style
Which is equivalent to:
int score[] = new int[5]; // C++ style
This is like declaring 5 variables of type int numbered as follows:
score[0], score[1], score[2], score[3], score[4]
The value in brackets is called an index or subscript
Individual values in an array are called items or elements
The number of indexed variables in an array is the size of the array
- The largest index is one less than the size
- The first index value is zero
Array declaration syntax:
DataType[] arrayName = new DataType[length];
Arrays can be of any data type
All the variables of an array are always of the same data type
- Known as the base type of the array
Allocated dynamically with operator new
Once created, you cannot change the number of elements
Reference Types
- Arrays assignments are different than for primitive types
- Arrays names are reference types because arrays are objects in Java
- For instance:
double[] prices;
prices = new double[6];
First line declares a reference variable of type array-of-doubles
Second line creates an array object in memory and assigns the location to the prices reference variable

^ top
7.3.3: Referencing Array Elements
- Each array element is referenced by name and an index inside of square brackets
score[3] is one of the indexed variables of the score array
score[0]++;
The index can be any integer expression
int n = 2;
score[n + 1] = 99;
You can use an indexed array variable like any regular variable
score[0] = score[1] + 1;
- Array elements referenced by the array name and index
- Use the array operator
[] to specify the index
- Index must be an integer expression
^ top
7.3.4: Initializing Array Values
- You can assign a value to an array element any time after it is declared
int[] score = new int[5];
score[0] = 90;
score[1] = 95;
score[2] = 87;
score[3] = 89;
score[4] = 98;
Static Initialization
- You can also initialize array elements in the declaration statement
- Called static initialization
- Use a comma-separated list inside curly-braces
int[] score = {90, 95, 87, 89, 98};
Produces the same array
Length of an array automatically determined from the initializer list
Default Values
- Uninitialized array elements are assigned default values:
- Integer (
byte, short, int, long): 0
- Floating-point (
float, double): 0.0
- Character (
char): '\u0000'
- Boolean:
false
- Objects:
null
^ top
7.3.5: Processing Array Values in a Loop
- Array processing is easily done in a loop
- A
for loop is commonly used to process array elements
- For example, to initialize array elements to a known value:
int[] score = new int[5];
for (int i = 0; i < score.length; i++) {
score[i] = 100;
}
Note the use of the constant length in the array loop
Initializing From the Keyboard
- We can also use a loop to initialize values from the keyboard
String input = JOptionPane.showInputDialog(
"How many scores?");
int numScore = Integer.parseInt(input);
int[] score = new int[numScore];
for (int i = 0; i < score.length; i++) {
input = JOptionPane.showInputDialog(
"Enter score " + i + ": ");
score[i] = Integer.parseInt(input);
}
Note that the loop counter and array index counts from 0 to length - 1
Displaying an Array
- Similarly, we can also use a loop to display the contents of an array
System.out.println("You entered:");
for (int i = 0; i < score.length; i++) {
System.out.println(score[i]);
}
^ top
7.3.6: Array Index Out of Range
- A common error is using a nonexistent index
- Index values for int
score[5] are the values 0 through 4
- An index value not allowed by the array declaration is out of range
- Using an out of range index value produces an error message!
ArrayIndexOutOfBoundsException
For example, using the following code:
public class WeekDays {
public static void main(String[] args) {
String[] day = {"Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"};
for (int x = 0; x < day.length; x++) {
System.out.println(day[x]);
}
}
}
Trying to use an index less than 0 or more than length - 1 causes an error
ArrayIndexOutOfBoundsException
^ top
7.3.7: Summary
- Arrays are convenient ways to process a list of data
- You declare an array with a single statement:
DataType[] arrayName = new DataType[length];
Each array element is referenced by name and an index inside of square brackets
You can use an indexed array variable like any regular variable
score[0] = score[1] + 1;
You can initialize array elements individually with an assignment statement
score[0] = 90;
A more convenient way is to use an initializer list
int score[] = {90, 95, 87, 89, 98};
You can use loops to assign values to an array and to display array values
String input = JOptionPane.showInputDialog(
"How many scores?");
int numScore = Integer.parseInt(input);
int[] score = new int[numScore];
for (int i = 0; i < score.length; i++) {
input = JOptionPane.showInputDialog(
"Enter score " + i + ": ");
score[i] = Integer.parseInt(input);
}
System.out.println("You entered:");
for (int i = 0; i < score.length; i++) {
System.out.println(score[i]);
}
The programmer must be very careful to keep the array index within bounds
Otherwise an error message will result
^ top
Exercise 7.3
With a partner, if needed, take 5 minutes to complete the following:
- Start a text file named exercise7.txt.
- Prepare the exercise header as described in the HowTo on submitting exercises
- Label this exercise: Exercise 7.3
- Submit all exercises for this lesson in one file unless instructed otherwise
- Write array declaration and allocation statements for the following descriptions and record them in your exercise7.txt file.
Array Descriptions
- A list of 100 integer grades
- A list of 25 characters
- A list of 50 double-precision values holding temperatures
- A list of 90 Strings holding names
^ top
7.4: Arrays and Methods
Objectives
At the end of the lesson the student will be able to:
- Pass arrays elements as arguments
- Pass entire arrays as arguments
- Use arrays in methods
- Return arrays from methods
- Obtain values from the array passed to the
main method
|
^ top
7.4.1: Array Elements as Arguments
- Indexed variables can be arguments to methods
- For example, if a program contains these declarations:
public static void main(String[] args) {
int i = 0, a[] = new int[10];
}
static void myMethod(int n) { /* some code */ }
You can use indexed variables a[0] through a[9] as arguments
myMethod(a[0]);
myMethod(a[3]);
myMethod(a[i]);
For Example
import java.text.NumberFormat;
public class ArrayItemApp {
public static void main(String[] args) {
double[] data = {12.3, 23.45, 3.456};
for (int i = 0; i < data.length; i++) {
showPrice(data[i]);
}
}
/**
* Displays a double to the screen
*/
static void showPrice(double value) {
NumberFormat currency =
NumberFormat.getCurrencyInstance();
String formattedItem = currency.format(value);
System.out.println(formattedItem);
}
}
^ top
7.4.2: Arrays as Method Parameters
- You can use an entire array as an argument to a method
- When calling the array, use just the array name and no brackets
showArray(days);
Method has access to the original array
Following example shows an array used in a method:
static void showArray(String[] values) {
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
}
You do not know the length of the array that will be passed
Length of the array passed can be different for each method call
So use the length variable inside the method body
You could easily overload the showArray method for different array types
^ top
7.4.3: Changing Array Elements in Methods
- All types in Java are passed-by-value (a.k.a. call-by-value)
- When method is called, value of each argument is copied to its corresponding parameter
- Method only gets a copy of the variable's value
- Variables used as arguments cannot be changed within the method
- However, arrays are objects and a variable contains reference values
- Location of the array is passed to the method
- Any action taken on the parameter is actually taken on the original argument
- Original argument is not protected for class types
- Thus array elements can be changed in methods
- You can even collect input in a method for an array

For Example:
import javax.swing.*;
public class ArrayFiller {
public static final int NUMBER_ITEMS = 3;
public static void main(String[] args) {
int[] data = new int[NUMBER_ITEMS];
fillUp(data);
showArray(data);
System.exit(0);
}
// Fills an array with values from the keyboard
static void fillUp(int data[]) {
String input, msg = "Enter number ";
for (int i = 0; i < data.length; i++) {
input = JOptionPane.showInputDialog(msg
+ (i + 1));
data[i] = (int) Double.parseDouble(input);
}
}
// Displays an array to the screen
static void showArray(int[] values) {
String msg = "You entered " + values.length
+ " numbers:\n";
for (int i = 0; i < values.length; i++) {
msg += values[i] + "\n";
}
JOptionPane.showMessageDialog(null, msg);
}
}
^ top
7.4.4: Returning an Array
- Methods can return an array reference
- Local array name just another name for the original array
- For example:
public class ArrayMaker {
public static void main(String arg[]) {
char[] c;
c = vowels();
for(int i = 0; i < c.length; i++)
System.out.println(c[i]);
}
public static char[] vowels() {
char[] newArray = new char[5];
newArray[0] = 'a';
newArray[1] = 'e';
newArray[2] = 'i';
newArray[3] = 'o';
newArray[4] = 'u';
return newArray;
}
}
^ top
7.4.5: Method main Parameters
public static void main(String[] args) {
Recall that every Java application must have a method called main
- Applications begin executing at
main method
Notice that the parameter args is an array of Strings
Arguments are passed to the program by the operating system
All words after the class name passed in the args array
java ArgEcho Java Rules!
Number of parameters can be determined from args.length
System.out.println(args.length);
args is a parameter of type String[]
Parameter String[] is an array of Strings
Parameters are passed when calling the program
Name args is a convention -- can be named anything
Number of parameters can be determined from the length field of args
For Example
class ArgEcho {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.print("Arg " + i + ": ");
System.out.println(args[i]);
}
}
}
Produces the output:
>java EchoArgs Hi Mom!
Arg 0: Hi
Arg 1: Mom!
^ top
7.4.6: Summary
- Can pass an array to a method
- A method may return an array
- Can change the array element within a method body
- Because arrays are reference types
- Location of the array passed to the method
- When an element is accessed, the original location is used
- Operating system sends arguments to the
String[] parameter of method main
- Can access these elements like any other array
^ top
Exercise 7.4
- Label this exercise: Exercise 7.4
- Submit all exercises for this lesson in one file unless instructed otherwise
- Complete the following and record the answers to any questions in exercise7.txt.
Specifications
- The following declarations were used to create an array:
final int NUMGRADES = 500;
double[] grades = new double[NUMGRADES];
Write a method header for a method named sortArray that accepts grades as a parameter. Record your solution in exercise7.txt.
- Write a method named
oneMore which has a parameter for an array of int's and adds one to each element of the array. Use the following starter code to get started and submit your solution along with these exercises.
public class OneMoreApp {
public static void main(String[] args) {
int[] a = {0, 2, 4, 6, 8};
showArray(a);
}
// Displays an array to the screen
static void showArray(int[] values) {
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
}
}
^ top
Wrap Up
^ top
Home
| WebCT
| Announcements
| Schedule
| Expectations
| Course info
Help
| FAQ's
| HowTo's
| Links
Last Updated: October 12 2004 @16:49:36
|