Professional Documents
Culture Documents
ARRAYS
PROGRAMMING 2
COMP 112
Introduction
2
int[][] a = {{1,2,3},
{4,5,6}};
for (int row=0; row < a.length; row++){
for (int col=0; col < a[row].length; col++){
a[row][col] = a[row][col] * 2;
}
}
int[][] a = {{1,2,3},
{4,5,6}};
for (int row=0; row < a.length; row++){
for (int col=0; col < a[row].length; col++){
a[row][col] = a[row][col] * 2;
} [0] [1] [2]
} row = 2 a = [0] 2 4 6
[1] 8 10 12
● Below is the list of important built-in exceptions in Java used to avoid the
Error in the Array:
ArrayIndexOutOfBoundsException
o It is thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the size
of the array.
class AOBExceptionTest {
public static void main(String args[]) {
try {
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
} // output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
}
Programming 2 COMP 112 Spring 20-21
Exception Handling – part 3
13
NegativeArraySizeException:
NegativeArraySizeException occurs whenever an
application tries to create an array with negative size.
For example, when we assigned the negative size to an
array:
//Here the array size is -10:
//int[] arr = new int[-10];
public class NASExceptionTest {
public static void main(String[] args) {
int[] arr=new int[-10];
}
}
// output: Exception in thread "main“ java.lang.NegativeArraySizeException