Java QB ANS
Java QB ANS
myDog.makeSound(); // Bark
myCat.makeSound(); // Meow
}
}
4) Define an exception. What are the key terms used in exception handling?
Explain
A)
Exception: An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions. It is a way to signal error conditions and handle
them in a controlled manner. Exceptions can be caused by various factors such as invalid
user input, device failure, or programming errors.
Key Terms in Exception Handling:
• Try
• Catch
• Finally
• Throw
• Throws
try Block:
• The try block contains the code that might cause an exception (divide(10, 0)).
catch Block:
• The catch block catches and handles the ArithmeticException.
finally Block:
• The finally block contains code that will always be executed, regardless of whether an
exception was thrown or caught.
throw Statement:
• The divide method uses the throw statement to throw an ArithmeticException when
division by zero is attempted.
throws Keyword:
• The divide method declares that it can throw an ArithmeticException using the
throws keyword.
Example:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int result = divide(10, 0); // This will cause an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block executed.");
}
}
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by zero");
} return a / b;
}
Module 5
1 .Explain the concept of importing packages in java and provide an
example demonstrating the usage of the import statement
A)
Concept of Importing Packages
• Default Package: Java automatically imports the java.lang package by default, which
includes fundamental classes such as String, System, and Math. For other packages,
you need to use the import statement.
• Single Type Import: You can import a specific class or interface from a package.
import packageName.ClassName;
• On-Demand Import: You can import all the classes and interfaces from a package.
import packageName.*;
Example
// File 1 // File:2
package com.example.utility; Main.java
public class MathUtils { import com.example.utility.MathUtils;
public static int add(int a, int b) {
return a + b; public class Main {
} public static void main(String[] args) {
} int sum = MathUtils.add(10, 20);
System.out.println("Sum: " + sum);
}
}