Solution:NIIT/GNIIT Sonugiri0032@gmail.com

Monday, October 19, 2015

Java Command Line Arguments

Java Command Line Arguments
The command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt.
1.    class CommandLineExample{  
2.    public static void main(String args[]){  
3.      
4.    System.out.println("Your first argument is: "+args[0]);  
5.      
6.    }  
7.    }  
1.    compile by > javac CommandLineExample.java  
2.    run by > java CommandLineExample sonoo  
Output: Your first argument is: sonoo

Example of command-line argument that prints all the values
In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop.
1.    class A{  
2.    public static void main(String args[]){  
3.      
4.    for(int i=0;i<args.length;i++)  
5.    System.out.println(args[i]);  
6.      
7.    }  
8.    }  
1.    compile by > javac A.java  
2.    run by > java A sonoo jaiswal 1 3 abc  
Output: sonoo
       jaiswal
       1
       3
       abc
     
Next Topic


Exception Handling in Java
The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the runtime errors so that normal flow of the application can be maintained.
In this page, we will know about exception, its type and the difference between checked and unchecked exceptions.
Exception
  • Dictionary Meaning:Exception is an abnormal condition.
  • In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors.
Advantage of Exception Handling
The core advantage of exception handling is that normal flow of the application is maintained. Exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario:
1.    statement 1;  
2.    statement 2;  
3.    statement 3;  
4.    statement 4;  
5.    statement 5;  
6.    statement 6;  
7.    statement 7;  
8.    statement 8;  
9.    statement 9;  
10. statement 10;  
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the exception will be executed. That is why we use exception handling.


Hierarchy of Exception classes

Types of Exception:
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions:
1.    Checked Exception
2.    Unchecked Exception
3.    Error

What is the difference between checked and unchecked exceptions ?
1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3)Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Common scenarios of Exception Handling where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
1.    int a=50/0;//ArithmeticException  

2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
1.    String s=null;  
2.    System.out.println(s.length());//NullPointerException  

3) Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.
1.    String s="abc";  
2.    int i=Integer.parseInt(s);//NumberFormatException  

4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
1.    int a[]=new int[5];  
2.    a[10]=50//ArrayIndexOutOfBoundsException  
Next


Use of try-catch block in Exception handling:


Five keywords used in Exception handling:

1.    try
2.    catch
3.    finally
4.    throw
5.    throws

try block

Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally block.

Syntax of try with catch block

1.    try{  
2.    ...  
3.    }catch(Exception_class_Name reference){}  

Syntax of try with finally block

1.    try{  
2.    ...  
3.    }finally{}  

catch block

Catch block is used to handle the Exception. It must be used after the try block.

Problem without exception handling

1.    class Simple{  
2.      public static void main(String args[]){  
3.          int data=50/0;  
4.        
5.          System.out.println("rest of the code...");  
6.    }  
7.    }  
Output:Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed i.e. rest of the code... statement is not printed. Let's see what happens behind the scene:

 

The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
·Prints out exception description.
·Prints the stack trace (Hierarchy of methods where the exception occurred).
·Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.

Solution by exception handling

1.    class Simple{  
2.      public static void main(String args[]){  
3.       try{  
4.          int data=50/0;  
5.        
6.       }catch(ArithmeticException e){System.out.println(e);}  
7.          
8.       System.out.println("rest of the code...");  
9.    }  
10.  }  
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
       rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is printed.

Multiple catch block:

If you have to perform different tasks at the occrence of different Exceptions, use multple catch block.
1.    <b><i>Example of multiple catch block</i></b>  
2.      
3.    class Excep4{  
4.      public static void main(String args[]){  
5.       try{  
6.        int a[]=new int[5];  
7.        a[5]=30/0;  
8.       }  
9.       catch(ArithmeticException e){System.out.println("task1 is completed");}  
10.     catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}  
11.     catch(Exception e){System.out.println("common task completed");}  
12.    
13.     System.out.println("rest of the code...");  
14.   }  
15.  }  
Output:task1 completed
       rest of the code...

Rule:At a time only one Exception is occured and at a time only one catch block is executed.



finally block

The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc.
Note:Before terminating the program, JVM executes finally block(if any).
Note:finally must be followed by try or catch block.

Why use finally block?

·finally block can be used to put "cleanup" code such as closing a file,closing connection etc.

Rule: For each try block there can be zero or more catch blocks, but only one finally block.


throw keyword
The throw keyword is used to explictily throw an exception.
We can throw either checked or uncheked exception. The throw keyword is mainly used to throw custom exception.
Example of throw keyword
In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
1.    class Excep13{  
2.      
3.       static void validate(int age){  
4.         if(age<18)  
5.          throw new ArithmeticException("not valid");  
6.         else  
7.          System.out.println("welcome to vote");  
8.       }  
9.         
10.     public static void main(String args[]){  
11.        validate(13);  
12.        System.out.println("rest of the code...");  
13.    }  
14.  }  
Output:Exception in thread main java.lang.ArithmeticException:not valid
Next Topi



throws keyword
The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.
Syntax of throws keyword:
1.    void method_name() throws exception_class_name{  
2.     ...   
3.    }  

Que) Which exception should we declare?
Ans) checked exception only, because:
·unchecked Exception: under your control so correct your code.
·error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError.

Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
There are two cases:
1.    Case1:You caught the exception i.e. handle the exception using try/catch.
2.    Case2:You declare the exception i.e. specifying throws with the method.
Case1: You handle the exception
·In case you handle the exception, the code will be executed fine whether exception occurs during the program or not.
1.    import java.io.*;  
2.    class M{  
3.     void method()throws IOException{  
4.      throw new IOException("device error");  
5.     }  
6.    }  
7.      
8.      
9.    class Test{  
10.     public static void main(String args[]){  
11.      try{  
12.       Test t=new Test();  
13.       t.method();  
14.      }catch(Exception e){System.out.println("exception handled");}     
15.    
16.      System.out.println("normal flow...");  
17.    }  
18.  }  
Output:exception handled
       normal flow...

Case2: You declare the exception
·A)In case you declare the exception, if exception does not occur, the code will be executed fine.
·B)In case you declare the exception if exception occures, an exception will be thrown at runtime because throws does not handle the exception.
A)Program if exception does not occur
1.    import java.io.*;  
2.    class M{  
3.     void method()throws IOException{  
4.      System.out.println("device operation performed");  
5.     }  
6.    }  
7.      
8.      
9.    class Test{  
10.     public static void main(String args[])throws IOException{//declare exception  
11.      Test t=new Test();  
12.      t.method();     
13.    
14.      System.out.println("normal flow...");  
15.    }  
16.  }  
Output:device operation performed
       normal flow...

B)Program if exception occurs
1.    import java.io.*;  
2.    class M{  
3.     void method()throws IOException{  
4.      throw new IOException("device error");  
5.     }  
6.    }  
7.      
8.      
9.    class Test{  
10.     public static void main(String args[])throws IOException{//declare exception  
11.      Test t=new Test();  
12.      t.method();     
13.    
14.      System.out.println("normal flow...");  
15.    }  
16.  }  
Output:Runtime Exception

Difference between throw and throws:
throw keyword
throws keyword
1)throw is used to explicitly throw an exception.
throws is used to declare an exception.
2)checked exception can not be propagated without throws.
checked exception can be propagated with throws.
3)throw is followed by an instance.
throws is followed by class.
4)throw is used within the method.
throws is used with the method signature.
5)You cannot throw multiple exception
You can declare multiple exception e.g.
public void method()throws IOException,SQLException.


Multithreading in Java
1.    Multithreading
2.    Multitasking
5.    What is Thread
Multithreading is a process of executing multiple threads simultaneously.
Thread is basically a lightweight subprocess, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than mulitprocessing because threads share a common memory area. They don't allocate separate memory area so save memory, and context-switching between the threads takes less time than processes.
Multithreading is mostly used in games, animation etc.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:
·Process-based Multitasking(Multiprocessing)
·Thread-based Multitasking(Multithreading)
1)Process-based Multitasking (Multiprocessing)
·Each process have its own address in memory i.e. each process allocates separate memory area.
·Process is heavyweight.
·Cost of communication between the process is high.
·Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.
2)Thread-based Multitasking (Multithreading)
·Threads share the same address space.
·Thread is lightweight.
·Cost of communication between the thread is low.
·Note:At least one process is required for each thread.

What is Thread?
A thread is a lightweight subprocess, a smallest unit of processing. It is a separate path of execution. It shares the memory area of process.
As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.
Note:At a time only one thread is executed.




Life cycle of a Thread (Thread States)
1.    New
2.    Runnable
3.    Running
5.    Terminated
A thread can be in one of the five states in the thread. According to sun, there is only 4 states new, runnable, non-runnable and terminated. There is no running state. But for better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread is controlled by JVM. The thread states are as follows:
1.    New
2.    Runnable
3.    Running
4.    Non-Runnable (Blocked)
5.    Terminated
1)New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2)Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
3)Running
The thread is in running state if the thread scheduler has selected it.
4)Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5)Terminated
A thread is in terminated or dead state when its run() method exits.
Next T

How to create thread:
There are two ways to create a thread:
1.    By extending Thread class
2.    By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
·Thread()
·Thread(String name)
·Thread(Runnable r)
·Thread(Runnable r,String name)
Commonly used methods of Thread class:
1.    public void run(): is used to perform action for a thread.
2.    public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3.    public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
4.    public void join(): waits for a thread to die.
5.    public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6.    public int getPriority(): returns the priority of the thread.
7.    public int setPriority(int priority): changes the priority of the thread.
8.    public String getName(): returns the name of the thread.
9.    public void setName(String name): changes the name of the thread.
10.  public Thread currentThread(): returns the reference of currently executing thread.
11.  public int getId(): returns the id of the thread.
12.  public Thread.State getState(): returns the state of the thread.
13.  public boolean isAlive(): tests if the thread is alive.
14.  public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
15.  public void suspend(): is used to suspend the thread(depricated).
16.  public void resume(): is used to resume the suspended thread(depricated).
17.  public void stop(): is used to stop the thread(depricated).
18.  public boolean isDaemon(): tests if the thread is a daemon thread.
19.  public void setDaemon(boolean b): marks the thread as daemon or user thread.
20.  public void interrupt(): interrupts the thread.
21.  public boolean isInterrupted(): tests if the thread has been interrupted.
22.  public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

1.    public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
·A new thread starts(with new callstack).
·The thread moves from New state to the Runnable state.
·When the thread gets a chance to execute, its target run() method will run.

1)By extending Thread class:
1.    class Multi extends Thread{  
2.    public void run(){  
3.    System.out.println("thread is running...");  
4.    }  
5.    public static void main(String args[]){  
6.    Multi t1=new Multi();  
7.    t1.start();  
8.     }  
9.    }  
Output:thread is running...

Who makes your class object as thread object?
Thread class constructor allocates a new thread object.When you create object of Multi class,your class constructor is invoked(provided by Compiler) fromwhere Thread class constructor is invoked(by super() as first statement).So your Multi class object is thread object now.

2)By implementing the Runnable interface:
1.    class Multi3 implements Runnable{  
2.    public void run(){  
3.    System.out.println("thread is running...");  
4.    }  
5.      
6.    public static void main(String args[]){  
7.    Multi3 m1=new Multi3();  
8.    Thread t1 =new Thread(m1);  
9.    t1.start();  
10.   }  
11.  }  
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitely create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute.
Next Topi

The Thread Schedular:
  • The thread scheduler is the part of the JVM that decides which thread should run.
  • There is no guarantee that which runnable thread will be chosen to run by the thread schedular.
  • Only one thread at a time can run in a single process.
  • The thread schedular mainly uses preemptive or time slicing scheduling to schedule the threads.
Next Topic

Sleeping a thread (sleep() method):

The sleep() method of Thread class is used to sleep a thread for the specified time.Syntax:


Syntax of sleep() method:

The Thread class provides two methods for sleeping a thread:
·public static void sleep(long miliseconds)throws InterruptedException
1.    //<b><i>Program of sleep() method</i></b>  
2.      
3.    class Multi extends Thread{  
4.     public void run(){  
5.      for(int i=1;i<5;i++){  
6.        try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
7.        System.out.println(i);  
8.      }  
9.     }  
10.   public static void main(String args[]){  
11.    Multi t1=new Multi();  
12.    Multi t2=new Multi();  
13.     
14.    t1.start();  
15.    t2.start();  
16.   }  
17.  }  
Output:1
       1
       2
       2
       3
       3
       4
       4
       5
       5
As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on.

Can we start a thread twice?
No. After staring a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. For Example:
1.    class Multi extends Thread{  
2.     public void run(){  
3.       System.out.println("running...");  
4.     }  
5.     public static void main(String args[]){  
6.      Multi t1=new Multi();  
7.      t1.start();  
8.      t1.start();  
9.     }  
10.  }  
Output:running
       Exception in thread "main" java.lang.IllegalThreadStateException
Next  
What if we call run() method directly instead start() method?
·Each thread starts in a separate call stack.
·Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
1.    class Multi extends Thread{  
2.     public void run(){  
3.       System.out.println("running...");  
4.     }  
5.     public static void main(String args[]){  
6.      Multi t1=new Multi();  
7.      t1.run();//fine, but does not start a separate call stack  
8.     }  
9.    }  
Output:running...
1.    //<b><i>Problem if you direct call run() method</i></b>  
2.      
3.    class Multi extends Thread{  
4.     public void run(){  
5.      for(int i=1;i<5;i++){  
6.        try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
7.        System.out.println(i);  
8.      }  
9.     }  
10.   public static void main(String args[]){  
11.    Multi t1=new Multi();  
12.    Multi t2=new Multi();  
13.     
14.    t1.run();  
15.    t2.run();  
16.   }  
17.  }  
Output:1
       2
       3
       4
       5
       1
       2
       3
       4
       5

As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not thread object.
The join() method:
The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
1.    //<b><i>Example of join() method</i></b>  
2.      
3.    class Multi extends Thread{  
4.     public void run(){  
5.      for(int i=1;i<=5;i++){  
6.       try{  
7.        Thread.sleep(500);  
8.       }catch(Exception e){System.out.println(e);}  
9.      System.out.println(i);  
10.    }  
11.   }  
12.  public static void main(String args[]){  
13.   Multi t1=new Multi();  
14.   Multi t2=new Multi();  
15.   Multi t3=new Multi();  
16.   t1.start();  
17.   try{  
18.    t1.join();  
19.   }catch(Exception e){System.out.println(e);}  
20.    
21.   t2.start();  
22.   t3.start();  
23.   }  
24.  }  
Output:1
       2
       3
       4
       5
       1
       1
       2
       2
       3
       3
       4
       4
       5
       5


As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.
1.    //<b><i>Example of join(long miliseconds) method</i></b>  
2.      
3.    class Multi extends Thread{  
4.     public void run(){  
5.      for(int i=1;i<=5;i++){  
6.       try{  
7.        Thread.sleep(500);  
8.       }catch(Exception e){System.out.println(e);}  
9.      System.out.println(i);  
10.    }  
11.   }  
12.  public static void main(String args[]){  
13.   Multi t1=new Multi();  
14.   Multi t2=new Multi();  
15.   Multi t3=new Multi();  
16.   t1.start();  
17.   try{  
18.    t1.join(1500);  
19.   }catch(Exception e){System.out.println(e);}  
20.    
21.   t2.start();  
22.   t3.start();  
23.   }  
24.  }  
Output:1
       2
       3
       1
       4
       1
       2
       5
       2
       3
       3
       4
       4
       5
       5


In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts executing.

getName(),setName(String) and getId() method:
public String getName()
public void setName(String name)
public long getId()
1.    class Multi6 extends Thread{  
2.      public void run(){  
3.       System.out.println("running...");  
4.      }  
5.     public static void main(String args[]){  
6.      Multi6 t1=new Multi6();  
7.      Multi6 t2=new Multi6();  
8.      System.out.println("Name of t1:"+t1.getName());  
9.      System.out.println("Name of t2:"+t2.getName());  
10.    System.out.println("id of t1:"+t1.getId());  
11.    
12.    t1.start();  
13.    t2.start();  
14.    
15.    t1.setName("Sonoo Jaiswal");  
16.    System.out.println("After changing name of t1:"+t1.getName());  
17.   }  
18.  }  
Output:Name of t1:Thread-0
       Name of t2:Thread-1
       id of t1:8
       running...
       After changling name of t1:Sonoo Jaiswal
       running...
    


The currentThread() method:
The currentThread() method returns a reference to the currently executing thread object.
Syntax:
public static Thread currentThread()
1.    //<b><i>Example of currentThread() method</i></b>  
2.      
3.    class Multi6 extends Thread{  
4.     public void run(){  
5.      System.out.println(Thread.currentThread().getName());  
6.     }  
7.     }  
8.     public static void main(String args[]){  
9.      Multi6 t1=new Multi6();  
10.    Multi6 t2=new Multi6();  
11.    
12.    t1.start();  
13.    t2.start();  
14.   }  
15.  }  
Output:Thread-0
       Thread-1
  

Naming a thread:

The Thread class provides methods to change and get the name of a thread.
1.    public String getName(): is used to return the name of a thread.
2.    public void setName(String name): is used to change the name of a thread.

Example of naming a thread:

1.    class Multi6 extends Thread{  
2.      public void run(){  
3.       System.out.println("running...");  
4.      }  
5.     public static void main(String args[]){  
6.      Multi6 t1=new Multi6();  
7.      Multi6 t2=new Multi6();  
8.      System.out.println("Name of t1:"+t1.getName());  
9.      System.out.println("Name of t2:"+t2.getName());  
10.     
11.    t1.start();  
12.    t2.start();  
13.    
14.    t1.setName("Sonoo Jaiswal");  
15.    System.out.println("After changing name of t1:"+t1.getName());  
16.   }  
17.  }  
Output:Name of t1:Thread-0
       Name of t2:Thread-1
       id of t1:8
       running...
       After changeling name of t1:Sonoo Jaiswal
       running...
     
 

The currentThread() method:

The currentThread() method returns a reference to the currently executing thread object.

Syntax of currentThread() method:

  • public static Thread currentThread(): returns the reference of currently running thread.
  •  

Example of currentThread() method:

1.    class Multi6 extends Thread{  
2.     public void run(){  
3.      System.out.println(Thread.currentThread().getName());  
4.     }  
5.     }  
6.     public static void main(String args[]){  
7.      Multi6 t1=new Multi6();  
8.      Multi6 t2=new Multi6();  
9.      
10.    t1.start();  
11.    t2.start();  
12.   }  
13.  }  
Output:Thread-0
       Thread-1
 

Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

3 constants defiend in Thread class:

1.    public static int MIN_PRIORITY
2.    public static int NORM_PRIORITY
3.    public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:

1.    class Multi10 extends Thread{  
2.     public void run(){  
3.       System.out.println("running thread name is:"+Thread.currentThread().getName());  
4.       System.out.println("running thread priority is:"+Thread.currentThread().getPriority());  
5.      
6.      }  
7.     public static void main(String args[]){  
8.      Multi10 m1=new Multi10();  
9.      Multi10 m2=new Multi10();  
10.    m1.setPriority(Thread.MIN_PRIORITY);  
11.    m2.setPriority(Thread.MAX_PRIORITY);  
12.    m1.start();  
13.    m2.start();  
14.     
15.   }  
16.  }     
Output:running thread name is:Thread-0
       running thread priority is:10
       running thread name is:Thread-1
       running thread priority is:1
       
 
Synchronization
Synchronization is the capability of control the access of multiple threads to any shared resource. Synchronization is better in case we want only one thread can access the shared resource at a time.
Understanding the concept of Lock
Synchronization is built around an internal entity known as the lock or monitor.Every object has an lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.
Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
1.    Class Table{  
2.      
3.    void printTable(int n){//method not synchronized  
4.       for(int i=1;i<=5;i++){  
5.         System.out.println(n*i);  
6.         try{  
7.          Thread.sleep(400);  
8.         }catch(Exception e){System.out.println(e);}  
9.       }  
10.    
11.   }  
12.  }  
13.    
14.  class MyThread1 extends Thread{  
15.  Table t;  
16.  MyThread1(Table t){  
17.  this.t=t;  
18.  }  
19.  public void run(){  
20.  t.printTable(5);  
21.  }  
22.    
23.  }  
24.  class MyThread2 extends Thread{  
25.  Table t;  
26.  MyThread2(Table t){  
27.  this.t=t;  
28.  }  
29.  public void run(){  
30.  t.printTable(100);  
31.  }  
32.  }  
33.    
34.  class Use{  
35.  public static void main(String args[]){  
36.  Table obj = new Table();//only one object  
37.  MyThread1 t1=new MyThread1(obj);  
38.  MyThread2 t2=new MyThread2(obj);  
39.  t1.start();  
40.  t2.start();  
41.  }  
42.  }  
Output: 5
       100
       10
       200
       15
       300
       20
       400
       25
       500
      

Solution by synchronized method
  • If you declare any method as synchronized, it is known as synchronized method.
  • Synchronized method is used to lock an object for any shared resource.
  • When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the method returns.
1.    //Program of synchronized method  
2.    Class Table{  
3.     synchronized void printTable(int n){//synchronized method  
4.       for(int i=1;i<=5;i++){  
5.         System.out.println(n*i);  
6.         try{  
7.          Thread.sleep(400);  
8.         }catch(Exception e){System.out.println(e);}  
9.       }  
10.    
11.   }  
12.  }  
13.    
14.  class MyThread1 extends Thread{  
15.  Table t;  
16.  MyThread1(Table t){  
17.  this.t=t;  
18.  }  
19.  public void run(){  
20.  t.printTable(5);  
21.  }  
22.    
23.  }  
24.  class MyThread2 extends Thread{  
25.  Table t;  
26.  MyThread2(Table t){  
27.  this.t=t;  
28.  }  
29.  public void run(){  
30.  t.printTable(100);  
31.  }  
32.  }  
33.    
34.  class Use{  
35.  public static void main(String args[]){  
36.  Table obj = new Table();//only one object  
37.  MyThread1 t1=new MyThread1(obj);  
38.  MyThread2 t2=new MyThread2(obj);  
39.  t1.start();  
40.  t2.start();  
41.  }  
42.  }  
Output: 5
       10
       15
       20
       25
       100
       200
       300
       400
       500
      

Same Example of synchronized method by using annonymous class
In this program, we have created the two threads by annonymous class, so less coding is required.
1.    //Program of synchronized method by using annonymous class  
2.    Class Table{  
3.     synchronized void printTable(int n){//synchronized method  
4.       for(int i=1;i<=5;i++){  
5.         System.out.println(n*i);  
6.         try{  
7.          Thread.sleep(400);  
8.         }catch(Exception e){System.out.println(e);}  
9.       }  
10.    
11.   }  
12.  }  
13.    
14.  class Use{  
15.  public static void main(String args[]){  
16.  final Table obj = new Table();//only one object  
17.    
18.  Thread t1=new Thread(){  
19.  public void run(){  
20.  obj.printTable(5);  
21.  }  
22.  };  
23.  Thread t2=new Thread(){  
24.  public void run(){  
25.  obj.printTable(100);  
26.  }  
27.  };  
28.    
29.  t1.start();  
30.  t2.start();  
31.  }  
32.  }  
Output: 5
       10
       15
       20
       25
       100
       200
       300
       400
       500
      
      

Same Example of synchronized block by using annonymous class:
1.    <b><i>//Program of synchronized block by using annonymous class</i></b>  
2.      
3.    class Table{  
4.      
5.    void printTable(int n){  
6.       synchronized(this){//synchronized block  
7.         for(int i=1;i<=5;i++){  
8.          System.out.println(n*i);  
9.          try{  
10.         Thread.sleep(400);  
11.        }catch(Exception e){System.out.println(e);}  
12.       }  
13.     }  
14.  }//end of the method  
15.  }  
16.    
17.  class Use{  
18.  public static void main(String args[]){  
19.  final Table obj = new Table();//only one object  
20.    
21.  Thread t1=new Thread(){  
22.  public void run(){  
23.  obj.printTable(5);  
24.  }  
25.  };  
26.  Thread t2=new Thread(){  
27.  public void run(){  
28.  obj.printTable(100);  
29.  }  
30.  };  
31.    
32.  t1.start();  
33.  t2.start();  
34.  }  
35.  }  
Output:5
       10
       15
       20
       25
       100
       200
       300
       400
       500
      
Next To

Input and Output in Java

Input and Output (I/O) is used to process the input and produce the output based on the input. Java uses the concept of stream to make I/O operations fast. java.io package contains all the classes required for input and output operations.

Stream

A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it's like a stream of water that continues to flow.

Three streams are created for us automatically:

  • 1) System.out: standard output stream
  • 2) System.in: standard input stream
  • 3) System.err: standard error


Do You Know ?
·How to write a common data to multiple files using single stream only ?
·How can we access multiple files by single stream ?
·How can we improve the performance of Input and Output operation ?
·How many ways can we read data from the keyboard?
·What is console class ?
·How to compress and uncompress the data of a file?

OutputStream

Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source, it may be a file,an array,peripheral device or socket.


OutputStream class

OutputStream class is an abstract class.It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.

Commonly used methods of OutputStream class

Method
Description
1) public void write(int)throws IOException:
is used to write a byte to the current output stream.
2) public void write(byte[])throws IOException:
is used to write an array of byte to the current output stream.
3) public void flush()throws IOException:
flushes the current output stream.
4) public void close()throws IOException:
is used to close the current output stream.

InputStream class

InputStream class is an abstract class.It is the superclass of all classes representing an input stream of bytes.

Commonly used methods of InputStream class

Method
Description
1) public abstract int read()throws IOException:
reads the next byte of data from the input stream.It returns -1 at the end of file.
2) public int available()throws IOException:
returns an estimate of the number of bytes that can be read from the current input stream.
3) public void close()throws IOException:
is used to close the current input stream.

FileInputStream and FileOutputStream (File Handling):
FileInputStream and FileOutputStream classes are used to read and write data in file. In another words, they are used for file handling in java.

FileOutputStream class:
A FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data, prefer FileWriter.But you can write byte-oriented as well as character-oriented data.
Example of FileOutputStream class:
1.    //<b><i>Simple program of writing data into the file</i></b>  
2.      
3.      
4.    import java.io.*;  
5.    class Test{  
6.      public static void main(String args[]){  
7.       try{  
8.         FileOutputstream fout=new FileOutputStream("abc.txt");  
9.         String s="Sachin Tendulkar is my favourite player";  
10.         
11.       byte b[]=s.getBytes();  
12.       fout.write(b);  
13.         
14.       fout.close();  
15.    
16.       System.out.println("success...");  
17.      }catch(Exception e){system.out.println(e);}  
18.    }  
19.  }  
Output:success...

FileInputStream class:
A FileInputStream obtains input bytes from a file.It is used for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data.For example, to read image etc.
Example of FileInputStream class:
1.    //<b><i>Simple program of reading data from the file</i></b>  
2.      
3.    import java.io.*;  
4.    class SimpleRead{  
5.     public static void main(String args[]){  
6.      try{  
7.        FileInputStream fin=new FileInputStream("abc.txt");  
8.        int i;  
9.        while((i=fr.read())!=-1)  
10.       System.out.println((char)i);  
11.    
12.      fin.close();  
13.    }catch(Exception e){system.out.println(e);}  
14.   }  
15.  }  
Output:Sachin is my favourite player.

Example of Reading the data of current java file and writing it into another file
We can read the data of any file using the FileInputStream class whether it is java file, image file, video file etc. In this example, we are reading the data of C.java file and writing it into another file M.java.
1.    import java.io.*;  
2.      
3.    class C{  
4.    public static void main(String args[])throws Exception{  
5.      
6.    FileInputStream fin=new FileInputStream("C.java");  
7.    FileOutputStream fout=new FileOutputStream("M.java");  
8.      
9.    int i=0;  
10.  while((i=fin.read())!=-1){  
11.  fout.write((byte)i);  
12.  }  
13.    
14.  fin.close();  
15.  }  
16.  }  


Share:

0 comments:

GNIITSOLUTION GNIIT SOLUTION. Powered by Blogger.

Translate

Blog Archive

Unordered List