Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Unit IV - Java Programming Answers

Blink

Uploaded by

likithbas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
9 views

Unit IV - Java Programming Answers

Blink

Uploaded by

likithbas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
UNIT -IV Java Programming - Dr. G. Bala Narasimha I. a) What is exception handling? Explain an example of exception handling in the case of division by zero. Ans: In Java, exception is an event that occurs during the execution of a program and disrupts the normal flow of the program's instructions, which aborts/terminates the program. + In java, when the interpreter encounters a run-time error, it creates an exception object and throws it. + If the exception object is not caught and handled properly, it terminates the program + Exceptions are not recommended, therefore these exceptions are to be handled to continue the execution of the program. Program: import java.util.Scanner; class Exception { Scanner input = new Scanner(System.in); void Div(){ try{ System.out.print("Enter the Numerator: int a = input.nextInt(); System.out print("Enter the Denominator: "); int b = input.nextInt(); int res = a/b; System.out.printIn(""The Quotient is: "+res); )5 catch (ArithmeticException e1) { //Handling the Exception System.out.printIn("You gave the Denominator as Zero") } public static void main(String[] args) { Exception! El = new Exception|(); EL.DivQ; } } Input: Enter the Numerator: 20 Enter the Denominator: 0 Output: You gave the Denominator as Zero. Java Programming - Dr. G. Bala Narasimha b) Write a Java program that illustrates the application of multiple catch statements. Ans: Program: public class MultipleCatchBlock{ //class Starts public static void main(String[] args) { /main method starts try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e){ System.out.printin("Arithmetic Exception occurs"); ) } cateh(ArrayIndexOutOfBoundsException e) { ‘System. out printin(”"ArrayIndexOutO {Bounds Exception occurs"); } } cateh(Exception e) { System.out.printin("Parent Exception occurs"); 3 System.out.printin("Rest of the code"); } Ymain method ends } Melass Ends Output: Arithmetic Exception occurs Rest of the code Java Programming - Dr. G. Bala Narasimha 2. a)What are the advantages of using the exception handling mechanism? Ans: 1. Error Detection and Debugging: Exception handling helps detect errors and exceptions that occur during program execution, making it easier to identify and debug issues 2. Program Robustness: By handling exceptions gracefully, you can prevent your program from crashing or terminating abruptly due to unexpected conditions, improving its robustness. 3. Separation of Error-Handling Logic: Exception handling allows you to separate error-handling logic from the main program flow, making your code more organized and maintainable. 4. Maintainability: Makes code more maintainable and readable by clearly delineating error-handling code from regular program logic. . Enhanced User Experience: Properly handled exceptions contribute to a more user-friendly experience by presenting meaningful error messages b)Explain Java exceptions keywords with an example code. In Java exceptions can be handled using five keywords. The following table describes each. Lay > The “try” keyword is used to specify a block where we place the code/program to monitor/observe the exceptions. > If an exception occurs in try block, it is thrown (informs to the user/programmer). > The try block must be followed by either catch or finally. 2. catch >» The "catch" block is used to handle the exception. » It must be preceded by try block , means we can't use catch block alone. > Itcan be followed by finally block later. 3. finally > The "finally" block is used to place the code that must be executed, whether an exception is handled or not. 4. throw » The "throw" keyword is used to manually throw an exception. J. throws > The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. > It doesn't throw an exception. It is always used with method signature. Java Programming - Dr. G. Bala Narasimha 3. a) Explain in detail Java’s built-in exceptions. Java provides a variety of built-in exceptions, which are organized under two main categories: checked exceptions and unchecked exceptions. i) Checked Exceptions Checked exceptions are those that are checked at compile-time. They must be either caught or declared in the method signature using the throws keyword. a) IOException: Thrown when an /O operation fails or is interrupted. b) FileNotFoundException: Thrown when an attempt to open a file denoted by a specified pathname has failed. c) SQLException: Thrown when there is a database access error or other errors related to SQL operations d) ClassNotFoundException: Thrown when an application tries to load a class through its string name but no definition for the class with the specified name could be found. ii) Unchecked Exceptions Unchecked exceptions are those that are not checked at compile-time, meaning they can be thrown at runtime and do not need to be declared in a method's throws clause. i) RuntimeExcepti The superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. Some common subelasses are: ii) | NullPointerExceptio : Thrown when an application attempts to use null where an object is required. iii) ArrayIndexOutOfBoundsException: Thrown to indicate that an array has been accessed with an illegal index. iv) MlegalArgumentException: Thrown to indicate that a method has been passed an illegal or inappropriate argument. Java Programming - Dr. G. Bala Narasimha vy) NumberFormatException: A subclass of IllegalArgumentException, thrown when an attempt is made to convert a string to a numeric type but the string does not have the appropriate format. vi) ArithmeticException: Thrown when an exceptional arithmetic condition has occurred, such as division by zero. b) Write a program with nested try statements for handling exceptions. public class NestedTry { public static void main(String[] args) { try{ /Outer try block int res = 30/0; //Arithmetic exception raises in Outer try System.out.printIn(res); try{, Anner try block int array[] = new int[5]; array[3] = 30; } cateh(ArrayIndexOutOfBoundsException i){ /Anner Catch Block System.out.println("Caught the Inner Exception"); } 4 } catch (ArithmeticException O){ /Outer Catch Block System. out.printIn("Caught the Outer Exception”); } } Output: Caught the Outer Exception Java Programming - Dr. G. Bala Narasimha 4, a) Explain how to create your own exception in a Java program. Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, the user can also create exceptions which are called ‘user- defined Exceptions”. 1) Create the new exception class extending Exception class 2) Create a public constructor for a new class with string type of parameter 3) Pass the string parameter to the super class 4) Create try block inside that create a new exception and throw it based on some condition 5) write a catch block and use some predefined exceptions 6) write the optionally finally block. Program: import java.util Scanner; class Age Exception extends Exception { public Age Exception (String message) { super(message); } public class UserException { static Scanner input = new Scanner(System.in); public static void VoterAge() { try { System.out printin("Enter the age: "); int age = input.nextInt(); if (age<18) { throw new Age_ Exception ("He/she is below 18 Years"); } else { System.out.printIn("Person is eligible to vote"); } } catch (Age Exception ¢){ System.out.printIn("Error: " + e.getMessage()); } } public static void main(String args[]){ VoterAge(); } } Input: Enter the age: 15 Output: He/she is below 18 Years. Java Programming - Dr. G. Bala Narasimha b) Write a Java program that illustrates the try-catch-finally clause. > 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. Program: public class TestFinally { public static void main(String args[]) { try { //below code throws divide by zero exception System.out.println("Inside the try block"); int data=25/0; System.out.printin(data); } catch(NullPointerException e){ System.out.printIn(e); //cannot handle Arithmetic type exception //can only accept Null Pointer type exception } finally { //executes regardless of exception occured or not System.out.printin("finally block is always executed"); } } Output: Inside the try block finally block is always executed Exception in thread “main” java.lang.ArithmeticException: /by zero Java Programming - Dr. G. Bala Narasimha 5. Explain the following: a) Checked exceptions and Unchecked exceptions. Checked exceptions: + Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. + The compiler ensures whether the programmer handles the exception or not. + The programmer should have to handle the exception; otherwise, the system has shown a compilation error. * The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. UnChecked exceptions: + The unchecked exceptions are just opposite to the checked exceptions. + The compiler will not check these exceptions at compile time. + Usually, it occurs when the user provides bad data during the interaction with the program. * The classes that inherit the RuntimeException are known as unchecked exceptions. Eg: ArithmeticException, IllegalArgumentException, IndexOutOfBoundsException, NegativeArraySizeException and NullPointerException. Java Programming - Dr. G. Bala Narasimha b)Explain the difference between throw and throws keywords in Java. Name throw throws Definition Java throw keyword is | Java throws keyword is used in used throw an exception | the method signature to declare explicitly in the code,| an exception which might be inside the function or the | thrown by the function while block of code. the execution of the code. Type of Using throw keyword, we | Using throws keyword, we can exception can only propagate} declare both checked and unchecked exception i.e., | unchecked exceptions. the checked exception | However, the throws keyword cannot be propagated using] can be used to propagate throw only. checked exceptions only. ‘Syntax The throw keyword is[The throws keyword is followed by an instance of | followed by class names of Exception to be thrown. _| Exceptions to be thrown. Declaration throw is used within the | throws is used with the method method. signature. Internal We are allowed to throw} We can declare — multiple implementation | only one exception at a| exceptions using throws time i.e. we cannot throw | keyword that can be thrown by multiple exceptions. the method. For example, main() throws IOException, SQLException. Java Programming - Dr. G. Bala Narasimha 6. a) Define the following: () Single-tasking: Single tasking in computing refers to the ability of an operating system to manage single task at a time. Eg: DOS (i) Multitasking: Multitasking in computing refers to the ability of an operating system to manage multiple tasks at the same time. Eg: Windows. Multiprocessing: > Multi process in computing refers to the ability of an operating system to manage multiple processes / programs at the same time. > Multiprocessing requires more than one CPU to increase computing power, speed and memory. (iv) Multithreading: Multithreading in computing refers to a single process with multiple code segments (Threads) run concurrently and parallel to each other to increase computing power b) Explain creating a thread by extending the thread class with an example code. class A extends Thread { public void run(){ for (int i=1;i<=2:i+4)} System.out.printIn(“Thread A:"+i);} System.out.printIn(“Thread A Executed"); } t class Main{ public static void main(String[] args){ Atl =new AQ); tl. start(); } Java Programming - Dr. G. Bala Narasimha 7. a) What is the differentiate between a thread and a process. Process Thread 1 | Process means any program is in| Thread means a segment of a execution. process. 2 | The process is isolated. Threads share memory. 3| The process does not share data | Threads share data with each other. with each other. 4 | The process is less efficient in | Thread is more efficient in terms of terms of communication. communication. 5 |The process is called the|A Thread is lightweight as each heavyweight process. thread in a process shares code, data, and resources. 6 | The process takes more time to] The thread takes less time to terminate. terminate. It takes more resources. It takes less resources. 8 | If one process is obstructed then | If one thread is obstructed then it will it will not affect the operation of | affect the execution of another another process. process. b) What is the differentiate between multiprocessing and multithreading. x Multi Processing Multi Threading 1 | Multiprocessing involves more | Multithreading involves a single CPU than one CPU (processor) to |(processor)to execute a single process execute the processes /programs | with multiple code segments (i.c., Threads) run concurrently. 2 | Multiprocessing increase | Multithreading uses a single process and computing power, speed and | parallel to each other to increase memory. computing power. 3/Multiprocessing is _for | Multithreading is for hiding latency. increasing speed 4 | Multiprocessing is parallelism _ | Multithreading is concurrency. 5 | Multiprocessing allocates | Multithreading threads belonging to the separate memory and resources | same process share the same memory for each process or program and resources as that of the process. 6 | Multiprocessing is slow | Multithreading is faster compared to compared to multithreading. _| Multiprocessing, 7|Multiprocessing is best for | Multithreading is best for 10. computations. 8 | Less economical. Economical. Java Programming - Dr. G. Bala Narasimha 8. Explain the complete life cycle of a thread with an example code. The life cycle of a thread in Java can be broken down into several states: New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated. Here's an explanation of each state along with a simple example to illustrate these states. Thread Life Cycle States 1. New: A thread is in this state when it is created but not yet started. It is the state when a thread object is instantiated. 2. Runnable: A thread enters this state when start() method is called. The thread is ready to run and is waiting for CPU time. 3. Blocked: A thread enters this state when it is waiting for a monitor lock to enter or re-enter a synchronized block/method. 4. Waiting: A thread is in this state when it is waiting indefinitely for another thread to perform a particular action (e.g., using wait()). 5. Timed Waiting: A thread is in this state when it is waiting for another thread to perform a specific action within a stipulated amount of time (e.g., using sleep(), wait(long timeout), join(long millis)), 6. Terminated: A thread enters this state when it has finished its execution or is terminated due to an exception. Blocked ae von or ce Time Waiting Java Programming - Dr. G. Bala Narasimha Program: class MyThread extends Thread { public void run() { try { System.out.printIn(Thread.currentThread().getName() +" is in RUNNABLE state"); Thread.sleep(2000); // TIMED WAITING state System. out printIn(Thread.currentThread().getName() +" is in TIMED WAITING state"); synchronized (this) { // WAITING state wait(1000); // Waiting for 1 second System.out.println(Thread.currentThread().getName() + " is in TIMED WAITING state"); } synchronized (MyThread.class) { // Blocked state System.out.printIn(Thread.currentThread().getName() +" is in BLOCKED state"); } } catch (InterruptedException e) { e.printStackTrace(); } } 1 t public class ThreadLifecycleDemo { public static void main(String[] args) { MyThread t1 = new MyThread(); System.out-printIn(t1.getName() + " is in NEW state"); // NEW state tlstart(); _// Starting the thread - moves to RUNNABLE state try { tl joinQ; } catch (InterruptedException e) { e.printStackTrace(); System.out.printIn(t1.getName() +" is in TERMINATED state"); My Java Programming - Dr. G. Bala Narasimha 9. List out the ways to create a thread and explain how to create a thread using the Runnable interface. In java, we can create threads in two ways 1, Extending Thread Class 2. Implementing Runnable interface Program: class Newthread implements Runnable { public void run() { /Amplementing the run() method System.out.printin("NewThread started : "); for (int i=1:i<=3:i++){ System.out.println("class A:"+i);} System.out.printin("NewThread Finished"); 1 } class Main { public static void main(String[] args) { Newthread tl = new Newthread(),; /Creating an object of the class Thread Tl = new Thread(tl); /Creating an object of thread class and passing reference tl to the Thread Constructor TL.start(); } } Output: NewThread started : class A:1 class A:2 class A:3 NewThread Finished Java Programming - Dr. G. Bala Narasimha 10. a) How do we set priorities for threads? a) Priority means the number of resources allocated to a particular thread. b) Every thread created in JVM is assigned a priority. The priority range is, between 1 and 10. > Minimum priority is 1 > Normal priority is 5. > Maximum priority is 10. ©) The default priority of any thread is 5. d) It is advised to adjust the priority using the Thread class's constants, Thread.MIN_PRIORITY Thread.NORM_ PRIORITY (ie., 5) Thread. MAX_PRIORITY e) We have the ability to adjust the priority of any thread using setPriority(). Program for setting the priority: public class ThreadPriority extends Thread { public void run (){ System.out printin ("Running thread name is:" + Thread.current Thread(). getName ()); System.out_printIn ("Running thread priority is:" + Thread.currentThread(). getPriority ()); } public static void main (String args[]) { ThreadPriority ml = new ThreadPriority (); m1.setPriority (Thread. MIN_PRIORITY); mL start (); 1} Output: Running thread name is: Thread-0 Running thread priority is:1 Java Programming - Dr. G. Bala Narasimha b) What are interrupting threads? 1. The interrupt() method of thread class is used to interrupt the thread. 2. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behavior and doesn't interrupt the thread but sets the interrupt flag to true. 3. If any thread is in sleeping (sleep()) or waiting state (wait()), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. Program: class A extends Thread { public void run(){ try Thread.sleep(5000); for (int i=1;i<=5;i++){ System.outprintin("Thread A:"'+i); } System.out printIn("Thread A Executed"); } catch (InterruptedException e){ System.out. printin ("Thread A Interrupted"); System.out printin (e); 3 } } } class Main{ public static void main(String[] args) { Atl =new AQ; tl.setName("ThreadA"); tl. start(); System.out.println(tl.getName()+ " is in"+ tl.getState()); tl.interrupt(); System.out.printIn(tl.getName()+ "is interrupted" + tl.isInterrupted()); System.out.printIn(tl.getName()+ "is interrupted" + t] .interrupted()); $ } Java Programming - Dr. G. Bala Narasimha Output: ThreadA is in RUNNABLE Thread A Interrupted java lang InterruptedException: sleep interrupted ThreadA is interrupted true ThreadA interrupted false Java Programming - Dr. G. Bala Narasimha

You might also like