Thursday, January 24, 2019

Java Unit 3 OOP Concept - Exception Handling, Threading and Streams Programming for B.C.A., M.C.A. and all IT Students


--------------------------------------------------------------------------------------------------------------------------
Prepared By : Uday Shah (HOT - IT)
Contact No : 7600044051
E-Mail: rupareleducation@gmail.com


Exception Handling, Threading and Streams (Input and Output)

Question 1: Introduction to Exception Handling
·      An exception is an abnormal condition that arises in code sequence at runtime so, we can say than an exception is runtime error.
·      An exception is an “unwanted or unexpected event”, which occurs during the execution of the program i.e, at run-time, that disrupts the normal flow of the program’s instructions. When an exception occurs, execution of the program gets terminated.
·     An exception can occur due to several reasons like Network connection problem, Bad input provided by user, Opening a non-existing file in your program etc
·         All exception in java are handle by super class throwable.
·         The throwable class has two subclass that is exception and error.
·         Exception has two subclass IOException and RuntimeException.
·         An exception is an object that is generated at runtime, when java interpreter encounter an error such as.
1.      Integer devide by 0
2.      Array index negative or out of range
3.      Elligal cast
4.      Intrupt input output operation
5.      Unexpected EOF condition
6.      Incorrect number of format
·         Etc... Are some predefine exceptions which can be handle by the java programming using try, catch, finally, throw and throws keywords
·         Following is general syntax for exception handling.
      try
      {
                  Executable statement
      }
      catch (Exception type Exception object)
      {
                  Handle the exception
      }
      finally
      {
                  Statements
      }
 ·    According to above syntax try block contain more than one executable statements that may arise exception at runtime.
·       If any exception is found it immediately transfer the cursor to the appropriate catch block.
·     Finally block is always execute even try block get successfully or may generate error in their code.
·     Throw is system generated exception are automatically thrown by the java runtime system now if you want to manually thrown an exception we have to use throw keyboard.
·      Throws means any exception that is thrown out of method must be specified by a throws keyword.
·  try: The try block contains set of statements where an exception can occur.try{// statement(s) that might cause exception}
·      catch : Catch block is used to handle the uncertain condition of try block. A try block is always followed by a catch block, which handles the exception that occurs in associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
·         throw: Throw keyword is used to transfer control from try block to catch block.
·         throws: Throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.
·      Finally: It is executed after catch block. We basically use it to put some common code when there are multiple catch blocks.
·       Inside the java standard package java.lang defines several exceptions.

1.      ArithmeticException : Arithmetic exception such as divide by 0

2.      ArrayIndexOutOfBoundException : Array Index is out of bound.

3.      ArrayStoreException : Assignment to an array element of incompatible type.

4.      ClassCastException: Invalid cast.

5.      IllegalArgumentException : Illegal argument use to invoke a method.
6.      NegativeArraySizeException: Array creates with negative size.

7.      NullPointerException: Invalid use of null reference.

8.      NumberFormatException: Invalid conversion of string to a number format.

                        Etc...  Are exceptions which are supported by java language at run time.

class Abc
{
            public static void main(String []args)
            {
                        int a=10,b=0,c=0;
                        System.out.println(“Demo”);
                        try
                        {
                                    try
                                    {
                                                System.out.println(“ “+a1[2]);
                                    }
                                    catch
                                    {
                                                System.out.println(“Error”);
                                    }
                                    c=a/b;
                        }
                        catch (ArithmeticException e)
                        {
                                    System.out.println(“Arithmetic”);
                        }
                        catch(Exception e)
                        {
                                    System.out.println(“Error”);
                        }
                        System.out.println(“Answer is : ”+c);
                        System.out.println(“After Exception”);
            }
}
Question 2 : Creating user define Exception class

·    Java provides built in exception to handle most common error although it support user define   exception class which is as subclass of Throw able.
·     The Exception class does not define any method of its own class it inherit a methods provided by   throw able.
·         On Exception class have several method and it can be use at the time of creating an exception.

class Abc extends Exception
{
      Abc(String str)
      {
                  System.out.println(“String is : ”+str);
      }
      public static void main(String []args)
      {
                  Abc a1=new Abc(“Hello”);
                  try
                  {
                              throw a1;
                  }
                  catch(Exception e)
                  {
                              System.out.println(“Error : ”+e);
                  }
      }
}

Question 3 : Thread and it’s life cycle.

·     A thread is often defined as a single sequence flow of control within a program they may be several  thread in one process.
·      Thread dies not have its own address space but use the memory and other resources of the process in  which it execute.
·      The JVM manage this and schedule them for execution.
·     A thread is similar to a program that has single flow of control infect all program has at least one   thread.
·         Java enable us to use multiple flow of control in developing programming.
·         Each flow control may be thought as a separate tiny program as a thread that runs in parallel to other.
·         A program that contains multiple flow of control is known as multithreaded programming.
·         Multithreaded is a specialized form of multitasking.
·         There are 2 types of multitasking process base & thread base.
·      Process base multitasking allow the computer to run 2 or more program concurrently for example. Text editor is being used at the sometime calculator is working, report from the excel may be taken

etc...

Thread base multitasking means single program can perform 2 or more task simultaneously for example test editor can format text at that time it is printing this 2 action are perform by the 2 separate thread.

Thread life cycle:

            A thread can be one of the five states. The life cycle of the thread in a java is control by JVM. 
            Following is a list of java state thread.
1.      New born state
2.      Runnable state
3.      Running state
4.      Block state
5.      Dead state.

1.      New born state :
When we create a new thread object the thread is set to be in a new born state.
The thread is not yet schedule for running at this state we can do only one of the following.
Either schedule it for running using start method or kill it using stop method.
If we schedule it for running then it move to runnable state.

2.      Runnable state :
The runnable state means that the thread is ready for execution. The thread has join the queue of threads that are waiting for execution or waiting for availability of the process.
 If all thread have equal priority then they are given time slot for execution in round robin fashion it means first come first server method.

3.      Running state :
A running means that the processor has given its time to the thread for it’s execution the threads run until control release it or kill the process during the running thread.

A running thread may release its control in a following situation.

It has been  suspended using suspend() method. This has been made to told to wait until some event occur using wait() method.

4.      Block state :
A thread is said to be black when it is prevented from entering into the runnable state and subsequently into the running state.

This happen when the thread is suspended, sleeping or waiting in order to satisfied certain requirement.

5.      Dead state :
A running thread ends it’s life when it has completed it’s execution using run method. It’s call natural death.

However we can kill it by sending them the stop message to it at any state then it call prematurely death.

A thread can be dill as soon as it is born or wait for the running.

Question 4 : Thread class and its method
            Thread class is use for multithreading, multi tasking execution system define by the java.lang.
            Some of the constructor for the thread class are as follow that is

            thread()
            thread(runnable r)
            thread(runnable r, string s)
            thread(string s)

           According to above a list of constructor r is a reference to an object that implement runnable               interface and s as a string use to identify a thread.

           Following is some list of method of thread class.

1.     currentThread()                  :           It return reference to the current thread.
2.     sleep(long millisecond)      :           It cause the current thread to wait for millisecond.
3.  void sleep(long millisecond)         :           It cause the current thread to wait for millisecond.
4.      String getName()                :           It return the name of the thread.
5.      int getPriority()                   :           It return the priority of the thread.
6.      void setName(String s)       :           Set the name of the thread.
7.      void setPriority(int p)         :           Set the priority of the thread.
8.      void start()                         :           start the thread.
9.      void run()                          :           to run the thread.
10.  boolean isaLive()               :           It return true if thread has been started and not yet                                                die otherwise return false.
            Extend from thread class

            class TDemo extends Thread
            {
                        public void run()
                        {
                                    try
                                    {
                                                for(i=1;i<=10;i++)
                                                {
                                                            Thread.sleep(2000);
                                                            System.out.println(“Thread Demo”);  
                                                }
                                    }
                        }
            }

       
Question 5 : Synchronization in multiple threads.

       When 2 or more thread need to use shared resource they need some way to ensure that the                     resource will be used by only one thread at a time.
       When thread being execution a synchronize instance method it automatically acquire a lock on            that object.
        The lock is automatically released when the method complete it’s execution.
       Only one thread has this lock at a time there for only one thread may execute any of the                         synchronize instance method for that some object at particular time.
        If second thread attempt to execute a synchronized instance method for that same object.
        The JVM automatically cause the second thread to wait until the first thread release the lock.
       When thread a begin execution a synchronize static method it automatically acquire a lock its               associated class object.
        
Question 6: Demon & Non-Daemon Thread.

             Daemon thread in java is a service provider thread that provide service to the user thread.
             It’s life depend on the user thread it means when the all user thread did JVM terminate this                  thread automatically.
            There re many Java Daemon Thread running automatically.

            For Ex. Garbage collector, finalizer etc...

            Following is some important point of about Daemon thread in JAVA.

            It provide service to user thread for background supporting task.
            It’s life depend on user thread.
            It is low priority thread.


:: Best Of Luck ::

 Please share and comment it... Thank you