0% found this document useful (0 votes)
2 views

java unit 3 tt2

The document discusses various concepts in Java, including exception handling, access protection in packages, and the implementation of interfaces. It outlines the advantages and disadvantages of exception handling, describes access specifiers (public, private, protected, default), and provides examples of implementing interfaces and handling exceptions. Additionally, it includes Java code snippets for linear search, arithmetic exceptions, and the use of try-catch-finally blocks.

Uploaded by

Tushar salunkhe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java unit 3 tt2

The document discusses various concepts in Java, including exception handling, access protection in packages, and the implementation of interfaces. It outlines the advantages and disadvantages of exception handling, describes access specifiers (public, private, protected, default), and provides examples of implementing interfaces and handling exceptions. Additionally, it includes Java code snippets for linear search, arithmetic exceptions, and the use of try-catch-finally blocks.

Uploaded by

Tushar salunkhe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Subject- JAVA Unit-3-

Que-1- Explain Advantages and Disadvantages of Exception Handling?(5 Marks)

Ans=**Advantages of Using Exceptions:**

1. **Clarity and Readability**: Exceptions provide a more intuitive way to


handle errors. Exception-handling code is typically separated from the main
flow of the program, making the main code easier to read and understand.

2. **Separation of Concerns**: Exceptions allow you to separate error-


handling logic from the normal flow of the program. This makes the
codebase cleaner and more organized.

3. **Stack Unwinding**: When an exception is thrown, the call stack is


unwound, allowing the program to jump directly to the appropriate
exception handler. This can lead to faster error recovery and better
debugging.

4. **No Need for Global Error Checks**: You don't need to explicitly check
for errors after every function call or operation, reducing clutter in the code
and avoiding the need for cascading error codes.

5. **Consistent Handling**: Using exceptions ensures that errors are


consistently handled across the application, promoting a more uniform
approach to error management.

**Disadvantages of Using Exceptions:**

1. **Performance Overhead**: Throwing and catching exceptions can


introduce performance overhead, especially in situations where exceptions
are thrown frequently.

2. **Resource Management**: Exceptions can complicate resource


management (e.g., memory, file handles) since resources might not be
released properly if an exception is thrown within a try block.
3. **Complex Control Flow**: Exception handling can introduce complex
control flow, especially if exceptions are nested or caught at different levels
of the call stack.

4. **Misuse of Exceptions**: Overusing exceptions for flow control or non-


exceptional situations can lead to confusing and error-prone code.

Que-2- Describe Access Protection in package?(5 Marks)

Ans= n Java, access specifiers are used to defining the visibility and
accessibility of class members such as variables, methods, and inner
classes. Java has four access specifiers: public, private, protected, and
default (also known as package-private).

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains
private data member and private method. We are accessing these private
members from outside the class, so there is a compile-time error.

1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

2) Default

If you don't use any modifier, it is treated as default by default. The default
modifier is accessible only within package. It cannot be accessed from
outside the package. It provides more accessibility than private. But, it is
more restrictive than protected, and public.

1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

3) Protected

The protected access modifier is accessible within package and outside


the package but through inheritance only.

The protected access modifier can be applied on the data member, method
and constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest


scope among all other modifiers.

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello

Que-3- Develop a java program to create a Animal interface with a method called
bark() that takes no arguments and returns void. Create a Dog class that
implements Animal and overrides bark() to print “Dog is barking” (10 Marks)

Ans=

ava Code:
// Animal.java

// Interface Animal

// Declare the Animal interface

public interface Animal {

// Declare the abstract method "bark" that classes


implementing this interface must provide

void bark();

Copy
// Dog.java
// Class Dog

// Declare the Dog class, which implements the Animal


interface

public class Dog implements Animal {

// Implement the "bark" method required by the Animal


interface

@Override

public void bark() {

// Print a message indicating that the Dog is


barking

System.out.println("Dog is barking!");

Copy
// Main.java

// Class Main

// Declare the Main class

public class Main {

public static void main(String[] args) {

// Create an instance of the Dog class

Dog dog = new Dog();


// Call the "bark" method on the Dog instance

dog.bark();

Copy
Sample Output:
Dog is barking!

Que-4- Explain importance of exception handling? (5 Marks)

Ans=

Importance of Exception Handling

Below refers to the points why exception handling is important.


Let’s see one by one.

Ensures the Continuity of the Program

One of the key benefits of exception handling is that it ensures


the continuity of the program. Without proper exception handling,
an unhandled exception would cause the program to terminate
abruptly, which can lead to data loss & other issues. With proper
exception handling, the program can continue to execute and
provide a more stable user experience.

Enhances the Robustness of the Program

Exception handling allows for the program to anticipate and


recover from errors, thus making the program more robust and
resistant to unexpected conditions. By catching and handling
exceptions, the program can continue to execute and provide a
more stable user experience.

Improves the Readability & Maintainability of the Code

Proper exception handling also improves the readability &


maintainability of the code. By catching and handling exceptions,
the program can provide clear error messages that accurately
describe the error and provide information on how to resolve the
issue. This makes it easier for developers to understand and
modify the code in the future. Additionally, by providing detailed
error messages, proper exception handling allows for more
accurate error reporting, which is essential for debugging and
troubleshooting purposes.

Allows for more Accurate Error Reporting

Exception handling allows the program to catch & report errors in


a more accurate & detailed manner, providing valuable
information to developers for debugging and troubleshooting
purposes.

Facilitates Debugging and Troubleshooting

Exception handling allows the program to catch & report errors in


a more accurate and detailed manner, which facilitates debugging
and troubleshooting. By providing detailed error messages and
stack traces, exception handling allows developers to quickly
identify and resolve issues, reducing the amount of time and
resources required for debugging.

Improves the Security of the Program

Exception handling can also improve the security of a program by


preventing sensitive information from being exposed in the event
of an error. By catching and handling exceptions, the program
can prevent sensitive information, such as passwords and
personal data, from being displayed to the user or logged-in error
messages.

Provides a Better user Experience

Proper exception handling allows the program to anticipate and


recover from errors, providing a more stable user experience. It
is particularly important for user-facing applications, as it ensures
that the program continues to function even in the event of an
error, reducing the likelihood of user frustration and
abandonment.

Enables the use of error-recovery Mechanisms

Exception handling enables the use of error-recovery


mechanisms, such as retries or fallbacks, which can improve the
reliability and availability of the program. For example, if a
program encounters a network error, it can retry the operation or
fall back to a different network connection, ensuring that the
program continues to function even in the event of an error.

Improves the Scalability and Performance of the Program

Proper exception handling can also improve the scalability and


performance of a program by reducing the amount of
unnecessary processing and resource consumption. By catching
and handling exceptions, the program can avoid performing
unnecessary operations and releasing resources that are no
longer needed, reducing the overall load on the system and
improving performance.

Que-5- Define a interface with its implementation (10 marks)

Ans=In Java, an interface specifies the behavior of a class by providing an


abstract type. As one of Java's core concepts, abstraction, polymorphism,
and multiple inheritance are supported through this technology. Interfaces
are used in Java to achieve abstraction. By using the implements keyword,
a java class can implement an interface.

In general terms, an interface can be defined as a container that stores the


signatures of the methods to be implemented in the code segment. It
improves the levels of Abstraction.

Following the brief introduction to Interface in Java, we will now be


exploring why we need it and why we should prefer it over the conventional
way of using an abstract class.

Need for Interface in Java

So we need an Interface in Java for the following reasons:

 Total Abstraction
 Multiple Inheritance
 Loose-Coupling
 So the Syntax of an Interface in Java is written as shown below.
 Interface <Interface Name> {
 //Declare Constant Fields;
 //Declare Methods;
 //Default Methods;
 }
 // interface
 interface Animal {
 public void animalSound(); // interface method (does
not have a body)
 public void sleep(); // interface method (does not
have a body)
 }

 // Pig "implements" the Animal interface
 class Pig implements Animal {
 public void animalSound() {
 // The body of animalSound() is provided here
 System.out.println("The pig says: wee wee");
 }
 public void sleep() {
 // The body of sleep() is provided here
 System.out.println("Zzz");
 }
 }

 class MyMainClass {
 public static void main(String[] args) {
 Pig myPig = new Pig(); // Create a Pig object
 myPig.animalSound();
 myPig.sleep();
 }
 }

Output-

The pig says: wee wee


Zzz

Que-6- What is exception handling explain with example (5 Marks)

Ans=The Exception Handling in Java is one of the powerful mechanism to


handle the runtime errors so that the normal flow of the application can be
maintained.

In this tutorial, we will learn about Java exceptions, it's types, and the
difference between checked and unchecked exceptions.

What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the


program. It is an object which is thrown at runtime.
What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException,
etc.

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }

Que-7- Write a java program for linear search handling following exception (10
marks)

A) ArrayIndexOutOfBounds=

// Importing generic Classes/Files


import java.util.*;

public class GFG {

// Main driver method


public static void main(String args[])
throws ArrayIndexOutOfBoundsException
{

// Taking input from user


Scanner s = new Scanner(System.in);

// Storing user input elements in an array


int arr[] = new int[5];
// Try block to check exception
try {
// Forcefully iteration loop no of times
// these no of times > array size
for (int i = 0; i < 6; i++) {

// Storing elements through


nextInt()
arr[i] = s.nextInt();
}
}
catch (ArrayIndexOutOfBoundsException e) {
// Print message when any exception
occurs
B) System.out.println(
"Array Bounds Exceeded...\nTry
Again");
}
}
}
Output:
10
20
30
40
50
60

B)Input Mismatch=

1. // import required classes and packages


2. package javaTpoint.MicrosoftJava;
3. import java.util.InputMismatchException;
4. import java.util.Scanner;
5. // create class InputMismatchExample1 to understand how Scanner throws
InputMismatchException
6. public class InputMismatchExample1 {
7. // main() method start
8. public static void main(String[] args) {
9. // create scanner class object
10. Scanner sc = new Scanner(System.in);
11. // use try-
catch block for taking input from the user and handling exception
12. try {
13. System.out.println("Enter value of a to get its square value:");
14. Integer a = sc.nextInt(); // we give any float value as input
15. System.out.println((a*a));
16. }
17. catch (InputMismatchException ex) {
18. System.out.println(
19. ex);
20. }
21. }
22. }

Que-8- What is finally block? Explain with example (5 marks)

Ans= Java finally block is a block used to execute important code such as
closing the connection, etc.

Java finally block is always executed whether an exception is handled or


not. Therefore, it contains all the necessary statements that need to be
printed regardless of the exception occurs or not.

The finally block follows the try-catch block.

1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }

Que-9- Write a java program to perform arithmetic exception (5 marks)

1. Ans= public class ArithmeticException


2. {
3. void divide(int a, int b)
4. {
5. // performing divison and storing th result
6. int res = a / b;
7. System.out.println("Division process has been done successfully.");
8. System.out.println("Result came after division is: " + res);
9. }
10.
11. // main method
12. public static void main(String argvs[])
13. {
14. // creating an object of the class ArithmeticException
15. ArithmeticException obj = new ArithmeticException();
16. obj.divide(1, 0);
17. }
18. }

Que-10- Explain try and catch block with example (10 marks)

Ans= Java try block

Java try block is used to enclose the code that might throw an exception. It must
be used within the method.

If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute. So, it is recommended not to keep the code in try
block that will not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch

1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block

1. try{
2. //code that may throw an exception
3. }finally{}
Java catch block

Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception (
i.e., Exception) or the generated exception type. However, the good approach is to
declare the generated type of exception.

1. public class TryCatchExample2 {


2.
3. public static void main(String[] args) {
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }

You might also like