0% found this document useful (0 votes)
49 views9 pages

Java Unit 4

Java unit 4

Uploaded by

dhirupadaswan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
49 views9 pages

Java Unit 4

Java unit 4

Uploaded by

dhirupadaswan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 9
KHARAT ACADEMY Subject ~ fave Programming GPR * (IMP Questions with Answers) SAME RRT IN 1 Scheme = MStr Branches: (O/CM/CW/IF (Weightage - 12 Marks) | 1. Define error, List types of error. Answer; | Errors are mistakes that can make a program go wrong. Errors may be logical or may | be typing mistakes. An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash. Errors are broadly classified into two categories: | 1. Compile time errors 2. Runtime errors 2. Enlist any four compile time errors. Answer: 1) Missing semicolon 2) Missing of brackets in classes and methods 3) Misspelling of variables and keywords. 4) Missing double quotes in Strings. 5) Use of undedlared variable. 6) Incompatible type of assignment/initialization. 7) Bad reference to object 3. Write the syntax of try-catch-finally blocks. /fStatements to be monitored for any exception }.catch(ThrowableInstance! obj) //Statements to execute if this type of exception oceurs } eatch(Throwableinstance2 obj2) { / [Statements Jinally { KHARAT ACADEMY 7/Statements which should be exvetited even If any exceptlon happens | An exception is a problem that arises during the execution of a program. Javé exception | handling is used to handle error conditions In a program systematically by: king t the. j| Necessary action | Built-in exceptions: 1) Arithmetic exception: Arithmetic error such as division by zcro. 2) ArrayindexOwOfBounds Exception: Array index is out ofbound |» 3) ClassNotFoundException 4) FileNotFoundException: Caused by an attempt to access a nonexistent file. 5) 10 Exception: Caused by general 1/0 failures, such as inability to read froma file. 6) NullPointerException: Caused by referencing a null object. 7) NumberFormatException: Caused when a conversion between strings and \ number fails. ; i 8) StringIndexOutOfBoundsException: Caused when a program attempts toaccess a | nonexistent character position in a string. | 9) OutOfMemoryException: Caused when there's not enough memory toallocatea | | new object. i | 10) SecurityException: Caused when an applet tries to perform an action not ! i | allowed by the browser's security setting. i _ 41) StackOverflowException: Caused when the system runs out of stack space. 5, Explain exception handling mechanism w.r.t. try, catch, throw and finally, y | i try: Program statements that you want to monitor for exceptions are contained within | a try block. Jf an exception occurs within the try block, It is thrown, | catch: Your code can catch this exception (using catch) and handle it in some rational manner, System-generated exceptions are automatically thrawn by the Java runtime system. A catch block immediately fallaws the try black. The catch black can have ane or more statements that are necessary to i ‘o¢ess the exception. Syntax: KUARAT ACADEMY catch (ExceptionTypel exOb) { // exception handler for ExceptionType1 } | throw: It is mainly used to throw an instance of user defined exception. Example: throw new myException(“Invalid number"); assuming myException as a user defined exception finally: finally block is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exceptions | handicd or not. Java finally block follows try or catch block. Syntax: finally t Ca /{ block of code to be executed before try block ends ‘ } G. Explain the two ways of creating threads in Java. | Answer: | Thread is a independent path of execution create a th nin a program. There are two ways to (1) By extending the Thread c ‘Thread class provide constructors and m ate and perform operations on a thread. This class implements the Kunnatee 4 end the class Thread, we need to implement the methe 1) Once we create an object, we can call cttace, When we the start() of the thread class or executing th Ep: class MyThread extends Thread { public void run() { for(int i= Lzis=20;i++) { System.out.printin(i); *s{public static void main(String a[]) { MyThread t = new MyThreadQ; tstart(); } ya (41) By implementing the runnable interface. KHARAT ACADEMY Runnable interface has only on ane niethou- run{). Eg: : class MyThread implements Runnable { public void ranQ { for(int i= 1;i<=20;1+4) { System.out.printin(i); } public static void main(String a[]) ( MyThread m = new MyThread() Thread t = new Thread(m); tstart(); } 7. Explain life cycle of thread. 2 | Answer: wf 4 } Thread Life Cycle Thread has five different states throughout its life. 1. Newborn State & , 2. Runnable State 3. Running State 4, Blocked State | 5. Dead State Thread should be in any one state of above and it can be move from one state to. another by different methods and ways. | Newborn state: When a thread object is created It is sald to be ina new born state. When the thread is in a.new born state it is not scheduled running from this state it can be scheduled for running by start() or killed by stop(). If put in a queue it moves to runnable state. Runnable State: It means that thread is ready for execution and Is waiting for the availability of the processor i.e. the thread has joined the queue and Is waiting for execution. If all threads have equal priority, then they are given time slots for execution in rourid’robin fashion. The thread that relinquishes contral joins the queue at the end {and again waits for its turn. A thread can relinquish the control to anether before its turn comes by yield(). Running State: {t means that the pracessor has given its time to the thread for execution. The thread runs until it relinquishes contral on its own or itis pre-empted by a higher priority thread. Poss KHARAT ACADEMY “Blocked state: A thread can be temporarily suspended or blacked from entering into the runnable and running state by using either of (he following thread method, 1) suspend() : Thread can be suspended by this method, It can be rescheduled by resume(). 2) wait(): Ifa thread requires to wait until some event occurs, it can be done using wait method and can be scheduled to run again by notify (). 3) sleep(): We can puta thread to slecp for a specified time period using sleep(time) where time is in ms, it re-enters the runnable state as soon as period has elapsed /over Dead State: Whenever we want to stop a thread form running further we can call its stop().The statement causes the thread to move to a dead state. A thread will also move to dead statc automatically when it reaches to end of the method. The stop method may be used when the premature death is required. 8. Write a program to create two threads one thread will II print even no. between 1 to 50 and other will print odd number between 1 to 50. Answer: import javaJang.*; class Even extends Thread { public void run() { ary { a’ for(int i=2;i<=50;i=i System.out.printin(“\t Even thread :"+i); sleep(500); ) < } catch(InterruptedException e) (System.outprintin(“even thread interrupted"); } class Oga extends Thread ( public void run() { i by Faint i= Tji< =50;i=1+2) { System-outprintin("\t Even thread 41); sleep(500); } catch(InterruptedException e) {System.ont.printin(“even thread interrupted"); } KHARAT ACADEMY F class Odd extends Thread { public void run() { try ( forfint f= 1s1< 50;i=142) ( System.outprintIn("\t Odd thread :"+i); steep(500); } ) catch(InterruptedException e) { System.out.printIn("odd thread interrupted"); class EvenOdd { public static void main(String args[}) { new Even().start(); new Odd().start(); } } 9. Write a Java program in which thread A will display the even numbers between 1 to 50 and thread B will display the odd numbers between 1 to 50, After 3 iterations thread A should go to sleep for 500ms. Answer: Import ja adang.*; class A extends Thread { public void run) uy{ % for(int =2:1<=50;i=142) { { System.outprintl n("\tA thread :"+i); } catch(Exception e) { 7 System.outprintIn("A thread interru pted"); KHARAT ACADEMY class B extends Thread { public void run() { try{ for(int i=1i< 50;i=142) { System.outprintin("\t B thread :"+4); } } catch(Exception e) { System.outprintIn("B thread interrupted"); class OddEven { public static void main(String args[)) { ; new A().start(); . new B().start(); } ia ) 10, Write a program to Input name and salary of employce and throw user defined exception ifentered salary Is negative. Answer: import Java.io. class NegativeSalary Exception extends Exception { } public NegativeSalaryException (String str) { super(stt}in. public dass 1 { : : “Public static void main(String] args) throws lOException { BufferedReaderbr= new BufferedRe: InputStreamReader(System.in)); Systemout print("Enter Name of employee"); String name = brreadLine(); ader(new System.outprint(Enter Salary of employee"); int salary = Integer.parsel at(br.readLine(}); KHARAT ACADEMY Try ( if{salary< 0) throw new NegativeSalaryException(” Enter Salary amount isnegative"); System.outprintin("Salary is “+salary); J catch (NegativeSalaryException a) { System.out printin(a); } } I 11, Write a program to create two threads. One thread will display the numbers from 1 to 50 (ascending order) and other thread will aisplay, numbers from 50 to 1 (descending order). Answer: I class Ascending extends Thread [ public void run() { for(int be 1; 4: “UGiee) { Systemoutprintin(*Asce: ag Theead 7 + i): class Descending extends Thread { public void runQ { for(int i= 15; i>0;1--) { System.outprinda("Descending Thread : * + i); publie static void main(String]] args) { Ascending a=new Ascending); astart(); Descending d=new Descending(); KHARAT ACADEMY

You might also like