Question: ArrayTest.java(attached in Moodle) provides an example on coding array basics initialize an array with predetermined values access array elements, and stay within the bounds of
ArrayTest.java(attached in Moodle) provides an example on coding array basics
- initialize an array with predetermined values
- access array elements, and
- stay within the bounds of an array
- Compile and execute this program. Attach the execution results in Moodle
- Explain in your words the reason for the exception encountered
public class ArrayTest
{
public static void main(String args[])
{
// 1.declare an array
double target[] = new double[3];
double source[] = {1.0, 5.5, 7.9};
int loopIndex;
// 2.initialize the array - Copy values from source to target.
for(loopIndex = 0; loopIndex < 3; loopIndex++)
target[loopIndex] = source[loopIndex];
// 3.Assign values to two elements of target.
target[0] = 2.0;
target[1] = 4.5;
// Print values stored in source and target.
for(loopIndex = 0; loopIndex < 3; loopIndex++) {
System.out.println("Source " + source[loopIndex]);
System.out.println("Target " + target[loopIndex]);
}
// 4.Encounter ArrayException due to change loopIndex <= 3
System.out.println("======== ARRAY EXCEPTION BELOW ==========");
for(loopIndex = 0; loopIndex <= 3; loopIndex++)
{
System.out.println("Source " + source[loopIndex]);
System.out.println("Target " + target[loopIndex]);
}
} }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
