Java Reference
In-Depth Information
printPerson(employee);
}
public static void printPerson(Person myPerson){
System.out.println(myPerson.name + " is " + myPerson.age +
" years old and works as a " + myPerson.job.JobName);
}
}
class Person{
String name;
int age;
JobType job;
Person (String name, int age, JobType job){
this.name = name;
this.age = age;
this.job = job;
}
}
class JobType{
String JobName;
int salaryBand;
JobType (String name, int band){
JobName = name;
salaryBand = band;
}
}
Another common exception is index out of bounds. This occurs when you have an indexed object,
such as an array, and you try to access an element outside the limits of the array. As you've already
seen, arrays are indexed starting from 0, so the last element is one less than the size of the array. For
example, an array of size 5 has elements indexed at 0, 1, 2, 3, and 4. It is important to consider this,
for example, when looping through the elements of an array.
public class IndexExceptionExample {
public static void main(String[] args) {
int[] hoursWorked = {7,8,7,9,5};
int totalHours = 0;
for (int i = 0; i <= hoursWorked.length; i++){
totalHours += hoursWorked[i];
}
System.out.println("Total Hours = " + totalHours);
}
}
Search WWH ::




Custom Search