Java

Java Week 2:Mastering Core Java concepts-Arrays,Strings And More

In this Week We’ll cover topics such as arrays and strings, methods and functions, recursion, and exception handling. So, let’s dive in! we will explore the  fundamental concepts in Java and provide examples and practice codes to help you understand them better. Please Visit this page for Java Basics.

On This Page

Arrays and Strings

When working with arrays, you need to understand concepts such as indexing, accessing elements, and manipulating array elements. You can perform various operations on arrays, such as sorting, searching, and merging. Additionally, understanding string manipulation techniques, such as concatenation, substring extraction, and searching for specific patterns, will enable you to work effectively with strings.

 Let’s start by understanding how to declare and initialize arrays.

Declaring and Initializing Arrays

To declare an array in Java, you need to specify the type of the elements it will hold, followed by the name of the array variable. Here’s the syntax:

                 type[] arrayName;

For example, to declare an array of integers, you would use:

int[] numbers;

After declaring an array, you need to initialize it before you can use it. There are several ways to initialize an array:

1. Initializing with values: You can directly assign values to an array at the time of declaration. Here’s an example:

int[] numbers = {1, 2, 3, 4, 5};

2. Initializing with a specified size:You can initialize an array with a specified size and then assign values to individual elements. Here’s an example:

int[] numbers = new int[5]; numbers[0] = 1; numbers[1] = 2; numbers[2] = 3; numbers[3] = 4; numbers[4] = 5;

3. Initializing with a default value: You can initialize an array with a default value for each element. Here’s an example:

int[] numbers = new int[5]; // All elements are initialized to 0 by default

Accessing Array ElementsOnce you have declared and initialized an array, you can access its individual elements using their indices. In Java, arrays are zero-based, which means the first element has an index of 0.

To access an element, you need to specify the array variable name followed by the index of the element in square brackets. Here’s an example:


int[] numbers = {1, 2, 3, 4, 5};
int firstNumber = numbers[0]; // Accessing the first element
int thirdNumber = numbers[2]; // Accessing the third element

Example Codes

Here are seven example codes that demonstrate various operations with arrays:

1. Sum of Array Elements:


int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println("Sum of array elements: " + sum);

2. Finding the Maximum Element:


int[] numbers = {1, 2, 3, 4, 5};
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum element: " + max);

3. Copying an Array:


int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[source.length];
for (int i = 0; i < source.length; i++) {
destination[i] = source[i];
}
System.out.println("Copied array: " + Arrays.toString(destination));

4. Reversing an Array:


int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[numbers.length - 1 - i];
numbers[numbers.length - 1 - i] = temp;
}
System.out.println("Reversed array: " + Arrays.toString(numbers));

5. Checking if an Array is Sorted:


int[] numbers = {1, 2, 3, 4, 5};
boolean isSorted = true;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < numbers[i - 1]) {
isSorted = false;
break;
}
}
System.out.println("Is the array sorted? " + isSorted);

6. Finding the Average of Array Elements:


int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}
double average = (double) sum / numbers.length;
System.out.println("Average of array elements: " + average);

7. Counting the Occurrences of an Element:


int[] numbers = {1, 2, 3, 4, 5, 2, 3, 2};
int target = 2;
int count = 0;
for (int number : numbers) {
if (number == target) {
count++;
}
}
System.out.println("Occurrences of " + target + ": " + count);

Practice Questions On Arrays

Here are some practice questions to test your understanding of arrays in Java:

  • Write a program to find the second smallest element in an array.
  • Write a program to remove duplicates from an array.
  • Write a program to check if two arrays are equal.
  • Write a program to find the frequency of each element in an array.
  • Write a program to sort an array in descending order.

Feel free to explore these questions and deepen your understanding of arrays in Java!

String Class and its Methods

The String class in Java is a fundamental class used for representing and manipulating strings of characters. It offers various methods to perform operations like extracting substrings, finding the length of the string, and searching for characters or substrings within the string.

Here are examples of five common methods of the String class:

1. substring(int beginIndex, int endIndex): This method returns a new string that is a substring of the original string. The substring begins at the specified beginIndex and extends to the character at index endIndex – 1

String str = "Hello, World!";
String substr = str.substring(7, 12); // Extracts "World"
System.out.println(substr);

2. length(): This method returns the length of the string.

String str = "Hello";
int length = str.length(); // Returns 5
System.out.println("Length of the string: " + length);

3. indexOf(int ch): This method returns the index within the string of the first occurrence of the specified character. If the character is not found, it returns -1.

String str = "Hello, World!";
int index = str.indexOf('W'); // Returns 7
System.out.println("Index of 'W': " + index);

4. indexOf(String str): This method returns the index within the string of the first occurrence of the specified substring. If the substring is not found, it returns -1.

String str = "Java is awesome!";
int index = str.indexOf("is"); // Returns 5
System.out.println("Index of 'is': " + index);

5. toUpperCase(): This method returns a new string with all the characters converted to uppercase.

String str = "hello";
String upperCaseStr = str.toUpperCase(); // Returns "HELLO"
System.out.println("Uppercase string: " + upperCaseStr);

6. charAt(int index): Returns the character at the specified index within the string.

String str = "Hello";
char ch = str.charAt(1); // Returns 'e'
System.out.println("Character at index 1: " + ch);

7. equals(Object obj): Compares this string to the specified object. Returns true if the strings are equal, false otherwise.

String str1 = "hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // Returns false
System.out.println("Are strings equal? " + isEqual);

8. equalsIgnoreCase(String anotherString): Compares this string to another string, ignoring case considerations.

String str1 = "hello";
String str2 = "HELLO";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // Returns true
System.out.println("Are strings equal (ignore case)? " + isEqualIgnoreCase);

9. toLowerCase(): Returns a new string with all the characters converted to lowercase.

String str = "Hello";
String lowerCaseStr = str.toLowerCase(); // Returns "hello"
System.out.println("Lowercase string: " + lowerCaseStr);

10. trim(): Returns a copy of the string with leading and trailing whitespace removed.

String str = "   Hello   ";
String trimmedStr = str.trim(); // Returns "Hello"
System.out.println("Trimmed string: " + trimmedStr);

These are just a few examples of the methods provided by the String class in Java. There are many more useful methods available for string manipulation. Try to explore them.

Practice Questions on String

1. Write a program that takes a string as input and prints the last character.

2. Write a program that takes two strings as input and checks if they are anagrams.

3. Write a program that takes a sentence as input and counts the number of words.

4. Write a program that takes a string as input and prints the reverse of the string.

5. Write a program that takes a string as input and checks if it is a palindrome.

Methods and Functions

Methods and functions are essentially the same thing in Java. They are blocks of code that perform a specific task. The terms “method” and “function” are often used interchangeably, but “method” is more commonly used in the context of object-oriented programming.

A method or function consists of a name, a set of parameters (optional), a return type (optional), and a body. The body contains the instructions that are executed when the method or function is called.

Defining Methods with Parameters and Return Types in Java

In Java, methods are used to encapsulate a set of instructions that can be executed when needed. They allow us to organize our code into reusable blocks, making our programs more modular and easier to understand. Methods can have parameters and return types, which further enhance their functionality and flexibility.

Parameters in Methods

Parameters are variables that are passed into a method when it is called. They allow us to provide input to the method, which can then be used in the method’s code block. Parameters are defined within the parentheses after the method name.

Here’s an example of a method with parameters:

public void greet(String name) { System.out.println("Hello, " + name + "!"); } 

In this example, the method greet takes a parameter named name of type String. When the method is called, we can pass a String value as an argument:

 greet("John"); 

This will output:

 Hello, John! 

We can also have multiple parameters in a method:

public void add(int a, int b) { int sum = a + b; System.out.println("The sum is: " + sum); } 

Here, the method add takes two parameters a and b of type int. We can pass two integer values as arguments:

add(5, 3); 

This will output:

 The sum is: 8 

Return Types in Methods

Return types specify the type of value that a method should return after its execution. If a method does not return any value, its return type is specified as void. If a method returns a value, its return type should match the type of the value being returned.

Here’s an example of a method with a return type:

 public int multiply(int a, int b) { return a * b; } 

In this example, the method multiply takes two parameters a and b of type int and returns their product as an int value. We can store the returned value in a variable and use it later:

 int result = multiply(4, 5); System.out.println("The result is: " + result);

This will output:

The result is: 20 

We can also have methods that return other types, such as Stringboolean, or even custom objects:

 public String getFullName(String firstName, String lastName) {
return firstName + " " + lastName;
}

In this example, the method getFullName takes two parameters firstName and lastName of type String and returns their concatenation as a String value.

Examples of Methods with Parameters and Return Types

Here are few examples of methods with different parameter and return types:

1. public int calculateSum(int[] numbers): This method takes an array of integers as a parameter and returns their sum as an integer value.

2. public boolean isEven(int number): This method takes an integer as a parameter and returns true if the number is even, and false otherwise.

3. public double calculateAverage(double[] numbers): This method takes an array of doubles as a parameter and returns their average as a double value.

4. public String reverseString(String str): This method takes a string as a parameter and returns its reverse as a string value.

5. public Person createPerson(String name, int age): This method takes a name and age as parameters and returns a Person object with the given values.

Practice Questions

1. Write a method public int calculateFactorial(int n) that calculates the factorial of a given number n.

2. Write a method public boolean isPalindrome(String str) that checks if a given string str is a palindrome.

3. Write a method public int findMax(int[] numbers) that finds the maximum value in an array of integers.

4. Write a method public String capitalize(String str) that capitalizes the first letter of each word in a given string str.

5. Write a method public String[] splitString(String str, String delimiter) that splits a given string str into an array of strings using the specified delimiter.

Method Overloading in Java

Method overloading is a feature in Java that allows a class to have multiple methods with the same name but different parameters. It is a form of polymorphism, where a single method name can be used to perform different actions based on the number, type, or order of the parameters.

Method overloading is achieved by:

  1. Changing the number of parameters.
  2. Changing the data type of parameters.
  3. Or both.

Java resolves overloaded methods at compile time, based on the parameters provided during the method invocation.

How Does Method Overloading Work?

In Java, method overloading is achieved by defining multiple methods with the same name but different parameter lists. The compiler determines which method to call based on the arguments passed during the method invocation.

When a method is called, the compiler looks for a method with the same name and compatible parameters. If an exact match is found, that method is called. If an exact match is not found, the compiler looks for the closest match by applying the following rules:

  1. If a method with the exact parameter types is found, it is called.
  2. If no exact match is found, the compiler looks for a method with compatible types. For example, if an int argument is passed, the compiler looks for a method that accepts int or a wider type like long.
  3. If multiple methods are found with compatible types, the compiler selects the most specific one. For example, if there are methods that accept both int and long, and an int argument is passed, the method accepting int will be called.
  4. If no match is found, a compile-time error occurs.

Examples of Method Overloading

Here are few examples of method overloading in Java:

Example 1: Addition of Two Integers

 
public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
    
    public double add(double a, double b) {
        return a + b;
    }
    
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        System.out.println(calculator.add(5, 10));      // Output: 15
        System.out.println(calculator.add(2.5, 3.5));  // Output: 6.0
    }
}

In this example, the Calculator class has two add methods. One accepts two int parameters and returns an int result, while the other accepts two double parameters and returns a double result. Depending on the argument types, the appropriate method is called.

Example 2: Concatenation of Strings

public class StringUtils {
    public String concatenate(String s1, String s2) {
        return s1 + s2;
    }
    
    public String concatenate(String s1, String s2, String s3) {
        return s1 + s2 + s3;
    }
    
    public static void main(String[] args) {
        StringUtils stringUtils = new StringUtils();
        System.out.println(stringUtils.concatenate("Hello", "World"));          // Output: HelloWorld
        System.out.println(stringUtils.concatenate("Java", " is", " awesome"));  // Output: Java is awesome
    }
}

In this example, the StringUtils class has two concatenate methods. One accepts two String parameters and returns the concatenation of the two strings, while the other accepts three String parameters and returns the concatenation of all three strings.

Example 3: Finding the Maximum of Two Numbers

public class MathUtils {
    public int max(int a, int b) {
        return (a > b) ? a : b;
    }
    
    public double max(double a, double b) {
        return (a > b) ? a : b;
    }
    
    public static void main(String[] args) {
        MathUtils mathUtils = new MathUtils();
        System.out.println(mathUtils.max(5, 10));     // Output: 10
        System.out.println(mathUtils.max(2.5, 3.5));  // Output: 3.5
    }
}

In this example, the MathUtils class has two max methods. One accepts two int parameters and returns the maximum of the two numbers, while the other accepts two double parameters and returns the maximum of the two numbers.

Example 4: Area Calculation

public class ShapeUtils {
    public double calculateArea(int side) {
        return side * side;
    }
    
    public double calculateArea(int length, int width) {
        return length * width;
    }
    
    public double calculateArea(double radius) {
        return Math.PI * radius * radius;
    }
    
    public static void main(String[] args) {
        ShapeUtils shapeUtils = new ShapeUtils();
        System.out.println(shapeUtils.calculateArea(5));      // Output: 25.0
        System.out.println(shapeUtils.calculateArea(4, 6));   // Output: 24.0
        System.out.println(shapeUtils.calculateArea(3.5));    // Output: 38.48451000647496
    }
}

In this example, the ShapeUtils class has three calculateArea methods. One accepts the side of a square, another accepts the length and width of a rectangle, and the third accepts the radius of a circle. The appropriate method is called based on the arguments provided.

Example 5: Finding the Average of Numbers

public class AverageUtils {
    public double calculateAverage(int... numbers) {
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        return (double) sum / numbers.length;
    }
    
    public static void main(String[] args) {
        AverageUtils averageUtils = new AverageUtils();
        System.out.println(averageUtils.calculateAverage(5, 10));                // Output: 7.5
        System.out.println(averageUtils.calculateAverage(2, 4, 6));              // Output: 4.0
        System.out.println(averageUtils.calculateAverage(1, 3, 5, 7, 9));        // Output: 5.0
    }
}

In this example, the AverageUtils class has a calculateAverage method that accepts a variable number of integers. The method calculates the average of the numbers and returns the result.

Recursion in Java

Recursion is a programming technique where a method calls itself to solve a problem. It is particularly useful when solving problems that can be broken down into smaller, similar subproblems.

Recursion follows a simple principle: a function calls itself until a certain condition is met. This condition, known as the base case, is crucial to prevent infinite recursion. Without a base case, the function would keep calling itself indefinitely, leading to a stack overflow error.

When a function calls itself, it creates a new instance of the function on the stack. Each instance has its own set of variables and parameters, allowing the function to work with different values each time it is called. As the function progresses, it eventually reaches the base case and starts returning values back up the call stack.

Key Components of Recursion

  1. Base Case: A condition that determines when the recursion should stop.
  2. Recursive Case: A condition that defines how the problem can be reduced to a smaller subproblem.
  3. Function Call: Invoking the same function within itself.

To better understand recursion, let’s dive into some examples:

Example 1: Factorial Calculation

public class Factorial {
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1; // Base case
        } else {
            return n * factorial(n - 1); // Recursive case
        }
    }
    public static void main(String[] args) {
        int result = factorial(5); // Calculate factorial of 5
        System.out.println("Factorial of 5: " + result); // Output: 120
    }
}

Explanation:

  • The factorial method calculates the factorial of a number n.
  • The base case checks if n is 0 or 1, in which case the factorial is 1.
  • The recursive case multiplies n with the factorial of n - 1, effectively reducing the problem size in each recursive call.

Example 2: Fibonacci Sequence

public class Fibonacci {
    public static int fibonacci(int n) {
        if (n <= 1) {
            return n; // Base case
        } else {
            return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
        }
    }
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.print(fibonacci(i) + " "); // Output: 0 1 1 2 3 5 8 13 21 34
        }
    }
}

Explanation:

  • The fibonacci method calculates the Fibonacci number at position n.
  • The base case returns n if it’s 0 or 1.
  • The recursive case returns the sum of Fibonacci numbers at positions n - 1 and n - 2, which eventually leads to the base case.

Example 3: Sum of Array Elements

public class ArraySum {
    public static int sum(int[] arr, int n) {
        if (n <= 0) {
            return 0; // Base case
        } else {
            return sum(arr, n - 1) + arr[n - 1]; // Recursive case
        }
    }
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int result = sum(arr, arr.length);
        System.out.println("Sum of array elements: " + result); // Output: 15
    }
}

Explanation:

  • The sum method calculates the sum of elements in an array arr.
  • The base case returns 0 if n (index) is less than or equal to 0.
  • The recursive case returns the sum of elements up to index n - 1 plus the element at index n - 1.

Example 4: Binary Search

public class BinarySearch {
    public static int binarySearch(int[] arr, int low, int high, int target) {
        if (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == target) {
                return mid; // Base case
            } else if (arr[mid] < target) {
                return binarySearch(arr, mid + 1, high, target); // Recursive case (search in right half)
            } else {
                return binarySearch(arr, low, mid - 1, target); // Recursive case (search in left half)
            }
        }
        return -1; // Base case (element not found)
    }
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11, 13, 15, 17};
        int target = 13;
        int result = binarySearch(arr, 0, arr.length - 1, target);
        if (result != -1) {
            System.out.println("Element found at index: " + result); // Output: Element found at index: 6
        } else {
            System.out.println("Element not found");
        }
    }
}

Explanation:

  • The binarySearch method searches for a target element in a sorted array using binary search.
  • The base case returns the index of the target element if found.
  • The recursive case divides the array into halves and continues searching in the appropriate half based on the comparison with the target element.

Example 5: Tower of Hanoi

public class TowerOfHanoi {
    public static void towerOfHanoi(int n, char from, char to, char aux) {
        if (n == 1) {
            System.out.println("Move disk 1 from rod " + from + " to rod " + to);
        } else {
            towerOfHanoi(n - 1, from, aux, to); // Move top n-1 disks from A to B using C as auxiliary
            System.out.println("Move disk " + n + " from rod " + from + " to rod " + to); // Move remaining disk from A to C
            towerOfHanoi(n - 1, aux, to, from); // Move n-1 disks from B to C using A as auxiliary
        }
    }
    public static void main(String[] args) {
        int n = 3; // Number of disks
        towerOfHanoi(n, 'A', 'C', 'B');
    }
}

Explanation:

  • The towerOfHanoi method solves the Tower of Hanoi puzzle for n disks.
  • The base case moves the top disk from the source rod to the destination rod when there’s only one disk.
  • The recursive case moves n-1 disks from the source rod to the auxiliary rod, then moves the remaining disk from the source rod to the destination rod, and finally moves n-1 disks from the auxiliary rod to the destination rod.

Exceptions and Errors 

Exception handling in Java is a mechanism used to deal with runtime errors or exceptional conditions that may occur during the execution of a program. Exceptions and errors are two types of such abnormal conditions.

Understanding Exceptions and Errors

  • Exceptions: Exceptions represent abnormal conditions that occur during the execution of a program, such as division by zero, array index out of bounds, or file not found. Exceptions are subclassed from the Throwable class.
  • Errors: Errors represent abnormal conditions that are generally caused by the environment in which the application is running, such as system crashes, out of memory errors, or stack overflow errors. Errors are also subclasses of Throwable.

In Java, an exception is an event that occurs during the execution of a program, which disrupts the normal flow of the program’s instructions. When an exception occurs, the program stops executing the current instructions and transfers the control to a special block of code called the exception handler.

Exceptions can be caused by various factors, such as invalid input, resource unavailability, or programming errors. Java provides a rich set of built-in exceptions, and you can also create your own custom exceptions.

Types of Exceptions

Java exceptions are classified into two broad categories:

Checked Exceptions

Checked exceptions are the exceptions that are checked at compile-time. These exceptions are typically caused by external factors that are beyond the control of the program. Examples of checked exceptions include FileNotFoundException and IOException. When a method throws a checked exception, it must be either caught using a try-catch block or declared using the throws keyword.

Unchecked Exceptions

Unchecked exceptions, also known as runtime exceptions, are not checked at compile-time. These exceptions are typically caused by programming errors or unexpected conditions within the program. Examples of unchecked exceptions include NullPointerException and ArrayIndexOutOfBoundsException. Unlike checked exceptions, methods are not required to declare or catch unchecked exceptions.

Try-Catch Blocks

  • A try block is used to enclose the code that might throw an exception.
  • A catch block is used to handle the exception if it occurs.
  • Multiple catch blocks can be used to handle different types of exceptions.

Throwing Exceptions

In Java, you can throw an exception using the throw keyword. This is useful when you want to indicate that something unexpected has occurred.

  • The throw keyword is used to explicitly throw an exception.
  • It is typically used when an error condition is detected within a method and the method cannot handle the error itself.

Here’s an example:

public void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");}
// Code to perform division}

In this example, the divide method throws an ArithmeticException if the second parameter b is zero.

Let’s look at some examples of exceptions  and its handling in Java:

Example 1: Handling Arithmetic Exception

public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage()); // Output: Error: / by zero
        }
    }
}

    Explanation:

  • In this example, the try block contains the code that may throw an ArithmeticException due to division by zero.
  • Since division by zero is not allowed in Java, it throws an ArithmeticException at runtime.
  • The catch block catches the ArithmeticException and handles it by printing an error message indicating the type of exception and its message.
Example 2: Handling ArrayIndexOutOfBoundsException
public class ExceptionHandling {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        try {
            int value = arr[3]; // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage()); // Output: Error: Index 3 out of bounds for length 3
        }
    }
}

Explanation:

  • Here, we have an array arr with three elements.
  • The try block tries to access the element at index 3, which is out of bounds because the array has only three elements.
  • Consequently, it throws an ArrayIndexOutOfBoundsException at runtime.
  • The catch block catches this exception and prints an error message indicating the type of exception and its message.
Example 3: Handling NullPointerException
public class ExceptionHandling {
    public static void main(String[] args) {
        String str = null;
        try {
            int length = str.length(); // NullPointerException
        } catch (NullPointerException e) {
            System.out.println("Error: " + e.getMessage()); // Output: Error: null
        }
    }
}

Explanation:

  • In this example, we have a string variable str initialized to null.
  • The try block attempts to retrieve the length of the string str, which is not possible because it’s null.
  • Consequently, it throws a NullPointerException at runtime.
  • The catch block catches this exception and prints an error message indicating the type of exception and its message.
Example 4: Throwing Custom Exception
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}
public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            throw new CustomException("Custom exception occurred");
        } catch (CustomException e) {
            System.out.println("Error: " + e.getMessage()); // Output: Error: Custom exception occurred
        }
    }
}

Explanation:

  • This example demonstrates how to throw a custom exception (CustomException) explicitly using the throw keyword.
  • The throw new CustomException("Custom exception occurred") statement throws a CustomException with a custom error message.
  • The catch block catches this custom exception and prints the error message.
Example 5: Using Finally Block
public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed"); // Output: Finally block executed
        }
    }
}

Explanation:

  • In this example, the try block attempts to perform a division operation that results in an ArithmeticException due to division by zero.
  • The catch block catches this exception and prints an error message.
  • The finally block is always executed regardless of whether an exception occurs or not. It’s commonly used for cleanup activities such as closing resources or releasing locks.

These examples demonstrate various aspects of exception handling in Java, including catching different types of exceptions, throwing custom exceptions, and using the finally block for cleanup operations.

Practice Questions

  1. Explain the difference between exceptions and errors in Java.
  2. What is the purpose of the try-catch block in exception handling?
  3. How do you handle multiple exceptions in a single try-catch block?
  4. When would you throw a custom exception in Java?
  5. What is the significance of the finally block in exception handling?

Lastly Why did the exception go to therapy?
Because it had too many issues to handle on its own! 😄

So, happy coding! Keep practicing and experimenting with the concepts we’ve covered in this Page . 
Moreover, consider attempting this quiz.

FAQs

What is the difference between an array and an ArrayList?

An array has a fixed size and is a primitive data structure, while an ArrayList is a dynamic array implementation provided by the Java Collections Framework and can resize dynamically.

How do you sort an array in Java?

You can sort an array in Java using the Arrays.sort() method. For example: int[] numbers = {3, 1, 4, 1, 5}; Arrays.sort(numbers);

What is the difference between String and StringBuilder in Java?

String objects are immutable, meaning their values cannot be changed after they are created. StringBuilder, on the other hand, is mutable and allows for dynamic modification of its contents.

How do you convert a String to an array of characters in Java?

You can use the toCharArray() method of the String class to convert a String to an array of characters. For example: String str = "hello"; char[] charArray = str.toCharArray();

How do you find the index of a specific character in a String?

You can use the indexOf() method of the String class to find the index of a specific character in a String. For example: String str = "hello"; int index = str.indexOf('e');

What is the difference between parameters and arguments in a method?

Parameters are variables declared in the method signature, while arguments are the actual values passed to the method when it is called.

Can you overload the main() method in Java?

Yes, you can overload the main() method in Java, but the JVM will only call the main() method with the standard signature public static void main(String[] args).

What is the return type of the main() method?

The return type of the main() method in Java is void. This indicates that the main() method does not return any value.

How do you call a method defined in another class?

To call a method defined in another class, you first create an object of that class and then use dot notation to access the method. For example: MyClass obj = new MyClass(); obj.myMethod();

What is the purpose of the return statement in a method?

The return statement is used to exit a method and optionally return a value to the caller. It can be used to return the result of a computation or indicate the completion status of a method.

What is the difference between errors and exceptions in Java?

Errors in Java are serious issues that typically cannot be handled by the programmer, whereas exceptions are less serious and can be caught and handled.

When should you use checked exceptions?

Checked exceptions should be used when a method encounters a condition that the caller should handle, such as file I/O errors or network connection issues.

Can you have multiple catch blocks for a single try block?

Yes, you can have multiple catch blocks for a single try block in Java. They are evaluated in order, and the first catch block with a matching exception type is executed.

What is the purpose of the finally block in exception handling?

The finally block is used to execute code that should always run, regardless of whether an exception occurs or not. It is commonly used for cleanup tasks, such as closing resources.

How do you create a custom exception in Java?

You can create a custom exception in Java by extending the Exception class or one of its subclasses. For example: class MyException extends Exception { /* constructor and additional methods */ }

What is the difference between throw and throws in Java?

The throw keyword is used to explicitly throw an exception within a method, while the throws keyword is used in the method signature to indicate that the method may throw certain types of exceptions.

You May Also Like

More From Author

+ There are no comments

Add yours