[go: up one dir, main page]

0% found this document useful (0 votes)
20 views16 pages

Unit 3 - JAVA

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

Unit 3 - JAVA

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

 Create Package in Java:

In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java contains many
pre-defined packages such as java.lang, java.io, java.net, etc. When we create any Java program the
java.lang package is imported by default. We need not to write the package name at the top of the
program. We can also create our own package by providing the name that we want. In this section, we
will learn how to create a package in Java.

We use package for the following reasons:


o The package makes the search easier for the classes and interfaces.
o It provides a fully qualified name that avoids naming conflicts.
o It also controls access.
o It organizes classes in a folder structure.
o It improves code reusability.
o Programmer can group classes and interfaces into a related package.

Now, we are going to create the main class named Calculator. In this class, we have imported all the packages
that we have created above. It includes all the classes in the Calculator class.
Calculator.java
package p5;
//importing pre-defined package
import java.util.*;
//importing user-defined package
import p1.Add;
import p2.Sub;
import p3.Mult;
import p4.Div;
public class Calculator
{
public static void main(String args[])
{
System.out.print("Enter your choice: ");
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
switch(t)
{
case 1:
Add a=new Add();
a.sum();
break;
case 2:
Sub s=new Sub();
s.diff();
break;
case 3:
Mult m=new Mult();
m.pro();
break;
case 4:
Div d=new Div();
d.divd();
break;
}
}
}

Output:
Enter your choice: 3
Enter the first number: 2
Enter the second number: 23
Product=46

Here are some examples of built-in packages:


 java. lang.
 java.io.
 java. util.
 java. applet.
 java. awt.
 java.net.

 Exception Handling in Java:

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.
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions.
Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the
code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is why we use exception handling
in Java.

 Types of Java Exceptions:


There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked
exception. However, according to Oracle, there are three types of exceptions namely:
Checked Exception
Unchecked Exception
Error

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the
exception.
JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

 Java try-catch block:


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

Syntax of Java try-catch


try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw an exception
}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.
The catch block must be used after the try block only. You can use multiple catch block with a single try block.

public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception


System.out.println("rest of the code");

}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero

 Java Multi-catch block:


A try block can be followed by one or more catch blocks. Each catch block must contain a different exception
handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch
block.

o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException
must come before catch for Exception.
Example:
public class MultipleCatchBlock2 {

public static void main(String[] args) {

try{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
 Java Nested try block:
In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement
that we enter a statement in try block, context of that exception is pushed onto the stack.
For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer
try block can handle the ArithemeticException (division by zero).
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may
cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Java Nested try Example
Example 1
Let's see an example where we place a try block within another try block for two different exceptions.
NestedTryBlock.java
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}
}
Output:

 Java finally block


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.
public class TestFinallyBlock2{
public static void main(String args[]){

try {

System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}

//executes regardless of exception occured or not


finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}

 Java throw Exception:


In Java, exceptions allows us to write good quality codes where the errors are checked at the compile time
instead of runtime and we can create custom exceptions making the code recovery and debugging easier.
The Java throw keyword is used to throw an exception explicitly.
We specify the exception object which is to be thrown. The Exception has some message with it that provides
the error description.
These exceptions may be related to user inputs, server, etc.
he syntax of the Java throw keyword is given below.
throw Instance i.e.,
1. throw new exception_class("error message");
Let's see the example of throw IOException.
1. throw new IOException("sorry device error");

TestThrow1.java
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.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}

 Java throws keyword:


The Java 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 the
normal flow of the program 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 checking the code before it being used.
Syntax of Java throws
return_type method_name() throws exception_class_name{
//method code
}
Java throws Example
Let's see the example of Java throws clause which describes that checked exceptions can be propagated by
throws keyword.
Testthrows1.java
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...

 Multithreading in Java:
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both
are used to achieve multitasking. However, we use multithreading than multiprocessing because threads use a
shared memory area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
Java 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 in two ways:
1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each process allocates a separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading registers, memory
maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading):


 Threads share the same address space.
 A thread is lightweight.
 Cost of communication between the thread is low.

What is Thread in java:


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared
memory area.
 How to create a thread in Java:
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
 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:
The start() method of Thread class is used to start a newly created thread. It performs the following tasks:
o A new thread starts(with new call stack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Java Thread Example by extending Thread class:


FileName: Multi.java
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...

2) Java Thread Example by implementing Runnable interface:


FileName: Multi3.java
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); // Using the constructor Thread(Runnable r)
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 explicitly create the Thread class object. We are passing the object of your class that implements Runnable so
that your class run() method may execute.

3) Using the Thread Class: Thread(String Name):


We can directly use the Thread class to spawn new threads using the constructors defined above.
FileName: MyThread1.java
1. public class MyThread1
2. {
3. // Main method
4. public static void main(String argvs[])
5. {
6. // creating an object of the Thread class using the constructor Thread(String name)
7. Thread t= new Thread("My first thread");
8.
9. // the start() method moves the thread to the active state
10. t.start();
11. // getting the thread name by invoking the getName() method
12. String str = t.getName();
13. System.out.println(str);
14. }
15. }
Output:
My first thread

Life cycle of a Thread (Thread States):


In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
Explanation of Different Thread States:
New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has
not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active state. The active
state contains two states within it: one is runnable, and the other is running.

o Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the
thread may be running or may be ready to run at any given instant of time. It is the duty of the thread
scheduler to provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each
and every thread runs for a short span of time and when that allocated time slice is over, the thread
voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of
time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn to
run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the
most common change in the state of a thread is from runnable to running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread
is in the blocked state or is in the waiting state.
PlayNext
Unmute
Current Time 2:15
/
Duration 18:10
Loaded: 17.98%
Â
Fullscreen
For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the
same time, the other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A
has to wait for thread B to use the printer. Thus, thread A is in the blocked state. A thread in the blocked state is
unable to perform any execution and thus never consume any cycle of the Central Processing Unit (CPU).
Hence, we can say that thread A remains idle until the thread scheduler reactivates thread A, which is in the
waiting or blocked state.
When the main thread invokes the join() method then, it is said that the main thread is in the waiting state. The
main thread then waits for the child threads to complete their tasks. When the child threads complete their job, a
notification is sent to the main thread, which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to
determine which thread to choose and which one to reject, and the chosen thread is then given the opportunity
to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered
the critical section of a code and is not willing to leave that critical section. In such a scenario, another thread
(its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is
given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not forever. A real
example of timed waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts
the thread in the timed wait state. After the time runs out, the thread wakes up and start its execution from when
it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is
no way one can respawn (active after kill) the dead thread.
The following diagram shows the different states involved in the life cycle of a thread.

 Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
Why use Synchronization?
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization

 Java 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 thread completes its task.

TestSynchronization2.java

//example of java synchronized method


class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:

5
10
15
20
25
100
200
300
400
500

 wait(), notify() and notifyAll() methods in Java:


The threads can communicate with each other through wait(), notify() and notifyAll() methods in Java. These
are final methods defined in the Object class and can be called only from within a synchronized context.
The wait() method causes the current thread to wait until another thread invokes
the notify() or notifyAll() methods for that object. The notify() method wakes up a single thread that is waiting
on that object’s monitor. The notifyAll() method wakes up all threads that are waiting on that object’s monitor.
A thread waits on an object’s monitor by calling one of the wait() method.
wait() method Syntax
public final void wait() throws InterruptedException

notify() Method Syntax


public final void notify()

NotifyAll() method Syntax


public final void notifyAll()

Example:
public class WaitNotifyTest {
private static final long SLEEP_INTERVAL = 3000;
private boolean running = true;
private Thread thread;
public void start() {
print("Inside start() method");
thread = new Thread(new Runnable() {
@Override
public void run() {
print("Inside run() method");
try {
Thread.sleep(SLEEP_INTERVAL);
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
synchronized(WaitNotifyTest.this) {
running = false;
WaitNotifyTest.this.notify();
}
}
});
thread.start();
}
public void join() throws InterruptedException {
print("Inside join() method");
synchronized(this) {
while(running) {
print("Waiting for the peer thread to finish.");
wait(); //waiting, not running
}
print("Peer thread finished.");
}
}
private void print(String s) {
System.out.println(s);
}
public static void main(String[] args) throws InterruptedException {
WaitNotifyTest test = new WaitNotifyTest();
test.start();
test.join();
}
}
Output
Inside start() method
Inside join() method
Waiting for the peer thread to finish.
Inside run() method
Peer thread finished.

You might also like