Java Arrays and Exceptions Study Guide¶
For Adult Learners New to Programming
Table of Contents¶
Arrays Basics¶
What is an Array?¶
An array is like a container that holds multiple items of the same type, arranged in a sequence. Think of it as an organized collection where each item has its own numbered spot.
Real-World Analogies¶
1. Egg Carton Analogy¶
graph TD
A[Egg Carton = Array]
A --> B[12 Fixed Spaces]
A --> C[Same Type Items]
A --> D[Numbered Positions]
B --> E[Fixed Size]
C --> F[Only Eggs]
D --> G[Position 0-11]
Comparison to Arrays:
- Fixed number of spaces (fixed array size)
- Each spot holds one egg (one element per index)
- Spots are numbered (array indices)
- Can only hold eggs (same data type)
// Java equivalent of an egg carton
Egg[] eggCarton = new Egg[12];
eggCarton[0] = new Egg("Brown"); // First position
eggCarton[11] = new Egg("White"); // Last position
2. Parking Lot Analogy¶
graph LR
A[Parking Lot = Array] --> B[Numbered Spaces]
A --> C[Car Storage]
A --> D[Space Status]
B --> E[0 to N-1]
C --> F[One Car Per Space]
D --> G[Empty/Occupied]
Comparison to Arrays:
- Numbered parking spaces (array indices)
- Each space can hold one car (one element)
- Fixed number of spaces (fixed size)
- Can track if occupied (boolean array)
// Java equivalent of a parking lot
boolean[] parkingSpaces = new boolean[100]; // 100 parking spaces
String[] parkedCars = new String[100]; // Store car license plates
// Park a car
parkingSpaces[5] = true; // Space 6 is now occupied
parkedCars[5] = "ABC123"; // Car with plate ABC123 in space 6
3. Weekly Pill Organizer¶
graph TD
A[Pill Organizer = Array]
A --> B[7 Daily Compartments]
A --> C[Ordered Sequence]
A --> D[Daily Access]
B --> E[Fixed Compartments]
C --> F[Monday to Sunday]
D --> G[One Day at a Time]
Comparison to Arrays:
- 7 fixed compartments (fixed size array)
- Days are in sequence (ordered indices)
- Each compartment holds pills for one day (elements)
- Access by day (index access)
// Java equivalent of a pill organizer
int[] dailyPillCount = new int[7]; // Pills per day
String[] daysOfWeek = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
// Set pills for Monday
dailyPillCount[0] = 3; // 3 pills on Monday
4. School Locker Row¶
graph LR
A[Locker Row = Array]
A --> B[Sequential Numbers]
A --> C[Individual Storage]
A --> D[Same Size Lockers]
B --> E[Easy Location]
C --> F[One Student Per Locker]
D --> G[Uniform Content Type]
Comparison to Arrays:
- Numbered sequentially (array indices)
- One student per locker (one element per index)
- All lockers same size (same data type)
- Fixed number of lockers (fixed array size)
// Java equivalent of school lockers
String[] lockers = new String[100]; // 100 lockers
boolean[] lockerOccupied = new boolean[100];
// Assign locker to student
lockers[15] = "John Smith"; // Locker 16 assigned to John
lockerOccupied[15] = true; // Marked as occupied
5. Monthly Calendar¶
graph TD
A[Calendar = Array]
A --> B[Fixed Days]
A --> C[Sequential Order]
A --> D[Daily Events]
B --> E[28-31 Days]
C --> F[Day 1 to Day 31]
D --> G[Events Per Day]
Comparison to Arrays:
- Fixed number of days (fixed size)
- Days are numbered (indices)
- Each day can hold events (elements)
- Sequential access (ordered indices)
// Java equivalent of a monthly calendar
String[] monthlyEvents = new String[31]; // 31 days
int[] eventCounts = new int[31]; // Number of events per day
// Add event to a day
monthlyEvents[0] = "Team Meeting"; // Event on day 1
eventCounts[0]++; // Increment event count for day 1
Key Concepts Illustrated by These Examples:¶
-
Fixed Size
-
Like an egg carton, arrays have a fixed size once created
-
Can't add extra spaces after creation
-
Same Type Elements
-
Like parking spaces designed for cars only
-
Arrays can only store elements of the same type
-
Sequential Access
-
Like numbered lockers in a row
-
Elements are stored in sequence and accessed by index
-
Zero-Based Indexing
-
Like a digital calendar where the first day is day 0
-
Array indices start at 0, not 1
-
Direct Access
-
Like going directly to locker #15
- Can access any element directly using its index
// Example demonstrating all concepts
public class ArrayConcepts {
public static void main(String[] args) {
// Fixed size - like a parking lot with 5 spaces
int[] spaces = new int[5];
// Same type - can only store integers
spaces[0] = 10; // Valid
// spaces[1] = "Car"; // Invalid - wrong type
// Sequential access - like checking each locker
for (int i = 0; i < spaces.length; i++) {
System.out.println("Space " + i + ": " + spaces[i]);
}
// Zero-based indexing - first position is 0
System.out.println("First space: " + spaces[0]);
// Direct access - like going straight to locker #3
spaces[3] = 25;
}
}
Key Concepts¶
- Declaration: Telling Java you want to create an array
- Creation: Actually setting aside memory for the array
- Initialization: Putting values into the array
Real-World Example: Student Grades¶
Let's say you're a teacher with 5 students. Instead of creating separate variables for each student's grade:
You can use an array:
Array Creation Flow¶
flowchart LR
A[Declaration] -->|int[] grades| B[Creation]
B -->|new int[5]| C[Initialization]
C -->|grades[0] = 95| D[Ready to Use]
style A fill:#f9f,stroke:#333
style B fill:#bbf,stroke:#333
style C fill:#bfb,stroke:#333
style D fill:#fbb,stroke:#333
Array Processing¶
Accessing Array Elements¶
- Array elements are accessed using an index
- Index starts at 0 (not 1!)
- Last index is array length - 1
Real-World Example: Temperature Tracking¶
Tracking daily temperatures for a week:
double[] weeklyTemps = new double[7];
// Store Monday's temperature
weeklyTemps[0] = 72.5;
// Store Tuesday's temperature
weeklyTemps[1] = 76.0;
Common Array Operations¶
graph TD
A[Array Operations] --> B[Reading Values]
A --> C[Writing Values]
A --> D[Looping Through Array]
B --> E[value = array[index]]
C --> F[array[index] = value]
D --> G[for loop]
D --> H[enhanced for loop]
style A fill:#f9f,stroke:#333
Real-World Array Examples¶
1. Monthly Budget Tracker¶
Track expenses and income over months using arrays.
public class MonthlyBudgetTracker {
private double[] monthlyExpenses;
private double[] monthlyIncome;
private String[] months = {
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
};
public MonthlyBudgetTracker() {
monthlyExpenses = new double[12];
monthlyIncome = new double[12];
}
// Add expense for a specific month
public void addExpense(int month, double amount) {
if (month < 0 || month > 11) {
throw new IllegalArgumentException("Invalid month");
}
monthlyExpenses[month] += amount;
}
// Calculate savings for each month
public double[] getMonthlySavings() {
double[] savings = new double[12];
for (int i = 0; i < 12; i++) {
savings[i] = monthlyIncome[i] - monthlyExpenses[i];
}
return savings;
}
// Print monthly report
public void printMonthlyReport() {
System.out.println("Monthly Budget Report");
System.out.println("===================");
for (int i = 0; i < 12; i++) {
System.out.printf("%s: Income: $%.2f, Expenses: $%.2f, Savings: $%.2f%n",
months[i], monthlyIncome[i], monthlyExpenses[i],
monthlyIncome[i] - monthlyExpenses[i]);
}
}
}
2. Restaurant Table Management¶
Track table status and orders in a restaurant.
public class RestaurantManager {
private boolean[] tableOccupied;
private int[] numberOfGuests;
private double[] tableBills;
public RestaurantManager(int numberOfTables) {
tableOccupied = new boolean[numberOfTables];
numberOfGuests = new int[numberOfTables];
tableBills = new double[numberOfTables];
}
// Seat guests at a table
public boolean seatGuests(int guests) {
for (int i = 0; i < tableOccupied.length; i++) {
if (!tableOccupied[i]) {
tableOccupied[i] = true;
numberOfGuests[i] = guests;
return true;
}
}
return false; // No available tables
}
// Add items to table's bill
public void addToTableBill(int tableNumber, double amount) {
if (tableNumber >= 0 && tableNumber < tableBills.length) {
tableBills[tableNumber] += amount;
}
}
// Print restaurant status
public void printStatus() {
System.out.println("Restaurant Status");
System.out.println("=================");
for (int i = 0; i < tableOccupied.length; i++) {
System.out.printf("Table %d: %s | Guests: %d | Bill: $%.2f%n",
i + 1,
tableOccupied[i] ? "Occupied" : "Available",
numberOfGuests[i],
tableBills[i]);
}
}
}
3. Library Book Management¶
Track books and their availability status.
public class LibraryManager {
private String[] bookTitles;
private boolean[] isBookAvailable;
private String[] borrowers;
private String[] dueDate;
public LibraryManager(int numberOfBooks) {
bookTitles = new String[numberOfBooks];
isBookAvailable = new boolean[numberOfBooks];
borrowers = new String[numberOfBooks];
dueDate = new String[numberOfBooks];
// Initially all books are available
for (int i = 0; i < numberOfBooks; i++) {
isBookAvailable[i] = true;
}
}
// Borrow a book
public boolean borrowBook(int bookId, String borrower, String returnDate) {
if (bookId >= 0 && bookId < bookTitles.length && isBookAvailable[bookId]) {
isBookAvailable[bookId] = false;
borrowers[bookId] = borrower;
dueDate[bookId] = returnDate;
return true;
}
return false;
}
// Return a book
public void returnBook(int bookId) {
if (bookId >= 0 && bookId < bookTitles.length) {
isBookAvailable[bookId] = true;
borrowers[bookId] = null;
dueDate[bookId] = null;
}
}
}
4. Parking Lot Management¶
Track parking spaces in a parking lot.
public class ParkingLotManager {
private boolean[] parkingSpaces;
private String[] licensePlates;
private long[] parkingTimes;
public ParkingLotManager(int totalSpaces) {
parkingSpaces = new boolean[totalSpaces];
licensePlates = new String[totalSpaces];
parkingTimes = new long[totalSpaces];
}
// Park a car
public int parkCar(String licensePlate) {
for (int i = 0; i < parkingSpaces.length; i++) {
if (!parkingSpaces[i]) {
parkingSpaces[i] = true;
licensePlates[i] = licensePlate;
parkingTimes[i] = System.currentTimeMillis();
return i + 1; // Return parking spot number
}
}
return -1; // Parking lot full
}
// Calculate parking fee when car leaves
public double calculateFee(int spotNumber) {
if (spotNumber > 0 && spotNumber <= parkingSpaces.length) {
int index = spotNumber - 1;
long parkingDuration = System.currentTimeMillis() - parkingTimes[index];
double hours = parkingDuration / (1000.0 * 60 * 60);
return Math.ceil(hours) * 2.50; // $2.50 per hour
}
return 0.0;
}
}
5. Weather Station Data¶
Track temperature readings throughout the day.
public class WeatherStation {
private double[] hourlyTemperatures;
private double[] hourlyHumidity;
private double[] hourlyRainfall;
public WeatherStation() {
hourlyTemperatures = new double[24];
hourlyHumidity = new double[24];
hourlyRainfall = new double[24];
}
// Record weather data for specific hour
public void recordData(int hour, double temp, double humidity, double rainfall) {
if (hour >= 0 && hour < 24) {
hourlyTemperatures[hour] = temp;
hourlyHumidity[hour] = humidity;
hourlyRainfall[hour] = rainfall;
}
}
// Get daily statistics
public void printDailyReport() {
double totalTemp = 0, totalHumidity = 0, totalRain = 0;
double maxTemp = hourlyTemperatures[0];
double minTemp = hourlyTemperatures[0];
for (int i = 0; i < 24; i++) {
totalTemp += hourlyTemperatures[i];
totalHumidity += hourlyHumidity[i];
totalRain += hourlyRainfall[i];
maxTemp = Math.max(maxTemp, hourlyTemperatures[i]);
minTemp = Math.min(minTemp, hourlyTemperatures[i]);
}
System.out.printf("Daily Weather Report%n");
System.out.printf("Average Temperature: %.1f°C%n", totalTemp / 24);
System.out.printf("High Temperature: %.1f°C%n", maxTemp);
System.out.printf("Low Temperature: %.1f°C%n", minTemp);
System.out.printf("Average Humidity: %.1f%%%n", totalHumidity / 24);
System.out.printf("Total Rainfall: %.1fmm%n", totalRain);
}
}
6. Flight Booking System¶
Manage seat assignments on a flight.
public class FlightBookingSystem {
private boolean[] seatAvailability;
private String[] passengerNames;
private String[] passengerMeals;
public FlightBookingSystem(int totalSeats) {
seatAvailability = new boolean[totalSeats];
passengerNames = new String[totalSeats];
passengerMeals = new String[totalSeats];
}
// Book a seat
public int bookSeat(String passengerName, String mealPreference) {
for (int i = 0; i < seatAvailability.length; i++) {
if (!seatAvailability[i]) {
seatAvailability[i] = true;
passengerNames[i] = passengerName;
passengerMeals[i] = mealPreference;
return i + 1; // Return seat number
}
}
return -1; // Flight full
}
// Print seating chart
public void printSeatingChart() {
System.out.println("Flight Seating Chart");
System.out.println("===================");
for (int i = 0; i < seatAvailability.length; i++) {
System.out.printf("Seat %d: %s%n",
i + 1,
seatAvailability[i] ?
"Occupied by " + passengerNames[i] +
" (Meal: " + passengerMeals[i] + ")" :
"Available");
}
}
}
Usage Example¶
public class ArrayExamplesDemo {
public static void main(String[] args) {
// Demo Restaurant Management
RestaurantManager restaurant = new RestaurantManager(10);
restaurant.seatGuests(4);
restaurant.addToTableBill(0, 125.50);
restaurant.printStatus();
// Demo Weather Station
WeatherStation weatherStation = new WeatherStation();
weatherStation.recordData(12, 25.5, 65.0, 0.0);
weatherStation.recordData(13, 26.0, 63.0, 0.0);
weatherStation.printDailyReport();
// Demo Flight Booking
FlightBookingSystem flight = new FlightBookingSystem(100);
flight.bookSeat("John Doe", "Vegetarian");
flight.bookSeat("Jane Smith", "Regular");
flight.printSeatingChart();
}
}
Multidimensional Arrays¶
What is a Multidimensional Array?¶
Think of a multidimensional array as a table or grid where you need two or more numbers to locate an item, like:
- Row and column in Excel
- Seat number in a theater (row and seat)
- Coordinates on a map (latitude and longitude)
Real-World Example: Seating Chart¶
// Movie theater seating (rows x columns)
String[][] seating = new String[10][12];
// Assign seat A1
seating[0][0] = "Reserved";
Visualization of 2D Array¶
graph TD
A[2D Array] --> B[Row 0]
A --> C[Row 1]
A --> D[Row 2]
B --> E[Col 0]
B --> F[Col 1]
B --> G[Col 2]
C --> H[Col 0]
C --> I[Col 1]
C --> J[Col 2]
D --> K[Col 0]
D --> L[Col 1]
D --> M[Col 2]
Real-World Examples¶
1. Movie Theater Seating System¶
Manage seats in multiple theater halls.
public class MovieTheater {
private String[][] seats;
private double[][] seatPrices;
private boolean[][] seatOccupancy;
public MovieTheater(int rows, int seatsPerRow) {
seats = new String[rows][seatsPerRow];
seatPrices = new double[rows][seatsPerRow];
seatOccupancy = new boolean[rows][seatsPerRow];
// Initialize seat labels and prices
for (int i = 0; i < rows; i++) {
for (int j = 0; j < seatsPerRow; j++) {
// Create seat labels (A1, A2, B1, B2, etc.)
seats[i][j] = (char)('A' + i) + String.valueOf(j + 1);
// Set prices (back rows cheaper than front rows)
seatPrices[i][j] = 15.0 - (i * 0.5);
}
}
}
// Book a seat
public boolean bookSeat(int row, int seat) {
if (!seatOccupancy[row][seat]) {
seatOccupancy[row][seat] = true;
return true;
}
return false;
}
// Display seating chart
public void displaySeatingChart() {
System.out.println("Screen This Way");
System.out.println("---------------");
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seatOccupancy[i][j]) {
System.out.print("[XX] ");
} else {
System.out.printf("[%s] ", seats[i][j]);
}
}
System.out.println(); // New line for each row
}
}
// Get price for specific seat
public double getSeatPrice(int row, int seat) {
return seatPrices[row][seat];
}
}
Usage example:
MovieTheater theater = new MovieTheater(5, 8);
theater.bookSeat(2, 3); // Book seat D4
theater.displaySeatingChart();
Output might look like:
Screen This Way
---------------
[A1] [A2] [A3] [A4] [A5] [A6] [A7] [A8]
[B1] [B2] [B3] [B4] [B5] [B6] [B7] [B8]
[C1] [C2] [C3] [XX] [C5] [C6] [C7] [C8]
[D1] [D2] [D3] [D4] [D5] [D6] [D7] [D8]
[E1] [E2] [E3] [E4] [E5] [E6] [E7] [E8]
2. City Building Temperature Monitoring System¶
Monitor temperatures across different floors and rooms in multiple buildings.
public class BuildingTemperatureSystem {
// 3D array: [building][floor][room]
private double[][][] temperatures;
private String[] buildingNames;
private boolean[][][] hasTemperatureSensor;
public BuildingTemperatureSystem(int buildings, int floorsPerBuilding, int roomsPerFloor) {
temperatures = new double[buildings][floorsPerBuilding][roomsPerFloor];
hasTemperatureSensor = new boolean[buildings][floorsPerBuilding][roomsPerFloor];
buildingNames = new String[buildings];
}
// Record temperature for a specific location
public void recordTemperature(int building, int floor, int room, double temp) {
if (hasTemperatureSensor[building][floor][room]) {
temperatures[building][floor][room] = temp;
} else {
throw new IllegalStateException("No sensor in this room");
}
}
// Get average temperature for a floor
public double getFloorAverage(int building, int floor) {
double sum = 0;
int count = 0;
for (int room = 0; room < temperatures[building][floor].length; room++) {
if (hasTemperatureSensor[building][floor][room]) {
sum += temperatures[building][floor][room];
count++;
}
}
return count > 0 ? sum / count : 0;
}
// Print temperature report
public void printTemperatureReport() {
System.out.println("Building Temperature Report");
System.out.println("=========================");
for (int b = 0; b < temperatures.length; b++) {
System.out.printf("Building %d:%n", b + 1);
for (int f = 0; f < temperatures[b].length; f++) {
System.out.printf(" Floor %d:%n", f + 1);
for (int r = 0; r < temperatures[b][f].length; r++) {
if (hasTemperatureSensor[b][f][r]) {
System.out.printf(" Room %d: %.1f°C%n",
r + 1, temperatures[b][f][r]);
}
}
System.out.printf(" Floor Average: %.1f°C%n",
getFloorAverage(b, f));
}
System.out.println();
}
}
}
3. School Class Schedule System¶
public class SchoolScheduleSystem {
// 3D array: [grade][day][period]
private String[][][] schedule;
private String[] teachers;
private String[] subjects;
private static final String[] DAYS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
public SchoolScheduleSystem(int grades, int periods) {
schedule = new String[grades][5][periods]; // 5 for weekdays
// Initialize with empty slots
for (int g = 0; g < grades; g++) {
for (int d = 0; d < 5; d++) {
for (int p = 0; p < periods; p++) {
schedule[g][d][p] = "Free";
}
}
}
}
// Schedule a class
public void scheduleClass(int grade, int day, int period, String subject) {
if (grade >= 0 && grade < schedule.length &&
day >= 0 && day < 5 &&
period >= 0 && period < schedule[0][0].length) {
schedule[grade][day][period] = subject;
} else {
throw new IllegalArgumentException("Invalid schedule parameters");
}
}
// Print schedule for a grade
public void printGradeSchedule(int grade) {
System.out.printf("Schedule for Grade %d%n", grade + 1);
System.out.println("===================");
// Print periods header
System.out.print("Day\\Period |");
for (int p = 0; p < schedule[0][0].length; p++) {
System.out.printf(" %d |", p + 1);
}
System.out.println();
// Print schedule
for (int d = 0; d < 5; d++) {
System.out.printf("%-10s |", DAYS[d]);
for (int p = 0; p < schedule[0][0].length; p++) {
System.out.printf(" %s |", schedule[grade][d][p]);
}
System.out.println();
}
}
// Check teacher availability
public boolean isTeacherAvailable(String teacher, int day, int period) {
for (int g = 0; g < schedule.length; g++) {
if (schedule[g][day][period].equals(teacher)) {
return false;
}
}
return true;
}
}
Example Usage:
public class MultiDimensionalArrayDemo {
public static void main(String[] args) {
// Create movie theater
MovieTheater theater = new MovieTheater(5, 8);
theater.bookSeat(2, 3);
theater.displaySeatingChart();
// Create building temperature system
BuildingTemperatureSystem tempSystem =
new BuildingTemperatureSystem(2, 3, 4);
tempSystem.recordTemperature(0, 1, 2, 22.5);
tempSystem.printTemperatureReport();
// Create school schedule
SchoolScheduleSystem school = new SchoolScheduleSystem(6, 7);
school.scheduleClass(0, 0, 1, "Math");
school.printGradeSchedule(0);
}
}
Key Concepts:¶
-
Dimensions
-
2D: Table/Grid (rows and columns)
- 3D: Cube (length, width, height)
-
Each dimension adds another level of indexing
-
Access Patterns
-
Need index for each dimension
-
Nested loops for processing
-
Memory Layout
-
Arrays of arrays
-
Each dimension can have different lengths
-
Common Use Cases - Tables and grids - Spatial data
- Time-based data across multiple categories
Exception Handling¶
What are Exceptions?¶
Think of exceptions as unexpected problems in your program, similar to:
- Trying to divide by zero
- Trying to read a file that doesn't exist
- Trying to access an array index that doesn't exist
Types of Exceptions¶
Checked Exceptions (Must be handled)¶
Exception
and its subclasses (except RuntimeException)- Examples: IOException, SQLException
- Compiler forces you to handle these
Unchecked Exceptions (Runtime)¶
RuntimeException
and its subclasses- Examples: ArithmeticException, NullPointerException
- Compiler doesn't force you to handle these
Exception Handling Flow¶
flowchart TD
A[Start] --> B{Try Block}
B -->|Exception Occurs| C[Catch Block]
B -->|No Exception| D[Normal Flow]
C --> E[Finally Block]
D --> E
E --> F[Continue Program]
style B fill:#bbf,stroke:#333
style C fill:#fbb,stroke:#333
style E fill:#bfb,stroke:#333
Common Exception Types / Exception Hierarchy¶
graph TD
A[Object] --> B[Throwable]
B --> C[Error]
B --> D[Exception]
D --> E[RuntimeException]
D --> F[IOException]
E --> G[ArithmeticException]
E --> H[NullPointerException]
E --> I[IndexOutOfBoundsException]
style D fill:#f9f,stroke:#333
style E fill:#bbf,stroke:#333
Common Exception Examples¶
public class ExceptionExamples {
public static void main(String[] args) {
// 1. ArithmeticException
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Can't divide by zero!");
}
// 2. ArrayIndexOutOfBoundsException
try {
int[] numbers = new int[3];
System.out.println(numbers[3]); // Array has only 0,1,2
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds!");
}
// 3. Multiple catch blocks
try {
String str = null;
str.length(); // Will cause NullPointerException
} catch (NullPointerException e) {
System.out.println("Null value found!");
} catch (Exception e) {
System.out.println("Some other exception occurred!");
}
}
}
Real-World Example: ATM Machine¶
public class ATM {
private double balance;
public void withdraw(double amount) {
try {
if (amount > balance) {
throw new Exception("Insufficient funds");
}
if (amount > 1000) {
throw new Exception("Amount exceeds daily limit");
}
balance -= amount;
System.out.println("Withdrawal successful");
} catch (Exception e) {
System.out.println("Transaction failed: " + e.getMessage());
} finally {
System.out.println("Thank you for using our ATM");
}
}
}
Key Points to Remember¶
-
Exception Class is the Parent
-
All exceptions inherit from the Exception class
-
Can catch any exception using Exception class
-
Try-Catch Block Structure
try {
// Code that might throw an exception
} catch (SpecificException e) {
// Handle specific exception
} catch (Exception e) {
// Handle any other exception
} finally {
// Always executed
}
- Best Practices
- Catch specific exceptions before general ones
- Always include meaningful error messages
- Use finally block for cleanup code
- Don't catch exceptions you can't handle
Practice Questions¶
Question 1¶
What will be the output of the following code?
Answer: 0 (Arrays are automatically initialized with default values)
Question 2¶
What's wrong with this code?
Answer: ArrayIndexOutOfBoundsException - The array has indices 0,1,2 but we're trying to access index 3
Question 3¶
How would you calculate the average of all numbers in an array?
Answer:
int sum = 0;
for (int value : values) {
sum += value;
}
double average = (double)sum / values.length;
Question 4¶
What will happen in this code?
try {
int result = 10 / 0;
System.out.println("After division");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Always executed");
}
Answer: Output will be:
Question 5¶
Write a program to find the largest number in an array. Answer:
public static int findLargest(int[] numbers) {
if (numbers.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
int largest = numbers[0];
for (int number : numbers) {
if (number > largest) {
largest = number;
}
}
return largest;
}
Tips for Success¶
- Always check array bounds before accessing elements
- Initialize arrays with appropriate sizes
- Use try-catch blocks when working with risky operations
- Remember that array indices start at 0
- Take advantage of the enhanced for loop when possible
Common Mistakes to Avoid¶
- Accessing index out of bounds
- Forgetting to initialize arrays
- Not handling exceptions properly
- Confusing 2D array indices
- Trying to resize arrays (they're fixed size!)