[go: up one dir, main page]

0% found this document useful (0 votes)
3 views47 pages

Java Task 1

Java task question for engg

Uploaded by

soorajkumar2828
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)
3 views47 pages

Java Task 1

Java task question for engg

Uploaded by

soorajkumar2828
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/ 47

Java Threads

• A Thread is a very light-weighted process, or we can say the smallest part of the process
that allows a program to operate more efficiently by running multiple tasks
simultaneously.

• All the tasks are executed without affecting the main program.

• In a program or process, all the threads have their own separate path for execution, so
each thread of a process is independent.
• if a thread gets an exception or an error at the time of its execution, it doesn't affect the
execution of the other threads.

• All the threads share a common memory and have their own stack, local variables and
program counter.

• When multiple threads are executed in parallel at the same time, this process is known
as Multithreading
Thread Life Cycle
Thread Creation
• By "creating or implementing" the Runnable Interface
The runnable interface gives us the run() method to perform
an action for the thread.

• By extending the Thread class.


start() method
• The method is used for starting a newly created
thread
• After executing the start() method, the thread
changes the state from New to Runnable
• It executes the run() method when the thread gets
the correct time to execute it.
• The runnable interface provides us both the run()
method and the start() method.
// Implementing runnable interface by extending Thread class
public class ThreadExample1 extends Thread {
// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the Thread class
t1.start();
}
}
Steps for Creating a Thread Using Runnable Interface

• Create a thread class that will implement the runnable


interface.
• In the thread class, write a function to override the run()
method.
• Create an instance of the Thread class.
• The thread instance has a constructor which accepts the
runnable object. Pass this object as a parameter to the
thread instance.
• Finally, call the start method of the thread instance.
Implementation of the Runnable Interface in Java
• Implementation of the run() method is the easiest way of creating a new
thread. It acts as a starting point for creating a new Thread. The runnable
interface implementation uses the code inside the run() method and
executes it on a concurrent thread.

• The runnable interface provides a standard set of rules for the instances of
classes which wish to execute code when they are active.

• The most common use case of the Runnable interface is when we want
only to override the run method.
A simple thread example using runnable
public class ExampleClass implements Runnable {

@Override
public void run() {
System.out.println("Thread has ended");
}

public static void main(String[] args) {


ExampleClass ex = new ExampleClass();
Thread t1= new Thread(ex);
System.out.println("Hi");
t1.start();

}
}
Example2:
Creating a Java Thread by extending Thread Class

• If the program uses Runnable interface, it needs to implement only


run() method.
• In case, where the class extends a Tread class, it must override run()
method of the Thread class.
• The first way to create a thread is to create a subclass of the Thread
class.
• The class that needs the thread can create an object of the class that
extends thread class.
Code:
Example:
Main differences between Thread class and Runnable interface:

• By extending thread, there is overhead of additional methods, i.e. they consume


excess or indirect memory, computation time, or other resources.

• Maintenance of the code is easy if we implement the Runnable interface.


Thread Synchronization
• When we start two or more threads within a program, there may be a
situation when multiple threads try to access the same resource and
finally they can produce deadlock situation due to concurrency issues.

• For example, if multiple threads try to write within a same file then they
may corrupt the data because one of the threads can override data or
while one thread is opening the same file at the same time another
thread might be closing the same file.

• So there is a need to synchronize the action of multiple threads and make


sure that only one thread can access the resource at a given point in time.
General form of the synchronized statement
Syntax:

synchronized(objectidentifier)
{

// Access shared variables and other shared resources

}
Without synchronization, Threads run in random way by blocking system
resources. So, Synchronization prevents thread interference.

Synchronization in Java is the capability to control the access of multiple


threads to any shared resource.
thread synchronization ways:

1. By Using Synchronized method

2. By Using Synchronized block.

3. By Using Static synchronization.


Exceptions in Java
• Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application
can be maintained.
• Exception is an abnormal condition.
• In Java, the core advantage of exception handling is to maintain the
normal flow of the application.
Java Exception hierarchy

Throwable class is the root class in the hierarchy.


• The hierarchy splits into two branches: Error and Exception.

• Errors represent irrecoverable conditions such as Java virtual machine


(JVM) running out of memory, memory leaks, stack overflow errors,
library incompatibility, infinite recursion, etc.
• Errors are usually beyond the control of the programmer

• Exceptions can be caught and handled by the program.


• It contains information about the exception such as the name and
description of the exception and state of the program when the
exception occurred.
Java Exception Types
• Runtime Exception : A runtime exception happens due to a
programming error. They are also known as unchecked
exceptions.
• These exceptions are not checked at compile-time but run-time.
• Examples:
Out-of-bounds array access - ArrayIndexOutOfBoundsException
Dividing a number by 0 - ArithmeticException
Null pointer access (missing the initialization of a variable) -
NullPointerException

Note: You can think about it in this way. “If it is a runtime


exception, it is your fault”.
• IOException : An IOexception is also known as a checked exception.
They are checked by the compiler at the compile-time and the
programmer is prompted to handle these exceptions.

• These exceptions are not checked at compile-time but run-time.

• Example:
Trying to open a file that doesn’t exist results in FileNotFoundException
Exception Handling in Java
List of different approaches to handle exceptions in Java.
• try...catch block

• finally block

• throw and throws keyword


Java try...catch block
• The try-catch block is used to handle exceptions in Java.
• Syntax:
try{
//code
}
Catch(Exception e)
{
//code
}

• We have to place the code that might generate an exception inside the try block.
Every try block is followed by a catch block.

• When an exception occurs, it is caught by the catch block. The catch block cannot be
used without the try block.
Example: Exception handling using try...catch
class Main {
public static void main(String[] args) {

try {

// code that generate exception


int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Java finally block
• In Java, the finally block is always executed no matter whether there is an
exception or not.
• The finally block is optional.

• For each try block, there can be only one finally block.

• Syntax:
try {
//code
}
catch (ExceptionType1 e1)
{ // catch block
}
finally {
// finally block always executes
}
Example: Java Exception Handling using finally block
class Demo {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}
Java throw and throws keyword
• The Java throw keyword is used to explicitly throw a single exception.

• When we throw an exception, the flow of the program moves from


the try block to the catch block.

• Example: Exception handling using Java throw

class Main {
public static void divideByZero() {

// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}

public static void main(String[] args) {


divideByZero();
}
}
Throws Keyword
• The throws keyword is used to declare the type of exceptions that might occur within the
method. It is used in the method declaration.

import java.io.*; When we run this program, if the file test.txt does
class Main {
not exist, FileInputStream throws
// declaring the type of exception
public static void findFile() throws IOException { a FileNotFoundException which extends
the IOException class.
// code that may generate IOException
File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
}
public static void main(String[] args) {
try {
findFile();
}
catch (IOException e) {
System.out.println(e);
}}
}
Hierarchy of
Java Exception
classes
Java Custom Exceptions

In Java, exceptions can be categorized into two types:


Unchecked Exceptions: They are not checked at compile-time but at run-
time.
For example:
ArithmeticException, NullPointerException,ArrayIndexOutOfBoundsException,
exceptions under Error class, etc.
Checked Exceptions: They are checked at compile-time.
For example, IOException, InterruptedException, etc.
Java Throws Keyword
1) The throws keyword in Java is used to declare exceptions that can occur during the
execution of a program.

2) For any method that can throw exceptions, it is mandatory to use the throws keyword
to list the exceptions that can be thrown.

3) When a method declares that it throws an exception, it is not required to handle the
exception. The caller of a method that throws exceptions is required to handle the
exceptions.

Java Throws Syntax:

accessModifier returnType methodName() throws ExceptionType1,


ExceptionType2 … { code }
● All exceptions that can be thrown by a method should be declared in the method signature using the
throws keyword

● Method can throw multiple exceptions, which should be separated by a comma in the

declaration.
Example:
Throw Keyword

The throw keyword is used to explicitly throw a single exception.

When an exception is thrown, the flow of program execution
transfers from the try block to the catch block. We use the throw
keyword within a method.

Syntax:
throw throwableObject;
Throw Example
import java.io.*;
class Main {
public static void findFile() throws IOException {
throw new IOException("File not found");
}

public static void main(String[] args) {


try {
findFile();
System.out.println("Rest of code in try block");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Example:2
Throw and Throws Example
Difference between Java Throw and Throws Keyword
File Handling in java
• To support file operations in java, java has a pre-defined
class known as File
• File class consists of number of methods that supports
different file operations
• Different methods supporting file operations are
performed by creating an instance (object) of the File
class

Syntax :
File object=new File(filename);
Reading from a file
• In order to perform read operation, a file must exist in
the storage system
• There are different methods and supporting classes for
performing file read operation
• We will be adopting Scanner class method to read the
contents from the file

Syntax:
Scanner object= new Scanner(fileinstance);
file instance is a file object that is created using File class
Reading from a file
Scanner class methods supporting file read operation
Method Description Syntax
Name
nextLine Returns a complete a line in scannerobject.nextLine(
string format and after reading )
refers to the next line in
sequence
hasNextLine Returns true if the file has a next Scannerobject.hasNextL
line else false ine()
Selected Methods of File class
Method Name Description Syntax
canRead Returns true if file is readable fileobject.canRead()
else false
canWrite Returns true if file is writable fileobject.canWrite()
else false
exists Returns true if file exists fileobject.exists()
getAbsolutePath Returns the pathname of the fileobject. getAbsolutePath()
file in the string format
length Returns size of file in bytes fileobject.length()
list Returns the array of files in fileobject.list()
string format present in a
specific directory
mkdir Creates a directory with a fileobject.mkdir()
specified name and if
successful returns true
delete Deletes a file and if fileobject.delete()
successful returns true
Writing into a file
• In order to perform write operation, a file may / may not
exist in the storage system
• There are different methods and supporting classes for
performing file write operation
• We will be adopting FileWriter class method to read the
contents from the file

Syntax:
FileWriter object= new FileWriter(fileinstance,boolean);
file instance is a file object that is created using File class
boolean is true or false. By default false. If true used for
appending
Writing into a file
• FileWriter class’s write method is used to write the
contents into the file

Syntax:
filewriterobject.write(string)

You might also like