Nothing Special   »   [go: up one dir, main page]

Object Oriented Techniques Using Java (ACSE0302) : Unit: 4

Download as zip, pdf, or txt
Download as zip, pdf, or txt
You are on page 1of 75

Noida Institute of Engineering and Technology, Greater Noida

Object Oriented Techniques Using Java


(ACSE0302)

Unit : 4

Concurrency in Java and I/O


Stream SAVITA YADAV
Assistant Professor
B.tech 3rd Sem IOT Department

Ms. SAVITA YADAV OOT Using Java Unit-4


11/24/2021
Introduction of Faculty member

I am Savita Yadav (Assistant


Professor) in CSE(IOT) in NIET,
Greater Noida. I have done my
B.Tech (CSIT) from M.J.P
Rohilkhand University, Bareilly.
And I have completed my M.Tech
(CSE) from Galgotias University,
Greater Noida.
I have 1.5 years of experience in
teaching field. My specialization
field is IoT, VANETs.
11/24/2021 Ms. SAVITA YADAV OOT Using
Java Unit-4
Evaluation Scheme

Sl. Subject   Ev E    
No. Codes Subject Name
P alu nd Total Credit
e ati
on
Se
m
r Sc est
he er
i me
o s

d
s
L T P C TA TO PS T P
T TAL E E
W
E
E
K
S

C
O
M
P
U
L
S
O
R
Y
11/24/2021 Ms. SAVITA YADAV OOT Using
I Java Unit-4
N
Syllabus

Course
Contents /
Syllabus
UNIT-I Introduction 8 Hours
  Object Oriented Programming: Introduction and Features:  
Abstraction, Encapsulation, Polymorphism, and Inheritance.
Modeling Concepts: Introduction, Class Diagram and Object
Diagram.
Control Statements: Decision Making, Looping and Branching,
Argument Passing Mechanism: Command Line Argument.

UNIT-II Basics of Java Programming 8 Hours


  Class and Object: Object Reference, Constructor, Abstract  
Class, Interface and its uses, Defining Methods, Use of “this”
and “super” keyword, Garbage Collection and finalize ()
Method.
 Inheritance: Introduction and Types of Inheritance in Java,
Constructors in Inheritance.
11/24/2021
 Polymorphism: Ms. SAVITA YADAV
Introduction
Java
and OOT Using
Types, Overloading and
Unit-4
Syllabus

UNIT-III Packages, Exception Handling and String Handling


  Packages: Introduction and Types, Access Protection in Packages, Import
and Execution of Packages.
 Exception Handling, Assertions and Localizations: Introduction and Types,
Exceptions vs. Errors, Handling of Exception. Finally, Throws and Throw
keyword, Multiple Catch Block, Nested Try and Finally Block. Assertions
and Localizations Concepts and its working.
String Handling: Introduction and Types, Operations, Immutable String,
Method of String class, String Buffer and String Builder class.
UNIT-IV Concurrency in Java and I/O Stream
  Threads: Introduction and Types, Creating Threads, Thread Life-
Cycle, Thread Priorities, Daemon Thread, Runnable Class,
Synchronizing Threads. I/O Stream: Introduction and Types,
Common I/O Stream Operations, Interaction with I/O Streams
Classes. Annotations: Introduction, Custom Annotations and
Applying Annotations.
UNIT-V GUI Programming, Generics and Collections
  GUI Programming: Introduction and Types, Applet, Life Cycle of
11/24/2021 Applet, AWT, Ms.
Components
SAVITA YADAV and OOT
Containers,
Using Layout Managers and
User-Defined Layout
Java and Event Handling. Generics and Collections:
Unit-4
Branch wise Applications

Image Recognition
Speech Recognition
Stock market trading
AI Programming
Genetic programming

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Course Objective

At the end of the semester, the student will be able to:

Understand the object-oriented methodology and its techniques to design


and develop conceptual models and
Demonstrate the standard concepts of object-oriented techniques
modularity, I/O and other standard language constructs.
The basic objective of this course is to understand the fundamental
concepts of object-oriented programming in Java language and also
implement the Multithreading concepts, GUI based application and
collection framework.

11/24/2021
Ms. SAVITA YADAV OOT Using Java Unit-3
Course Outcomes
Course outcomes : After completion of this course students will be able to

CO 1 Identify the concepts of object oriented programming and K2


relationships among them needed in modeling.
CO 2 Demonstrate the Java programs using OOP principles K3
and also implement the concepts of lambda
expressions.
CO 3 Implement packages with different protection level K3, K5
resolving namespace collision and evaluate the error
handling concepts for uninterrupted execution of Java
program.
CO 4 Implement Concurrency control, I/O Streams and K3
Annotations concepts by using Java program.

CO 5 Design and develop the GUI based application, Generics K6


and Collections in Java programming language to solve
the real-world problem.
11/24/2021 Ms. SAVITA YADAV OOT Using
Java Unit-3
Program Outcome
1. Engineering knowledge
2. Problem analysis
3. Design/development of solutions
4. Conduct investigations of complex problems
5. Modern tool usage
6. The engineer and society
7. Environment and sustainability
8. Ethics
9. Individual and team work
10. Communication
11. Project management and finance
12. Life-long learning

11/24/2021
Ms. SAVITA YADAV OOT Using Java Unit-4
CO-PO Mapping

Mapping of Course Outcomes and Program Outcomes:

PO PO PO PO PO PO PO PO PO9 PO1 PO1 PO1


1 2 3 4 5 6 7 8 0 1 2
CO.1 3 3 3 2 1 2 3

CO.2 3 3 3 2 1 2 3

CO.3 3 3 3 2 1 2 3

CO.4 3 3 3 2 1 2 3

CO.5 3 3 3 2 1 2 3

3= High, 2=Medium, 1=Low

11/24/2021 Ms. SAVITA YADAV OOT Using Java


Unit-4
End Semester Question paper Templates

Printed page: …. Subject Code: …………………….


Roll No:

NOIDA INSTITUTE OF ENGINEERING AND TECHNOLOGY ,GREATER NOIDA

(An Autonomous Institute Affiliated to AKTU, Lucknow)


B.Tech/B.Voc./MBA/MCA/M.Tech (Integrated)
(SEM: ….. THEORY EXAMINATION (2020-2021)
Subject ………..
Time: 3 Hours Max. Marks:100

General Instructions:
All questions are compulsory. Answers should be brief and to the point.
This Question paper consists of …………pages & …8………questions.
It comprises of three Sections, A, B, and C. You are to attempt all the sections.
Section A -Question No- 1 is objective type questions carrying 1 mark each, Question No- 2 is very short
answer type carrying 2 mark each. You are expected to answer them as directed.
Section B - Question No-3 is Long answer type -I questions with external choice carrying 6 marks each.
You need to attempt any five out of seven questions given.
Section C - Question No. 4-8 are Long answer type –II (within unit choice) questions carrying 10 marks
each. You need to attempt any one part a or b.
Students are instructed to cross the blank sheets before handing over the answer sheet to the invigilator.
No sheet should be left blank. Any written material after a blank sheet will not be evaluated/checked.

11/24/2021 Ms. SAVITA YADAV OOT Using Java


Unit-3
    SECTION – A   CO
         
1.   Att [10×1=  
em 10]
pt
all
par
ts-
  1- Question-
(1)  
a.
  1- Question-
(1)  
b.
  1- Question-
(1)  
c.
  1- Question-
(1)  
d.
  1- Question-
(1)  
e.
11/24/2021 Ms. SAVITA YADAV OOT Using Java
  1- Question- Unit-3 (1)  
          
SE   CO
CT
IO
N

B
     
3. Answe
r any
[5×6=3  
five of 0]
the
follow
ing-

  3- Question-
(6)  
a.
  3- Question-
(6)  
b.
  3- Question-
(6)  
c.
  3-
11/24/2021 Question- Ms. SAVITA YADAV OOT Using Java (6)  
Unit-3
Prerequisite and Recap

Student must know at least the basics of how to use a


computer and should be able to start a command line shell.
Knowledge of basic programming concepts, as covered in
‘Programming Basic” course is necessary.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Brief Introduction about the Subject with videos

OOTS refers to languages that uses objects in programming.


OOTS aims to implement real-world entities like
inheritance, hiding, polymorphism etc in programming.
The main aim of OOTS is to bind together the data and the
functions that operate on them so that no other part of the
code can access this data except that function

https://www.youtube.com/watch?v=OjdT2l-EZJA

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Unit Content
Threads: Introduction and Types

Creating Threads
Thread Life-Cycle
Thread Priorities
Daemon Thread
Runnable Class
Synchronizing Threads
I/O Stream: Introduction and Types

Common I/O Stream Operations


Interaction with I/O Streams Classes
Annotations: Introduction

Custom Annotations
Applying Annotations

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Unit Objective

This course gives the fundamental knowledge of threads, I/O


control and annotations.
The unit will help the students to understand how the
approaches of threads help in solving real life problems.
Basic understanding of I/O operations used.
Overview of creating custom annotations and using them in
programs.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Threads: Introduction

Threads
Threads allows a program to operate more efficiently by
doing multiple things at the same time.
Threads can be used to perform complicated tasks in the
background without interrupting the main program.
Java is a multi-threaded programming language which
means we can develop multi-threaded program using Java.
A multi-threaded program contains two or more parts that
can run concurrently, and each part can handle a different
task at the same time making optimal use of the available
resources specially when your computer has multiple CPUs.
Multitasking is when multiple processes share common
processing resources such as a CPU.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Threads: Introduction

Multi-threading extends the idea of multitasking into


applications where you can subdivide specific operations
within a single application into individual threads.
Each of the threads can run in parallel.
The OS divides processing time not only among different
applications, but also among each thread within an
application.
Multi-threading enables you to write in a way where
multiple activities can proceed concurrently in the same
program.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Types of Threads

Types of threads
There are two types of Threads in java.
User threads are threads which are created by the
application or user.
They are high priority threads.
JVM (Java Virtual Machine) will not exit until all user
threads finish their execution.
JVM wait for these threads to finish their task. These
threads are foreground threads.

Ms. SAVITA YADAV OOT Using Java Unit-4


11/24/2021
Types of Threads

Daemon threads are threads which are mostly created by


the JVM.
These threads always run-in background.
These threads are used to perform some background
tasks like garbage collection and house-keeping tasks.
These threads are less priority threads.
JVM will not wait for these threads to finish their
execution.
JVM will exit as soon as all user threads finish their
execution.
JVM doesn’t wait for daemon threads to finish their task.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Creating Threads

Create a Thread by Implementing a Runnable Interface


If your class is intended to be executed as a thread, then
you can achieve this by implementing
a Runnable interface. You will need to follow three basic
steps −
Step 1
As a first step, you need to implement a run() method
provided by a Runnable interface. This method provides
an entry point for the thread, and you will put your
complete business logic inside this method. Following is
a simple syntax of the run() method −
public void run( )
11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4
Creating Threads

Step 2
As a second step, you will instantiate a Thread object using the
following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the
Runnable interface and threadName is the name given to the new
thread.

Step 3
Once a Thread object is created, you can start it by calling start()
method, which executes a call to run( ) method. Following is a
simple syntax of start() method −
void start();
11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4
Creating Threads

Example:
 

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Creating Threads

Create a Thread by Extending a Thread Class


The second way to create a thread is to create a new class that
extends Thread class using the following two simple steps. This
approach provides more flexibility in handling multiple threads
created using available methods in Thread class.
Step 1
You will need to override run( ) method available in Thread class.
This method provides an entry point for the thread, and you will
put your complete business logic inside this method. Following is
a simple syntax of run() method −

public void run( )

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Creating Threads

Step 2
Once Thread object is created, you can start it by
calling start() method, which executes a call to run( )
method. Following is a simple syntax of start()
method-
void start( );

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Creating Threads

Example:

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Thread Lifecycle

A thread in Java at any point of time exists in any one of the


following states. A thread lies only in one of the shown
states at any instant:
New
Runnable
Blocked
Waiting
Timed Waiting
Terminated

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Thread Lifecycle

The diagram shown below represent various states of a


thread at any instant of time.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Thread Lifecycle

New Thread: When a new thread is created, it is in the new state.


The thread has not yet started to run when thread is in this
state.
When a thread lies in the new state, it’s code is yet to be run
and hasn’t started to execute.
Runnable State: A thread that is ready to run is moved to
runnable state.
In this state, a thread might be running or it might be ready
run at any instant of time. It is the responsibility of the
thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to
each individual thread.
Each thread runs for a short while and then pauses and
relinquishes the CPU to another thread, so that other threads
can get a chance to run.
When this happens, all such threads that are ready to run,
waiting for the CPU and the currently running thread lies in
runnable state.
11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4
Thread Lifecycle

Blocked/Waiting state: When a thread is temporarily inactive,


then it’s in one of the following states:

Blocked
Waiting
For example, when a thread is waiting for I/O to
complete, it lies in the blocked state.
It’s the responsibility of the thread scheduler to
reactivate and schedule a blocked/waiting thread.
A thread in this state cannot continue its execution any
further until it is moved to runnable state. Any thread in
these states does not consume any CPU cycle.
A thread is in the blocked state when it tries to access a
protected section of code that is currently locked by
some other thread.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Thread Lifecycle

When the protected section is unlocked, the schedule


picks one of the thread which is blocked for that section
and moves it to the runnable state.
Whereas, a thread is in the waiting state when it waits
for another thread on a condition.
When this condition is fulfilled, the scheduler is notified
and the waiting thread is moved to runnable state.
If a currently running thread is moved to blocked/waiting
state, another thread in the runnable state is scheduled
by the thread scheduler to run.
It is the responsibility of thread scheduler to determine
which thread to run.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Thread Lifecycle

Timed Waiting: A thread lies in timed waiting state when it


calls a method with a time out parameter.
A thread lies in this state until the timeout is completed
or until a notification is received.
For example, when a thread calls sleep or a conditional
wait, it is moved to a timed waiting state.
Terminated State: A thread terminates because of either of
the following reasons:
Because it exists normally. This happens when the code
of thread has entirely executed by the program.
Because there occurred some unusual erroneous event,
like segmentation fault or an unhandled exception.
A thread that lies in a terminated state does no longer
consumes any cycles of CPU.

Ms. SAVITA YADAV OOT Using Java Unit-4


11/24/2021
Thread Priorities

Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant
of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is
given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads.
However, thread priorities cannot guarantee the order in which threads
execute and are very much platform dependent.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Daemon Thread

Daemon thread in java is a service provider thread that


provides services to the user thread.
Its life depend on the mercy of user threads i.e. when all the
user threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically
e.g. gc, finalizer etc.
Points to remember for Daemon Thread in Java
It provides services to user threads for background
supporting tasks. It has no role in life than to serve user
threads.
Its life depends on user threads.
It is a low priority thread.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Daemon Thread

Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java
daemon thread.

No. Method Description


1) public void setDaemon(boolean is used to mark the current
status) thread as daemon thread or
user thread.
2) public boolean isDaemon() is used to check that current
is daemon.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Daemon Thread Example

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Runnable Class

java.lang.Runnable is an interface that is to be implemented by a


class whose instances are intended to be executed by a thread.
There are two ways to start a new Thread – Subclass Thread and
implement Runnable.
There is no need of subclassing Thread when a task can be done by
overriding only run() method of Runnable.
Create a Runnable implementer and implement run() method.
Instantiate Thread class and pass the implementer to the Thread,
Thread has a constructor which accepts Runnable instance.
Invoke start() of Thread instance, start internally calls run() of the
implementer. Invoking start(), creates a new Thread which executes
the code written in run().
Calling run() directly doesn’t create and start a new Thread, it will
run in the same thread. To start a new line of execution, call start()
on the thread.
11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4
Runnable Class Example

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Synchronized Threads

The process of allowing multiple threads to modify an object


in a sequence is called synchronization.
We can allow multiple threads to modify the objects
sequentially only by executing that objects’ mutator
methods logic in sequence from multiple threads.
This is possible by using an object locking concept.
Thread Synchronization is a process of allowing only one
thread to use the object when multiple threads are trying to
use the object at the same time.
To achieve this Thread Synchronization, we must use a java
keyword or modifier called “synchronized”.
Synchronization in java is the capability to control the access
of multiple threads to any shared resource. Java
Synchronization is a better option where we want to allow
only one thread to access the shared resource.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Synchronized Threads

General Syntax:synchronized(objectidentifier){         //


Access shared variables and other shared resources;}
Why use Synchronization?
The synchronization is mainly used to :
If you start with at least two threads inside a
program, there might be a chance when multiple
threads attempt to get to the same resource.
It can even create an unexpected outcome because of
concurrency issues.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Synchronized Threads

Types of Synchronization
There are basically two types of synchronization
available. They are:
Process Synchronization: It means sharing system
resources by processes in such a way that, Concurrent
access to shared data is handled thereby minimizing
the chance of inconsistent data.
Thread Synchronization: It means that every access to
data shared between threads is protected so that
when any thread starts operation on the shared data,
no other thread is allowed access until the first
thread is done.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Synchronized Threads
Locks in Java
Synchronization is built around an internal entity known as
the lock or monitor lock. (The API specification often refers to
this entity simply as a “monitor.”)
Locks play a role in both aspects of synchronization: enforcing
exclusive access to an object’s state and establishing happens-
before relationships that are essential to visibility.
Every object has a lock associated with it.
By convention, a thread that needs exclusive and 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.
A thread is said to own the lock between the time it has
acquired the lock and released the lock.
As long as a thread owns a lock, no other thread can acquire
the same lock. The other thread will block when it attempts
to acquire the lock.
11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4
I/O Stream: Introduction

Java brings various Streams with its I/O package that helps


the user to perform all the input-output operations.
These streams support all the types of objects, data-types,
characters, files etc to fully execute the I/O operations.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


I/O Stream: Introduction

Before exploring various input and output streams lets look


at 3 standard or default streams that Java must provide
which are also most common in use:

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


I/O Stream: Introduction

System.in: This is the standard input stream that is used to read


characters from the keyboard or any other standard input device.
System.out: This is the standard output stream that is used to produce
the result of a program on an output device like the computer screen.
Here is a list of the various print functions that we use to output
statements:
print(): This method in Java is used to display a text on the
console.
This text is passed as the parameter to this method in the form of
String.
This method prints the text on the console and the cursor remains
at the end of the text at the console.
The next printing takes place from just here.
Syntax:
System.out.print(parameter);
11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4
I/O Stream: Introduction

println(): This method in Java is also used to display a text on


the console.
It prints the text on the console and the cursor moves to the
start of the next line at the console.
The next printing takes place from the next line.
Syntax:
System.out.println(parameter);
printf(): This is the easiest of all methods as this is similar
to printf in C.
Note that System.out.print() and System.out.println() take
a single argument, but printf() may take multiple
arguments.
This is used to format the output in Java.
11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4
I/O Stream: Introduction

System.err: This is the standard error stream that is used to


output all the error data that a program might throw, on a
computer screen or any standard output device.
This stream also uses all the 3 above-mentioned functions to
output the error data:
print()
println()
printf()

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Types of Streams

Depending on the type of operations, streams can be divided


into two primary classes:
Input Stream: These streams are used to read data that
must be taken as an input from a source array or file or
any peripheral device. For eg., FileInputStream,
BufferedInputStream, ByteArrayInputStream etc.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Types of Streams

Output Stream: These streams are used to write data as


outputs into an array or file or any output peripheral
device. For eg., FileOutputStream,
BufferedOutputStream, ByteArrayOutputStream etc.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Types of Streams

Depending on the types of file, Streams can be divided into


two primary classes which can be further divided into other
classes as can be seen through the diagram below followed
by the explanations.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Types of Streams

ByteStream: This is used to process data byte by byte (8 bits).


Though it has many classes, the FileInputStream and the
FileOutputStream are the most popular ones.
The FileInputStream is used to read from the source and
FileOutputStream is used to write to the destination.
CharacterStream: In Java, characters are stored using Unicode
conventions.
Character stream automatically allows us to read/write data
character by character.
Though it has many classes, the FileReader and the FileWriter are the
most popular ones.
FileReader and FileWriter are character streams used to read from
the source and write to the destination respectively.
11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4
Common I/O Stream Operations

Useful methods of Output


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

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Common I/O Stream Operations

Useful methods of Input


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

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Interaction with I/O Streams Classes

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Interaction with I/O Streams Classes

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Annotations: Introduction

Annotations are used to provide supplement information


about a program.
Annotations start with ‘@’.
Annotations do not change action of a compiled program.
Annotations help to associate metadata (information) to the
program elements i.e. instance variables, constructors,
methods, classes, etc.
Annotations are not pure comments as they can change the
way a program is treated by compiler.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Annotations: Introduction

Built-In Java Annotations used in Java code


@Override
@SuppressWarnings
@Deprecated

@Override
@Override annotation assures that the subclass method is
overriding the parent class method. If it is not so,
compile time error occurs.
@SuppressWarnings
@SuppressWarnings annotation is used to suppress
warnings issued by the compiler.
@Deprecated
@Deprecated annotation marks that this method is
deprecated so compiler prints warning. It informs user
that it may be removed in the future versions. So, it is
better not to use such methods.
11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4
Custom Annotations

Java Custom annotations or Java User-defined


annotations are easy to create and use.
The @interface element is used to declare an
annotation. For example:
@interface MyAnnotation{ }  
Here, MyAnnotation is the custom annotation name.
Points to remember for java custom annotation signature
Method should not have any throws clauses
Method should return one of the following: primitive data
types, String, Class, enum or array of these data types.
Method should not have any parameter.
We should attach @ just before interface keyword to
define annotation.
It may assign a default value to the method.

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Applying Annotations

Example of custom annotation: creating, applying and


accessing annotation

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Applying Annotations

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4


Daily Quiz

Q1. Which of these method of Thread class is used to find out the priority
given to a thread?a) get()b) ThreadPriority()c) getPriority()d)
getThreadPriority()
Q2. Which of these method of Thread class is used to Suspend a thread for
a period of time?a) sleep()b) terminate()c) suspend()d) stop()

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Daily Quiz

Q3.Which function of pre defined class Thread is used to check weather


current thread being checked is still running?
a) isAlive()
b) Join()
c) isRunning()
d) Alive()
Q4. In java a thread can be created by ..........
A. Extending the thread class.
B.Implementing Runnable interface.
C.Both of the above
D.None of these

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Daily Quiz

Q5.Thread synchronization in a process will be required when


A.All threads sharing the same address space
B.All threads sharing the same global variables
C.All threads sharing the same files
D.All
Q6.Which thread will be executed first if two threads have same
priority
A. They will fall in starvation and none will be executed.
B. Both will be executed simultaneously
C. It depends upon operating system
D.They will be executed on first come first serve basis

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Daily Quiz

Q7.The life cycle of a thread in java is controlled by


A.JRE
B.JDK
C.JVM
D.None
Q8.Which method is used to get current running thread object?
A.runningThread()
B.currentThread()
C.runnableThread()
D.None

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Daily Quiz

Q9. Which of these stream contains the classes which can work on
character stream?
a) InputStream
b) OutputStream
c) Character Stream
d) All of the mentioned
Q10.Which of these method of FileReader class is used to read characters
from a file?
a) read()
b) scanf()
c) get()
d) getInteger()

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Weekly Assignment

Q1. Explain Threads and types of threads in java.


Q2. Explain Thread Life Cycle in detail.
Q3. Explain Thread Creation in java with suitable example.

Q4. What is Daemon Thread? Give its example.


Q5. Explain input output stream operations in java.
Q6. What are Custom Annotations? Explain how to create custom
annotations in java with suitable example.
Q7. Explain various types of Output Streams in java.
Q8. What do you understand by Annotations? Explain various built in java
annotations in java.
Q9.Explain various methods of input stream in detail.
Q10. Explain various output streams methods in detail.

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Topic Links

https://www.youtube.com/watch?v=qQVqfvs3p48
https://www.youtube.com/watch?v=TCd8QIS-2KI
https://www.youtube.com/watch?v=vd9nJK22BwU

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
MCQ

Q1.Which version of Java introduced annotation?a) Java 5b) Java 6c) Java
7d) Java 8
Q2.Annotations which are applied to other annotations are called meta
annotations.a) Trueb) False
Q3.Which of these is used to perform all input & output operations in
Java?a) streamsb) Variablesc) classesd) Methods

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
MCQ

Q4.Which of these is a type of stream in Java?a) Integer streamb) Short


streamc) Byte streamd) Long stream
Q5.Which of these classes are used by Byte streams for input and output
operation?a) InputStreamb) InputOutputStreamc) Readerd) All of the
mentioned
Q6.  Which of these classes are used by character streams for input and
output operations?a) InputStreamb) Writerc) ReadStreamd)
InputOutputStream

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
MCQ

Q7.Daemon thread runs in


A. Background
B. Foreground
C. Both
D.None
Q8. Which method is used to create a daemon thread?
A. setDaemon(boolean value)
B. setThread(boolean value)
C. createDaemon(boolean value)
D. makeDeamon(boolean value);

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
MCQ

Q9. Which will contain the body of the thread in Java?


A. Start()
B. Run()
C. Main()
D. Execute()
Q10.  To create a daemon thread
A. First thread setDaemon() is called then start()
B. First thread start() is called then setDaemon()
C. Call thread start() and setDaemon() in any order
D.All correct

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Previous Questions paper

1. What is Multithreading? What are the ways to create multiple


threads in java.
2. Explain about Thread Life Cycle.
3. Define Daemon Threads? Explain with an example.
4. Write a java program to implement join() method in
multithreading.
5. What are the states of a thread?
6. What are the threads will start, when you start the java program?
7. What are the different identifier states of a Thread?
8. Why do threads block on I/O?
9. What is synchronization and why is it important?

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Expected Questions

1. Discuss how to set the priority to threads? What are the different
ranges.
2. Write a java program to create two threads and execute
simultaneously
3. Write a Java program that creates three threads. First thread
displays “Hello!” every one second, the second thread displays
“Wear Mask !” every two seconds and “Use Sanitizer !” every 5
seconds.
4. Write the difference between Extending thread and implementing
runnable?
5. Explain in detail about thread methods?

11/24/2021 Ms. SAVITA YADAV OOT Using


Java Unit-4
Noida Institute of Engineering and Technology,
Greater Noida

THANK YOU !!

11/24/2021 Ms. SAVITA YADAV OOT Using Java Unit-4

You might also like