0% found this document useful (0 votes)
4 views

22CS202 JAVA PROGRAMMING UNIT-3

Uploaded by

SHREE LEKHA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

22CS202 JAVA PROGRAMMING UNIT-3

Uploaded by

SHREE LEKHA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

Please read this disclaimer before

proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
22CS202
JAVA PROGRAMMING

Batch / Year / Semester: 2022-2026 / I / 02

4
Table Of Contents
S. Page
Topic
No. No.
1 Contents 5
2 Course Objectives 6
3 Pre-Requisites 7
4 Syllabus 8
5 Course outcomes 11
6 CO- PO/PSO Mapping 12
7 Lecture Plan 13
8 Activity based Learning 14
9 Lecture Notes 18
10 Assignments 80

11 Part A Questions With Answers 81

12 Part B Questions 89

13 Online Certifications 90

14 Real Time Applications 91

15 Contents Beyond the Syllabus 92

16 Assessment Schedule 94

17 Text Books & Reference Books 95

18 Mini Project suggestions 96

5
2. Course Objectives
L T P C
22CS202 JAVA PROGRAMMING
3 0 2 4

OBJECTIVES:

To explain object-oriented programming concepts and fundamentals of Java.


To apply the principles of packages, interfaces, and exceptions.
To develop a Java application with I/O streams, threads, and generic programming.
To build applications using strings and collections.
To apply the JDBC concepts.

6
3. PRE REQUISITES

• Pre-requisite Chart

22CS202 –JAVA PROGRAMMING

21GE101 – PROBLEM SOLVING AND C PROGRAMMING

7
4. Syllabus
L T P C
22CS202 JAVA PROGRAMMING
3 0 2 4

UNIT I JAVA FUNDAMENTALS 15


An Overview of Java - Data Types, Variables, and Arrays – Operators - Control
Statements – Class Fundamentals – Declaring objects – Methods – Constructors – this
keyword - Overloading methods - Overloading constructors - Access Control – Static –
Final.

List of Exercise/Experiments:
1. Develop a Java application to generate Electricity bill. You must use one
super
class called EB Bill and must have two sub classes namely Domestic Bill and
Commercial Bill. Create a class with the following members: Consumer no.,
consumer name, previous month reading, current month reading, type of EB
connection (i.e domestic or commercial). Compute the bill amount using the
following tariff
If the type of the EB connection is domestic, calculate the amount to be paid as
follows:
First 100 units - Rs. 1 per
unit 101-200 units - Rs.
2.50 per unit 201 -500
units - Rs. 4 per unit
> 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be
paid as follows:
First 100 units - Rs. 2 per
unit 101-200 units - Rs.
4.50 per unit 201 -500
units - Rs. 6 per unit
> 501 units - Rs. 7 per unit
2. Arrays Manipulations: (Use Methods for implementing these in a Class)
a. Find kth smallest element in an unsorted array
b. Find the sub array with given sum
c. Matrix manipulations – Addition, Subtraction, Multiplication
d. Remove duplicate elements in an Array
e. Accept an integer value N and print the Nth digit in the integer sequence 1,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 and so on till infinity.
Example: The 11th digit in the sequence 12345678910111213…. is 0.
UNIT II INHERITANCE, INTERFACES AND EXCEPTION HANDLING 15
Inheritance: Inheritance basics, Using super, Method Overriding, Using
Abstract Classes, Using final with Inheritance - Package and Interfaces: Packages,
Packages and member access, Importing Packages, Interfaces, Static Methods in an
Interface – Exception Handling: Exception-Handling Fundamentals, Exception Types,
Uncaught Exceptions, Using try and catch, Multiple catch Clauses, Nested try
Statements, throw, throws, finally, Java’s Built-in Exceptions.

8
List of Exercise/Experiments:
1. Develop a Java application with Employee class with Emp_name, Emp_id, Address,
Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant
Professor, Associate Professor and Professor from employee class. Add Basic
Pay (BP) as the member of all the inherited classes with 97% of BP as DA, 10 %
of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund. Generate pay slips
for the employees with their gross and net salary.
2. Design a Java interface for ADT Stack. Implement this interface using array
and
built-in classes. Provide necessary exception handling in both the implementations.
3. Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains the methods print Area () that prints the
area of the given shape and Numberofsides() that prints the number of sides of the
given shape.
4. Write a Java program to apply built-in and user defined exceptions.

UNIT III MULTITHREADING, I/O AND GENERIC PROGRAMMING 15


Multithreaded Programming: Creating a Thread, Thread Priorities, Synchronization,
Interthread Communication – I/O: I/O Basics, Reading Console Input, Writing Console
Output, Reading and Writing Files – Generics: Introduction, Generic class, Bounded
Types, Generic Methods, Generic Interfaces, Generic Restrictions.

List of Exercise/Experiments:
1. Write a Java program that correctly implements producer consumer problem
using
the concept of inters thread communication.
2. Write a Java program to read and copy the content of one file to other
by handling all file related exceptions.
UNIT IV STRING HANDLING AND COLLECTIONS 15
Lambda Expressions - String Handling – Collections: The Collection Interfaces,
The Collection Classes – Iterator – Map - Regular Expression Processing.

List of Exercise/Experiments:
1. String Manipulation:
a. Reversing a set of words and count the frequency of each letter in the string.
b. Pattern Recognition - Find the number of patterns of form 1[0]1 where
[0] represents any number of zeroes (minimum requirement is one 0)
there should not be any other character except 0 in the [0] sequence in
a given binary string.
c. Remove all the occurrences of string S2 in string S1 and print the remaining.
d. Find the longest repeating sequence in a string
e. Print the number of unique string values that can be formed by rearranging

9
the letters in the string S.
2. Collections:
a. Write a program to perform string operations using ArrayList. Write
functions
for the following
i. Append - add at end
ii. Insert – add at particular index
iii. Search
iv. List all string starts with given letter
b. Find the frequency of words in a given text.
UNIT V JDBC CONNECTIVITY 15
JDBC – DataSource, Configurations, Connection, Connection Pools, Driver
Types, ResultSet, Prepared Statement, Named Parameter, Embedded SQL (Insert,
Update, Delete, Join, union etc), ResultSet Navigation, Connection Close and Clean up.

List of Exercise/Experiments:
1. Mini Project (using JDBC) TOTAL: 45+30=75
PERIODS

TEXT BOOK:
1. Herbert Schildt, “Java: The Complete Reference”, 11th Edition, McGraw
Hill Education, 2019.

REFERENCES:
1. Cay S. Horstmann, Gary Cornell, “Core Java Volume – I Fundamentals”,
11th Edition, Prentice Hall, 2019.
2. Paul Deitel, Harvey Deitel, Java SE 8 for programmers, 3rd Edition,
Pearson, 2015.
3. Steven Holzner, Java 2 Black book, Dream tech press, 2011.
4. Timothy Budd, Understanding Object-oriented programming with Java, Third
Edition, Pearson Education, 2008.
5. https://infyspringboard.onwingspan.com/web/en/app/toc/lex_299594739473672
7 0000_shared/overview

10
5. Course Outcomes
At the end of this course, the students will be able to:

Course Outcomes HKL


Understand the object-oriented programming concepts and
CO1 fundamentals of Java. K2

CO2 Develop Java programs with the packages, interfaces, and exceptions. K3
Build java applications with I/O streams, threads, and generics
CO3 programming. K3

CO4 Apply strings and collections in developing applications. K3

CO5 Implement the concepts of JDBC. K3

1
1
6. CO-PO/PSO Mapping

POs/PSOs
PS
COs P P P P P P P P P PO PO PO PS PS O
O O O O O O O O O 1 1 1 O O 3
1 2 3 4 5 6 7 8 9 0 1 2 1 2
CO1 3 3 3 - - - - - - - - - 3 2 2
CO2 3 2 2 - - - - - - - - - 3 2 2
CO3 3 2 2 - - - - - - - - - 3 2 2
CO4 3 2 2 - - - - - - - - - 3 2 2
CO5 3 2 2 - - - - - - - - - 3 2 2
7.Lecture Plan
UNIT - III

S. Scheduled Actual Date Mode of Taxonomy


Topic Date of Completion CO Delivery Level
No.

Multithreaded Video/
1 Programming, Creating CO3 K2
PPT
a Thread
PPT/
2 Thread Priorities CO3 K3
Demo
Synchronization,
PPT/
3 Interthread CO3 K3
Communication Demo

PPT/
4 I/O: I/O Basics CO3 K3
Demo
Reading Console
PPT/
5 Input, Writing CO3 K3
Console Output Demo
Reading and Writing PPT/
6 CO3 K3
Files Demo
Generics: Introduction,
PPT/
7 Generic class, CO3 K3
Bounded Types Demo
Generic methods, PPT/
8 CO3 K3
Generic Interfaces Demo
PPT/
9 Generic Restrictions CO3 K3
Demo
8. ACTIVITY BASED LEARNING – UNIT III

Complete The Puzzle: https://crosswordlabs.com/view/unit-3-oop-2


ACTIVITY BASED LEARNING – UNIT III
QUIZ- LINKS
Multithreading

https://quizizz.com/admin/quiz/5f2ce7e57bcc30001b886ae7

https://quizizz.com/admin/quiz/5f2b8dbb166dda001bd4d276

https://quizizz.com/admin/quiz/5f351bb858dbca001e8616b3

Generics in Java

https://www.sanfoundry.com/java-mcqs-generics/

http://www.allindiaexams.in/engineering/cse/java-generics-mcq-quiz-java-
generics-online-test
ACTIVITY BASED LEARNING – UNIT III

Test Yourself:

1. Thread priority in Java is?

a) Integer
b) Float
c) double
d) long

Ans :a

2. What will happen if two thread of the same priority are called to be processed

simultaneously?

a) Anyone will be executed first lexographically


b) Both of them will be executed simultaneously
c) None of them will be executed
d) It is dependent on the operating system

Ans:d
3.What will be the output of the following Java code?

classmultithreaded_programing

public static void main(String args[])

{
Thread t = Thread.currentThread();
System.out.println(t);

Ans: Thread[main,5,main]
ACTIVITY BASED LEARNING – UNIT III

4. Which of the following cannot be Type parameterized?


a) Overloaded Methods
b) Generic methods
c) Class methods
d) Overriding methods

Ans:a

5. Which of these instance cannot be created?


a) Integer instance
b) Generic class instance
c) Generic type instance
d) Collection instances

Ans:c
9. Lecture Notes

UNIT III MULTITHREADING, I/O AND GENERIC PROGRAMMING 15

Multithreaded Programming: Creating a Thread, Thread Priorities, Synchronization, Interthread


Communication - I/O: I/O Basics, Reading Console Input, Writing Console Output, reading and Writing
Files – Generics: Introduction, Generic class, Bounded Types, Generic Methods, Generic Interface,
Generic Restrictions.

18
UNIT – III
MULTITHREADING,I/O AND GENERIC PROGRAMMING

3.1 Thread:
A thread is referred as a light weight smallest part of a process. Threads are
independent because all the threads follow a separate path of execution within the
program. Each thread has its own program counter, stack and local variables. It uses
a shared memory area, files and per-process state.

Multithreading
The process of executing multiple threads simultaneously is known as
multithreading. Multithreading is a programming concept where a program
(process) is divided into two or more subprograms (process), which can be
implemented at the same time in parallel. A multithreaded program contains two or
more parts that can run concurrently and each part can perform different task at the
same time making optimal use of the available resources. Each part of such a
program is called a thread, and each thread defines a separate path of execution.

Advantages of Java Multithreading


It doesn't block the user because threads are independent and multiple
operations can be performed at the same time.

It can perform many operations together, hence saves time.


Threads are independent, so it doesn't affect other threads if an exception occurs
in one thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. Multitasking is
when multiple processes share common processing resources such as a CPU.
Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
Differences between Multi-threading and Multi-tasking

Process-based multi-tasking (Multiprocessing)


Executing various jobs or process together where each process is a separate
independent operation is called process-based multi-tasking. Each process has a
separate address in memory and switching from one process to another requires
some time for saving and loading registers and updating lists. A process is heavy
weight and cost of communication between the process is high.

Thread-based multi-tasking (Multithreading)


Executing several tasks simultaneously where each task is a separate independent
part of the same program is called Thread-based multitasking and each independent
part is called Thread. The main goal of multi-tasking is to make or do a better
performance of the system by reducing response time. Threads share the same
address space. A thread is light weight and cost of communication between the
thread is low.
3.1.1 Life Cycle of a Thread

A thread can be in any of the following states:


New
Runnable
Running
Blocked
Waiting
Timed Waiting
Terminated

New: A newly created thread that has not yet started the execution. It remains
in this state until the program starts the thread using start() method. It is also
referred to as a born thread.
Runnable: If a thread is in this state it means that the thread is ready for
execution and waiting for the availability of the processor. If all threads in queue
are of same priority then they are given time slots for execution in round robin
fashion.
Running: It means that the processor has given its time to the thread for
execution. A thread keeps running until the following conditions occurs:
(a)Thread give up its control on its own and it can happen in the following
situations:
A thread gets suspended using suspend() method which can only be revived
using resume() method.
A thread is made to sleep for a specified period of time using sleep(time)
method, where time is specified in milliseconds.
A thread is made to wait for some event to occur using wait () method. In
this case a thread can be scheduled to run again using notify() method.

(b) A thread is pre-empted by a higher priority thread.


Blocked: If a thread is prevented from entering into runnable state or waiting
for I/O to complete, then a thread is said to be in Blocked state. A thread in this
state cannot continue its execution until it is moved to runnable state. Any thread

in these states does not consume any CPU cycle.


Life Cycle of a Thread

Waiting: A thread waits indefinitely for another thread to perform a task. A


thread transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.
Timed Waiting: A thread that is waiting for another thread to perform a task for
a specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the dead or terminated state when it
successfully completes its task or otherwise terminated due to any error or even
forcefully killed.

The Thread life cycle is given in below Fig.4.1.

Fig.4.1 Life Cycle of a Thread


The Main() thread

When we run any java program, the program begins to execute its code starting
from the main method.
Therefore, the JVM creates a thread to start executing the code present in main
method. This thread is called as main thread.
Although the main thread is automatically created, it can be controlled by
obtaining a reference to it by calling currentThread() method.

Two important things to know about main thread are,


It is the thread from which other threads will be produced.
main thread must be always the last thread to finish execution.
3.1.2 Thread Priorities
Thread priorities

Thread priorities are integers which decide how one thread should be treated with
respect to the others.
Thread priority decides when to switch from one running thread to another, and
the process is called context switching.
A thread can voluntarily release control and the highest priority thread that is
ready to run is given the CPU.
A thread can be preempted by a higher priority thread no matter what the lower
priority thread is doing. Whenever a higher priority thread wants to run it does.
To set the priority of the thread, setPriority() method is used which is a method of
the class Thread Class.
In place of defining the priority in integers, we can use MIN_PRIORITY with value
1, NORM_PRIORITY(Default Priority) with value 5, MAX_PRIORITY with value 10.

Get and Set Thread Priority:

int getPriority(): Thread.getPriority() method returns priority of given thread.


void setPriority(int newPriority): Thread.setPriority() method changes the
priority of thread to the value newPriority.This method throws
IllegalArgumentException if value of parameter newPriority goes beyond
minimum(1) and maximum(10) limit.

Example:
public class Demo extends Thread
{
public void run()
{
System.out.println("Inside run method");
}
Thread Priorities

public static void main(String args[])


{
Demo t1 = new Demo();
Demo t2 = new Demo();

System.out.println("t1 thread priority:"+t1.getPriority());


System.out.println("t2 thread priority:"+t2.getPriority());
t1.setPriority(2);
t2.setPriority(5);
System.out.println("t1 thread priority:"+t1.getPriority());
System.out.println("t2 thread priority:"+t2.getPriority());
System.out.println(Thread.currentThread().getName());
System.out.println("Main thread Priority:“
+Thread.currentThread(). getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Main thread Priority:“

+Thread.currentThread().getPriority());
}
}

Output:
t1 thread priority:5
t2 thread priority:5
t1 thread priority:2
t2 thread priority:5
Main
Main thread priority:5
Main thread priority:10
3.1.3 Methods of Thread Class

Methods

getName(): It is used for obtaining a thread’s name


setName(): changes the name of the thread
getPriority(): Obtain a thread’s priority
setPriority(): changes the priority of the thread
isAlive(): Determine if a thread is still running
join(): Wait for a thread to terminate

run(): Entry point for the thread


sleep(): Suspend a thread for a period of time
start(): Start a thread by calling its run() method
isDaemon(): tests if the thread is a daemon thread
Thread currentThread(): returns the reference of currently executing
thread.

Thread.State getState(): returns the state of the thread.


sleep(): Causes the currently executing thread to sleep

Commonly used Constructors of Thread Class

Thread()
Thread(String name)
Thread(Runnable r)

Thread(Runnable r, String name)


3.1.4 Creation of Thread

There are two ways to create a thread in Java:


1) By implementing Runnable Interface
2) By extending Thread Class

1. By Implementing Runnable Interface

The easiest way to create a thread is to create a class that implements the Runnable
interface. To implement Runnable, a class need only implement a single method
called run().

Example:

class Demo implements Runnable


{
public void run()
{
try
{
for (int i = 4; i > 0; i--)
{
System.out.println("Child Thread:" +i);
Thread.sleep(1000);

}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted");
}
System.out.println("Exiting Child Thread");
}
}
Creation of Thread - By Implementing Runnable Interface
public class MainThread
{
public static void main(String args[])
{
Demo d = new Demo();
Thread s = new Thread(d);

s.start();
try
{
for (int i = 4; i > 0; i--)
{
System.out.println("Main Thread:" +i);
Thread.sleep(5000);
}
}
catch (InterruptedException e)
{
System.out.println("Main interrupted");
}
System.out.println("Exiting Main Thread");
}
}
Output:
Main Thread:4
Child Thread:4
Child Thread:3
Child Thread:2
Child Thread:1
Main Thread:3
Exiting Child Thread
Main Thread:2
Main Thread:1
Exiting Main Thread
Creation of Thread – By Extending Thread Class

2. By Extending Thread Class


The second way to create a thread is to create a new class that extends Thread, and
then to create an instance of that class. The extending class must override the
run( ) method, which is the entry point for the new thread. It must also call start( )
to begin execution of the new thread.

Example:
class Demo1 extends Thread
{
public void run()
{
try
{
for (int i = 4; i > 0; i--)
{
System.out.println("Child Thread:" +i);
Thread.sleep(1000);

}
}
catch (InterruptedException e)
{
System.out.println("Child interrupted");
}
System.out.println("Exiting Child Thread");
}
}
public class MainThread
{
public static void main(String args[])
{
Creation of Thread – By Extending Thread Class

Demo1 d = new Demo1();


d.start();

try
{
for (int i = 4; i > 0; i--)
{
System.out.println("Main Thread:" +i);
Thread.sleep(5000);

}
}
catch (InterruptedException e)
{
System.out.println("Main interrupted");
}
System.out.println("Exiting Main Thread");
}
}
Output:
Main Thread:4
Child Thread:4
Child Thread:3
Child Thread:2
Child Thread:1
Main Thread:3
Exiting Child Thread
Main Thread:2
Main Thread:1
Exiting Main Thread
3.1.5 Synchronizing Threads

Java Synchronization:

Synchronization in java is the capability to control the access of multiple threads to


any shared resource. Java Synchronization is a better choice if we want to allow
only one thread to access the shared resource.

Need for Synchronization:

When two or more threads start within a program, there arises a situation where
multiple threads try to access the same resources and finally produce erroneous and
unforeseen results. For ex., 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. This is implemented using a concept called monitors. Each object in Java
is associated with a monitor, which a thread can lock or unlock. Only one thread at a
time may hold a lock on a monitor. Java programming language provides a way of
creating threads and synchronizing their task by using synchronized blocks.

General Syntax:
synchronized(object)
{
//statement to be synchronized
}

Synchronization is mainly used to


To prevent thread interference.
To prevent consistency problem.
Synchronizing Threads

Types of Synchronization:
There are two types of synchronization
Process Synchronization: The simultaneous execution of multiple threads or
processes to reach a state such that they commit to a certain sequence of
actions.

Thread Synchronization: When more than one thread tries to access a shared
resource, it should be ensured that the resource will be used by only one thread
at a time.

Thread Synchronization:
There are two types of thread synchronization namely mutual exclusive and inter-
thread communication.
Mutual Exclusive
Synchronized method.
Synchronized block.

Static synchronization.
Cooperation (Inter-thread communication in java)

1. Mutual Exclusive helps keeping threads from interfering with one another while
sharing data. This can be done by three ways in java:
by synchronized method
by synchronized block
by static synchronization

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.
3.1.6 Synchronized Method

Example of synchronized method

public class SynThread


{
public static void main(String args[])
{
sync s = new sync();
ThreadDemo m1 = new ThreadDemo(s, "Thread1");
ThreadDemo m2 = new ThreadDemo(s, "Thread2");
ThreadDemo m3 = new ThreadDemo(s, "Thread3");

}
}
class ThreadDemo extends Thread
{
sync s;
ThreadDemo(sync s, String str)
{
super(str);
this.s = s;
start();

}
public void run()
{
s.print(Thread.currentThread().getName());
}
}
class sync
{
public synchronized void print(String str)
{
Synchronized Method
for (int i = 0; i < 3; i++)
{
System.out.println("Started:" + str);
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
}
}
}
}
Output:
Started:Thread1
Started:Thread1
Started:Thread1
Started:Thread3
Started:Thread3
Started:Thread3
Started:Thread2
Started:Thread2
Started:Thread2

Synchronized Block

Synchronized block can be used to perform synchronization on any specific


resource of the method.
For ex. If you have 20 lines of code in a method, and you want to synchronize
only 5 lines, synchronized block can be used. If you put all the codes of the
method in the synchronized block, it will work same as the synchronized method.
Synchronized Block

Syntax for synchronized block


synchronized (object reference expression)
{
//code block
}
An example of Synchronized block is given in the below Fig.4.2.

Fig.4.2 Synchronized Block


Synchronized Block

class syncblock
{
void print(int n)
{
synchronized(this)
{ //synchronized block
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try

{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class Thread1 extends Thread
{
syncblock s;
Thread1(syncblock s)

{
this.s=s;
}
` public void run()
{
s.print(5);
}
}
Synchronized Block
class Thread2 extends Thread
{
syncblock s;
Thread2(syncblock s)

{
this.s=s;
}
public void run()
{
s.print(100);
}
}
public class SynchBlock
{
public static void main(String args[])
{
syncblock obj = new syncblock(); //only one object

Thread1 t1=new Thread1(obj);


Thread2 t2=new Thread2(obj);
t1.start();

t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
3.1.7 Static synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
Use synchronized keyword on the static method to perform static synchronization.

Example:
class staticsync
{
synchronized static void print(int n)
{
for(int i=1;i<=3;i++)
{
System.out.println(n*i);
try

{
Thread.sleep(500);
}
catch(Exception e)
{
}
}
}
}
class Thread1 extends Thread
{
public void run()
{
staticsync.print(1);
}
}
class Thread2 extends Thread
{
public void run()
{
staticsync.print(3);
}
}
Static synchronization

class Thread3 extends Thread


{
public void run()
{
staticsync.print(50);
}
}
public class TestSynch
{
public static void main(String args[])
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
Thread3 t3=new Thread3();
t1.start();

t2.start();
t3.start();
}
}
Output:

3
6
9
1
2
3
50
100
150
3.1.8 INTER-THREAD COMMUNICATION

Definition
• Inter-Thread communication or Co-operation is defined as the process
of allowing synchronized threads to communicate with each other.
• It is a mechanism in which a thread is paused running in its critical section
and another thread is allowed to enter (or lock) in the same critical section to
be executed.

Methods of Object class used to implement Inter-Thread


Communication
Inter-Thread Communication can be implemented by following
methods of Object class

• wait()

• notify()

• notifyAll()
wait() Method causes current thread to release the lock and wait
until either another thread invokes the notify() method or the notifyAll() method for
this object, or a specified amount of time has elapsed. Figure 4.1 illustrates the
functionality of wait() method.

Figure 2.1: wait() Method Role


Syntax:
public final void wait()throws InterruptedException
public final void wait(long timeout)throws InterruptedException
notify() method wakes up a single thread that is waiting on this
object's monitor. If any threads are waiting on this object, one of them is chosen to
be awakened. Figure 4.2 illustrates the functionality of notify() method in Inter-
Process Communication.

Figure 4.2: Role of notify() method

Syntax: public final void notify()

notifyAll() wakes up all the threads that called wait() on the same
object.

Syntax: public void notifyAll()

Example for Inter-Thread Communication (Producer Consumer


Problem)

• Producer-consumer problem (also known as the bounded-buffer problem) is a


classic example of a multi-process synchronization problem

• The problem describes two processes, the producer and the consumer, which
share a common, fixed-size buffer used as a queue
• The producer’s job is to generate data, put it into the buffer, and start again

• At the same time, the consumer is consuming the data (i.e. removing it from
the buffer), one piece at a time. Figure 4.3 depicts the Producer-Consumer
Problem

Figure 4.3: Producer-Consumer Problem

While implementing, the following two conditions should be satisfied:

• Producer should not try to add data into the buffer when it is full

• Consumer should not try to remove data from an empty buffer


PROGRAM FOR PRODUCER CONSUMER PROBLEM
IMPLEMENTATION

public class ProducerConsumerTest {


public static void main(String[] args) {

Buffer c = new Buffer();


Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();

c1.start();
}
}

class Buffer {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {

wait();
} catch (InterruptedException e) {}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {

try {
wait();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();

}
}

class Consumer extends Thread {


private Buffer buff;

private int number;


public Consumer( Buffer c, int number) {
buff = c;

this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 5; i++) {
value = buff.get();

System.out.println("Consumer got: " + value);


}
}
}
class Producer extends Thread {
private Buffer buff;

private int number;


public Producer( Buffer c, int number) {
buff = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 5; i++) {
buff.put(i);
System.out.println("Producer put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}

OUTPUT
Producer put: 0
Consumer got: 0
Producer put: 1
Consumer got: 1
Producer put: 2
Consumer got: 2
Producer put: 3
Consumer got: 3
Producer put: 4
Consumer got: 4
3.2 Input / Output Basics

Java I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.

Stream

A stream can be defined as a sequence of data. There are two kinds of Streams −

1. InputStream − The InputStream is used to read data from a source.

2. OutputStream − The OutputStream is used for writing data to a destination.

Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes. Though
there are many classes related to byte streams but the most frequently used
classes are, FileInputStream and FileOutputStream. Following is an example
which makes use of these two classes to copy an input file into an output file −
Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java


standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method


Example
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in
creating output.txt file with the same content as we have in input.txt. So let's put
the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.

We can re-write the above example, which makes the use of these two classes to copy an
input file (having unicode characters) into an output file –

import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in
creating output.txt file with the same content as we have in input.txt. So let's put
the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that


contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream


output
Standard Streams
All the programming languages provide support for standard I/O where the user's
program can take input from a keyboard and then produce an output on the
computer screen.

In Java, 3 streams are created for us automatically with the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

System.out.println("simple message");

int i=System.in.read();//returns ASCII code of 1st character

System.out.println((char)i);//will print the character

System.err.println("error message");
3.1.2 Reading and Writing Console

Reading Console Input:

The preferred method of reading console input is to use a character-oriented


stream.

There are three different ways for reading input from the user in the command line
environment(console).

1. Using Buffered Reader Class


2. Using Scanner Class
3. Using Console Class
1.Using Buffered Reader Class

In Java, console input is accomplished by reading from System.in. To


obtain a character based stream that is attached to the console, wrap System.in
in a BufferedReader object. BufferedReader supports a buffered input stream.
Its most commonly used constructor is shown here:

BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of


BufferedReader that is being created. Reader is an abstract class. One of its
concrete subclasses is InputStreamReader, which converts bytes to characters.
To obtain an InputStreamReader object that is linked to System.in, use the
following constructor:

InputStreamReader(InputStream inputStream)
Because System.in refers to an object of type InputStream, it can be used for
inputStream. Putting it all together, the following line of code creates a
BufferedReader that is connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

After this statement executes, br is a character-based stream that is linked to the


console through System.in.
import java.io.*;
public class Test

{
public static void main(String[] args) throws IOException
{
//Enter data using BufferReader
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String name = br.readLine();
System.out.println(name);
}
}
Input
Computer
Output
Computer
2. Using Scanner Class

This is probably the most preferred method to take input. The main
purpose of the Scanner class is to parse primitive types and strings using regular
expressions, however it is also can be used to read input from the user in the
command line.

Advantages:
• Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from
the tokenized input.
• Regular expressions can be used to find tokens.
Example
// Java program to demonstrate working of Scanner in Java
import java.util.Scanner; class
GetInputFromUser

{
public static void main(String args[])
{
// Using Scanner for Getting Input from User Scanner in =
new Scanner(System.in);

String s = in.nextLine(); System.out.println("You entered


string: "+s);

int a = in.nextInt();
System.out.println("You entered integer: "+a);

float b = in.nextFloat();
System.out.println("You entered float: "+b);
}
}
Input Computer 12

14.3
Output
You entered string: Computer You entered
integer: 12

You entered float: 14.3


3. Using Console Class
It is a preferred way for reading user’s input from the command line. In
addition, it can be used for reading password-like input without echoing the
characters entered by the user; the format string syntax can also be used (like
System.out.printf()).

Advantages:
•Reading password without echoing the entered characters.
•Reading methods are synchronized.
•Format string syntax can be used.
Drawback:
•Does not work in non-interactive environment (such as in an IDE).
Example
//Java program to demonstrate working of System.console(). Note that //this
program does not work on IDEs as System.console() may require //console
public class Sample
{
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();

System.out.println(name);
}
}
3.1.3 Writing Console Output

Console output is most easily accomplished with print() and println() methods. These
methods are defined by the class PrintStream which is the type of object referenced by
System.in. Even though System.out is a byte stream, using it for a simple program output is
still acceptable.

Because the PrintStream is an output stream derived from the OutputStream, it also
implements the low-level method write(). Thus, write() can be used to write to the console.
The simplest form of write() defined by the PrintStream is shown below :

void write(int byteval)

This method writes the byte specified by byteval. Although byteval is declared as an integer,
only the low-order eight bits are written. Following is a short example that uses write() to
output the character 'X' followed by a newline to the screen:

class WriteConsoleOutput
{
public static void main(String args[])
{
int y;
y = 'X';
System.out.write(y);
System.out.write('\n');
}
}
Output
X

You will not often use write() to perform console output (although doing so might be useful
in some situations) because print() and println() are substantially easier to use.
Writing with printf()

The printf(String format, Object.. args) method takes an output string and multiple
parameter which are substituted in the given string to produce the formatted output
content. This formatted output is written in the console.

String name=“RMD”;

int age=25;

Console.printf(“My name is %s and my age is %d’,name,age);

Program output:

My name is RMD and my age is 25


3.1.4 Reading and Writing Files

Reading and Writing Files


A stream can be defined as a sequence of data. The InputStream is used to read
data from a source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.

The two important streams are FileInputStream and FileOutputStream

FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object
to read the file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the
file. First we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

Once you have InputStream object in hand, then there is a list of helper methods
which can be used to read to stream or to do other operations on the stream.
Sr.No. Method & Description
public void close() throws IOException{}
1 This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close
2 method of this file output stream is called when there are no more
references to this stream. Throws an IOException.

public int read(int r)throws IOException{}

3 This method reads the specified byte of data from the InputStream.
Returns an int. Returns the next byte of data and -1 will be returned if it's
the end of the file.
public int read(byte[] r) throws IOException{}

4 This method reads r.length bytes from the input stream into an array.
Returns the total number of bytes read. If it is the end of the file, -1 will be
returned.
public int available() throws IOException{}
5 Gives the number of bytes that can be read from this file input stream.
Returns an int.

There are other important input streams available, for more detail you can refer to the
following links −

 ByteArrayInputStream

 DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object
to write the file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write
the file. First, we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper
methods, which can be used to write to stream or to do other operations on the
stream.
Sr.No. Method & Description
public void close() throws IOException{}

1 This method closes the file output stream. Releases any system
resources associated with the file. Throws an IOException.
protected void finalize()throws IOException {}

This method cleans up the connection to the file. Ensures that the close
2 method of this file output stream is called when there are no more
references to this stream. Throws an IOException.

public void write(int w)throws IOException{}


3
This methods writes the specified byte to the output stream.
public void write(byte[] w)
4 Writes w.length bytes from the mentioned byte array to the
OutputStream.
There are other important output streams available, for more detail you can refer
to the following links −
• ByteArrayOutputStream

• DataOutputStream
Example
Following is the example to demonstrate InputStream and OutputStream.
import java.io.*;
public class fileStreamTest {

public static void main(String args[]) {

try {

byte bWrite [] = {11,21,3,40,5};


OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();

InputStream is = new FileInputStream("test.txt");


int size = is.available();

for(int i = 0; i < size;i++) {


System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given numbers in binary
format. Same would be the output on the stdout screen.
To sum up table below presents classes used to read and write text and binary
files in Java:

Stream Read Write


Byte FileInputStream FileOutputStream

Character InputStreamReader OutputStreamWriter

Character FileReader FileWriter

Last two classes FileReader and FileWriter are equivalent to using


InputStreamReader and OutputStreamWriter with Charset.defaultCharset().name()
as encoding. Default encoding (charset) may differ between various JVM’s, it is
always better to use InputStreamReader and OutputStreamWriter with
explicit encoding than to relay on FileReader and FileWriter classes.

class diagrams that connects classes described above with abstract classes like
Reader and Writer:
What will be the output of the following Java program?
import java.io.*;
class Chararrayinput
{
public static void main(String[] args)
{
String obj = "abcdef";
int length = obj.length();
char c[] = new char[length];
obj.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 0, 3);
int i;
try
{
while ((i = input2.read()) != -1)
{
System.out.print((char)i);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
a) abc
b) abcd
c) abcde
d) abcdef
What will be the output of the following Java program? (Note:
inputoutput.java is stored in the disk.)
import java.io.*;
class filesinputoutput
{
public static void main(String args[])
{
InputStream obj = new FileInputStream("inputoutput.java");
System.out.print(obj.available());
}
}
a) true
b) false
c) prints number of bytes in file
d) prints number of characters in the file

What will be the output of the following Java program?


import java.io.*;
public class filesinputoutput
{
public static void main(String[] args)
{
String obj = "abc";
byte b[] = obj.getBytes();
ByteArrayInputStream obj1 = new ByteArrayInputStream(b);
for (int i = 0; i < 2; ++ i)
{
int c;
while ((c = obj1.read()) != -1)
{
if(i == 0)
{
System.out.print((char)c);
}
}
}
}
}
a) abc
b) ABC
c) ab
d) AB
3.3 GENERIC PROGRAMMING

Generic programming enables the programmer to create classes, interfaces and


methods that automatically works with all types of data(Integer, String, Float etc).
It has expanded the ability to reuse the code safely and easily.
Advantages
There are 3 main advantages of Java generics
Type-safety: We can hold only a single type of objects in generics. It doesn’t
allow to store other objects
Type casting is not required: There is no need to typecast the object
Compile-Time Checking: It is checked at compile time so problem will not
occur at runtime.

Generic class
A generic class is a class with one or more type variables. Generics means
parameterized types. Parameterized types enables to create classes, interfaces,
and methods in which the type of data upon which they operate is specified as a
parameter. Class, interface, or method that operates on a parameterized type is
called generic, as in generic class or generic method.

Syntax for declaring a generic class:


class class-name<type-param-list >
{ // …
Syntax for declaring a reference to a generic class:
class-name<type-arg-list > var-name =new class-name<type-arg-list >(cons-arg-
list);
}
Example Program:
// A simple generic class.
// Here, T is a type parameter that class Gen<T>
{
T ob; // declare an object of type T Gen(T o)
{
ob = o;
}
// Return ob. T getob()
{
return ob;
}
// Show type of T.
void showType()
{
System.out.println("Type of T is " +ob.getClass().getName());
}
}

public class GenDemo


{
public static void main(String[] args)
{
// Create a Gen reference for Integers.

Gen<Integer> iOb= new Gen<Integer>(88); iOb.showType();

int v = iOb.getob(); System.out.println("value: " +v);

// Create a Gen object for Strings.


Gen<String> strOb = new Gen<String> ("RMDEC"); strOb.showType();
String str = strOb.getob(); System.out.println("value: +str);

}
}

Output:

Type of T is java.lang.Integer value: 88

Type of T is java.lang.String value: RMDEC


Note: Generics Work Only with Objects
When declaring an instance of a generic type, the type argument passed to
the type parameter must be a class type.Primitive type, such as int or char can’t be
used. Gen<int> intOb = new Gen<int>(53); // Error, can't use primitive type
Java’s autoboxing and auto-unboxing mechanism makes the use of the type
wrapper transparent.
A Generic Class with Two Type Parameters
It is possible to declare more than one type parameter in a generic type. To specify
two or more type parameters, simply use a comma-separated list.
class TwoGen<T, V>
{
T ob1; V ob2;
TwoGen(T o1, V o2)
{
ob1 = o1; ob2 = o2;
}
void showTypes()
{
System.out.println("Type of T is “ +ob1.getClass().getName());
System.out.println("Type of V is " +ob2.getClass().getName());
}
T getob1()
{
return ob1;
}
V getob2()
{
return ob2;
}
}
public class GenDemo
{
public static void main(String[] args)
{
// Create a Gen reference for Integers.
TwoGen<Integer, String> tgObj =new TwoGen<Integer, String>
(88, " R.M.D Engineering College");
tgObj.showTypes();
int v = tgObj.getob1();
System.out.println("value: " + v); String str = tgObj.getob2();
System.out.println("value: " + str);
}
}
Output:
Type of T is java.lang.Integer
Type of V is java.lang.String value: 88
value: R.M.D Engineering College
Explanation:
Here, class TwoGen<T, V> has two type parameters: T and V, separated by a
comma. Because it has two type parameters, two type arguments must be passed
to TwoGen when an object is created. In this case, Integer is substituted
for T, and String is substituted for V.
3.3.1 Generic methods:
Methods inside a generic class can make use of a class’ type parameter and are,
therefore, automatically generic relative to the type parameter. However, it is
possible to declare a generic method that uses one or more type parameters of its
own. The scope of arguments is limited to the method where it is declared. It
allows static as well as non-static methods.
Syntax for a generic method:
<type-parameter> return_type method_name (parameters)
{
...
}
Example 1:
class Demo
{
static <V, T> void display (V v, T t)
{
System.out.println(v.getClass().getName()+" = " +v);
System.out.println(t.getClass().getName()+" = " +t);
}
public static void main(String[] args)
{
display(88," R.M.D Engineering College ");
}
}

Output:
java lang.Integer = 88
java lang.String = R.M.D Engineering College
Example 2:
Following example illustrates how we can print an array of different type using a
single Generic method
public class GenericMethodTest
{
// generic method printArray
public static < E > void printArray( E[] inputArray )
{
// Display array elements for(E element : inputArray)
{
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[])
{
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'R', 'M', 'D', 'E', 'C' };

System.out.println("Array integerArray contains:");


printArray(intArray);// pass an Integer array

System.out.println("Array doubleArray contains:");


printArray(doubleArray); // pass a Double array

System.out.println("Array characterArray contains:");


printArray(charArray); // pass a Character array
}
}
Output
Array integerArray contains:
12345
Array doubleArray contains:
1.1 2.2 3.3 4.4
Array characterArray contains:
RMDEC
3.3.2 Bounded Types:
In Java Generics it is possible to set restriction on the type that will be allowed to
pass to a type-parameter. This is done with the help of extends keyword when
specifying the type parameter.

< T extends Number >


Here we have taken Number class, it can be any wrapper class name. This
specifies that T can be only be replaced by Number class data itself or any of its
subclass.
Example: Create a generic class that contains a method that returns the average of
an array of numbers.
class Stats<T extends Number>
{
T[] nums; // array of Number or subclass
Stats(T[] o)
{
nums = o;
}
double average()
{
double sum = 0.0;
for(int i=0; i < nums.length; i++) sum += nums[i].doubleValue(); return sum /
nums.length;
}
}
public class GenDemo
{
public static void main(String[] args)
{
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
}
}
Output:
iob average is 3.0 dob average is 3.3

3.3.3 Generic Interface


Comparable interface is a great example of Generics in interfaces and it’s written as:
Package
import java.util*;
public interface Comparable<T>
{
public int compareTo(T o);
}
In similar way, we can create generic interfaces in java. We can also have multiple
type parameters as in Map interface. Again we can provide parameterized value to a
parameterized type also, for example new HashMap<String, List<String>>(); is
valid.
3.3.4 Restrictions and Limitations:
There are a few restrictions that you need to keep in mind when using generics.
They involve creating objects of a type parameter, static members, exceptions,
and arrays.
Type Parameters Can’t Be Instantiated
It is not possible to create an instance of a type parameter.
For example, consider this class: class Gen<T>
{
T ob; Gen()
{
ob = new T(); // Illegal!!!
}
}
Here, it is illegal to attempt to create an instance of T. The reason is since T does
not exist at run time, how the compiler doesn’t know what type of object to create.

3.3.5 Restrictions on Static Members


No static member can use a type parameter declared by the enclosing class. For
example,both of the static members of this class are illegal:
class Wrong<T>
{
// Wrong, no static variables of type T.
static T ob;
// Wrong, no static method can use T. static T getob()
{
return ob;
}
}
Although we can’t declare static members that use a type parameter declared by
the enclosing class, we can declare static generic methods, which define their own
type parameters.
3.3.6 Generic Array Restrictions
There are two important generics restrictions that apply to arrays.
First, you cannot instantiate an array whose element type is a type parameter.
Second, you cannot create an array of type-specific generic references. The
following short program shows both situations:
// Generics and arrays.
class Gen<T extends Number>
{
T ob;
T vals[]; // OK Gen(T o, T[] nums)
{
ob = o;
// This statement is illegal.
// vals = new T[10]; // can't create an array of T
// But, this statement is OK.
vals = nums; // OK to assign reference to existent array
}
}
class GenArrays
{
public static void main(String args[])
{
Integer n[] = { 1, 2, 3, 4, 5 };
Gen<Integer> iOb = new Gen<Integer>(50, n);
// Can't create an array of type-specific generic references.
// Gen<Integer> gens[] = new Gen<Integer>[10]; // Wrong!
// This is OK.
Gen<?> gens[] = new Gen<?>[10]; // OK
}
}
The reason you can’t create an array of T is that T does not exist at run time, so
there is no way for the compiler to know what type of array to actually create.
However, you can pass a reference to a type-compatible array to Gen( ) when an
object is created and assign that reference to vals, as the program does in this line:

Generic Exception Restriction


A generic class cannot extend Throwable. This means that you cannot create
generic exception classes.

Runtime Type Inquiry Only Works with Raw Types


Objects in the virtual machine always have a specific non generic type.
Therefore, all type inquiries yield only the raw type. you will get a compiler error
(with instanceof) or warning (with casts) when you try to inquire whether an object
belongs to a generic type.

Beware of Clashes after Erasure


It is illegal to create conditions that cause clashes when generic types are
erased.Here is an example. Suppose we add an equals method to the Pair class,
public class Pair<T>

{
public boolean equals(T value)
{
return first.equals(value) && second.equals(value); . . .
}

Consider a Pair<String>. Conceptually, it has two equals methods:


boolean equals(String) // defined in Pair<T>

boolean equals(Object) // inherited from Object

But the intuition leads us astray. The erasure of the method boolean
equals(T) is boolean equals(Object) which clashes with the Object.equals method.
The remedy is, to rename the offending method.
10. Assignments

1.Write a Java program that spawns n threads, where n is a program argument.


These threads access a shared counter (initialized as 0) in a loop. In each
iteration, they read the counter to a local (stack) variable, increment it, and store
it back to the counter. When all threads complete 10000 iterations each, the
program stops and prints the value of the shared counter. Note that the final value
may be smaller than the total number of iterations. Run the program on 1, 4, 8
and 16 threads and report the results in a textual table in the “doc.txt file”. In your
report, include the run time in miliseconds. You can measure the run time by
calling the System.currentTimeMillis() before and after the execution.

2.The Java concurrency package, java.util.concurrent, is a library that provides


synchronization tools for Java programs. This library includes a built-in mutual
exclusion primitive called ReentrantLock. You may also look at the ReentrantLock
Tutorial here . You are required to write a Java program doing the same task as in
part A but protect the shared counter using java.util.concurrent.ReentrantLock, so
no two threads modify the counter at the same time. Run the program on 1, 4, 8
and 16 threads and report the results in a textual table in the doc.txt file. In your
report, include the run time in miliseconds.
PART – A
1. What is thread in Java? (K1, CO4)
A Thread is a concurrent unit of execution. Or in other words you can say that it
is part of process that can run concurrently with other parts of the process.
2. What is Multithreading? (K1, CO4)
The process of executing multiple threads simultaneously is known as
multithreading. Java supports multithreading.
The main advantage of multithreading is reducing CPU idle time and improving
the CPU utilization. This makes the job to be completed in less time.
3. What is the difference between a process and a thread in Java?
(K1, CO4)
A program in execution is often referred as process. A thread is a subset(part) of
the process.
A process consists of multiple threads. A thread is a smallest part of the process
that can execute concurrently with other parts(threads) of the process.
A process is sometime referred as task. A thread is often referred as lightweight
process.
A thread can communicate with other thread (of the same process) directly by
using methods like wait(), notify(), notifyAll(). A process can communicate with
other process by using inter-process communication.
New threads are easily created. However the creation of new processes require
duplication of the parent process.
Threads have control over the other threads of the same process. A process does
not have control over the sibling process, it has control over its child processes
only.
4. What are the two ways of creating a thread? (K1, CO4)
We can create a thread by using any of the two following methods.
1) By implementing Runnable interface
2) By extending Thread class
5. What is life cycle of thread? (K1, CO4)
New born state.
PART – A
Runnable state
Running state
Blocked state
Dead state
6. Can we start a thread twice in Java? (K1, CO4)
No, once a thread is started, it can never be started again. Doing so will throw an
illegalThreadStateException
7. Can we call run() method of Thread class? (K1, CO4)
We can call run() method if we want but then it would behave just like a normal
method and we would not be able to take the advantage of multithreading. In
general run() methods starts execution when we call start() method of a Thread
class.
8. What is deadlock? (K1, CO4)
A deadlock is a condition when two or more threads are in waiting for each other
to release the resources that they need. For example Thread A holds a resource X
and need resource Y whereas Thread B holds a resource Y and need X, in this
case both threads are waiting for each other to release the resource and are in
blocked condition.
9. What is synchronization? (K1, CO4)
It is a technique of granting access to the shared resources in multithread
environment to avoid inconsistencies in the results.
10. What is the difference between notify() and notifyAll()? (K1, CO4)
notify() wakes up the first thread that called wait() on the same object, whereas
the notifyAll() method wakes up all the waiting threads.
11. What does join() method do? (K1, CO4)
The join() method is used to hold the execution of currently running thread until
the specified thread is dead (finished execution).
12. How does thread communicate with each other? (K1, CO4)
when threads share resources, communication between Threads is important to
coordinate their efforts.
PART – A
Object class wait(), notify() and notifyAll() methods allows threads to
communicate about the lock status of a resource.
13. What is the difference between wait() and sleep() method? (K1, CO4)

wait() sleep()

The wait() method is defined in The sleep() method is defined


Object class. in Thread class.

The wait() method releases the The sleep() method doesn't


lock. release the lock.

14. What is Daemon Threads in Java? (K1, CO4)


Daemon thread is a thread that has no other role than to serve other threads.
Daemon thread have low priority.
Methods:
1. setDaemon(boolean on)
2. isDeamon()
15. What is thread group? (K1, CO4)
Thread group is a collection of thread that can be managed together.
All the threads belong to the same thread group.
Methods:
1. activeCount()
2. activeGroupCount()
3. checkAccess()
4. getName()
5. destroy()
6. enumerate()
7. interrupt()
PART – A
16. What are Generics? (K1, CO4)
Generics are used to create Generic Classes and Generic methods which can work
with different Types(Classes).

17. What is Generic Programming? (K1, CO4)


Generic programming means defining software components with type parameters.
Helps to write reusable object oriented components.
This helps to create class, method, interface that automatically works with
different types of data.

18. What is Generic class? (K1, CO4)


A class that operates on a parameterized type is called as a generic class.
Syntax:

class classname <type-param-list>


{
// statements
}
19. What is Generic Method? (K1, CO4)
Generic methods are methods that introduce their own type parameters.
A Generic methods can be a menber of an ordinary class or a generic class.
The type parameter of a generic method is local to that method not to the class
Syntax:
public <type-parameter> <returntype> function_name()
{
// statements
}
20. What is a generic type parameter? (K1, CO4)
Type is the name of a class or interface.
A generic type parameter is when a type can be used as a parameter in a class,
method or interface declaration.

Generic methods are methods that introduce their own type parameters.
PART – A
21. List out commonly used type parameters. (K4, CO4)
T type – represent first generic type parameter
S type – represent second generic type parameter
U type – represent third generic type parameter

V type – represent value of the map


N type – represent numbers
K type – represent key of a map
E type – represent element and used in collection framework
22. What are Some Advantages of Using Generic Types? (K1, CO4)
Generics is avoiding casts and provide type safety. This is particularly useful when
working with collections

23. What is Type Erasure? (K1, CO4)


Generic type information is only available to the compiler, not the JVM.
In other words, type erasure means that generic type information is not available
to the JVM at runtime, only compile time.

24. What is Type Inference? (K1, CO4)


Type inference is when the compiler can look at the type of a method argument
to infer a generic type.

25. What is a Bounded Type Parameter? (K1, CO4)


When we use bounded parameters, we are restricting the types that can be used
as generic type arguments.

Achieved by using “extends” when specifying the parameters.


Syntax:
<Type extends superclass>
26.Is it Possible to Declared a Multiple Bounded Type Parameter? (K1,
CO4)
Yes, Declaring multiple bounds for our generic types is possible.
PART – A
27. What is a Wildcard Type? (K1, CO4)
A wildcard type represents an unknown type. It's detonated with a question mark as
follows:
public static void f1(List<?> list)
There are 3 kinds of wildcard types:

1. wildcard with lower bound


2. wildcard with upper bound
3. unbounded wildcard
28. What is lower bound wildcard? (K1, CO4)
A lower bounded wildcard means we are forcing the type to be a superclass of our
bounded type

< ? Extends E > any sub types of E


29. What is upper bound wildcard? (K1, CO4)
An upper bounded wildcard is when a wildcard type inherits from a concrete type.
< ? Super N > any super type of N
30. What is unbound wildcard? (K1, CO4)
An unbounded wildcard is a wildcard with no upper or lower bound, that can
represent any type.

<?> any type

31.Define Stream. (K1, CO3)


A stream can be defined as a sequence of data. The InputStream is used to read
data from a source and the OutputStream is used for writing data to a destination

32. list the type of streams supported in Java. (K3, CO3)

1. Byte Stream : It is used for handling input and output of 8 bit bytes. The
frequently

used classes are FileInputStream and FileOutputStream.


2.Character Stream : It is used for handling input and output of characters. Charac-
ter stream uses 16 bit Unicode. The frequently used classes are FileReader and File
Writer.
PART – A

33. List out the predefined streams available in Java. (K3, CO3)

Java provides the following three standard streams −


•Standard Input − refers to the standard InputStream which is the keyboard by
default. This is used to feed the data to user’s program and represented as
system.in.

• Standard Output − refers to the standard OutputStream by default,this is console


and represented as system.out.
•Standard Error − This is used to output the error data produced by the user’s
program and usually a computer screen is used for standard error stream and
represented as system.err.
34. What is Byte stream in Java? list some of the Bytestream classes. (K1, CO3)
The byte stream classes provide a rich environment for handling byte-oriented I/O.
List of Byte Stream classes

• Byte Array Input Stream


• Byte Array Output Stream
• Filtered Byte Streams
• Buffered Byte Streams

35. What is character stream in Java? list some of the characterstream classes.
(K1, CO3)
The Character Stream classes provide a rich environment for handling character-
oriented I/O.
List of Character Stream classes
• File Reader
• File Writer
• Char Array Reader
• Char Array Writer

36. What are the two variations of read() method?


(K1, CO3)
public int read(byte[] bytes, int offset, int length) throws IOException

public int read(byte[] bytes) throws


IOException
PART – A

37. What are the two variations of write() method? (K1, CO3)
public void write(byte[] bytes, int offset, int length) throws IOException

public void write(byte[] bytes) throws


IOException
38.What’s the difference between println(), print() and printf()? (K1,
CO3)
print() - prints string inside the quotes println() - prints string inside the quotes
similar like print() method. Then the cursor moves to the beginning of the next
line. printf() - it provides string formatting (similar to printf in C/C++
programming).
39. Write about Fileinputstream. (K1, CO3)
• This stream is used for reading data from the files.
• Objects can be created using the keyword new and there are several types of
constructors available.
• The two constructors which can be used to create a FileInputStream object:
i)Following constructor takes a file name as a string to create an input stream
object to read the file:
OutputStream f = new FileOutputStream("filename ");
ii)Following constructor takes a file object to create an input stream object to read
the file. First we create a file object using File() method as follows:

File f = new File(“filename “);


InputStream f = new FileInputStream(f);
40. Write about Fileoutputstream. (K1, CO3)
• FileOutputStream is used to create a file and write data into it.
• The stream would create a file, if it doesn’t already exist, before opening it for
output.
• The two constructors which can be used to create a FileOutputStream object:
i)Following constructor takes a file name as a string to create an input stream
object to write the file:
OutputStream f = new FileOutputStream(“filename “);
ii)Following constructor takes a file object to create an output stream object to
write the file. First, we create a file object using File() method as follows:
File f = new File(“filename “);
OutputStream f = new FileOutputStream(f);
PART - B

1. What is a thread? Describe the lifecycle and states of thread with example. (K1,
K4, CO4)

2. Summarize briefly about thread synchronization with an example. (K2, CO4)


3. Demonstrate Inter thread communication and suspending, resuming and stopping
threads. (K2, CO4)

4. List the two ways of implementing threads with example. (K4, CO4)
5. Show how to extend thread class and how to implement runnable interface for
creating and starting threads? (K2, CO4)

6. Classify the generic in java with example. (K2, CO4)


7. Explain briefly about generic classes and methods in java programming. (K5, CO4)
8. Evaluate how generic methods and generic expressions are translated. (K6, CO4)
9. Design two threads to display odd numbered element in an array of size 50 and
even numbered elements in another array in size 50. create instances of the
above thread and run them. (K6, CO4)

10. Explain the concept of streams and its byte stream classes in detail. (K2, CO3)

11. Explain the use of File stream classes and file modes. Write an example program
for file manipulation. (K2, CO3)

12. Explain I/O streams with suitable examples. (K2, CO3)


13. Online Certifications
1. https://www.hackerrank.com/skills-verification/java_basic
2. https://www.sololearn.com/Course/Java/
3. https://www.coursera.org/specializations/object-oriented-programming
4. https://www.udemy.com/course/java-the-complete-java-developer-course/ [Paid]
5. https://nptel.ac.in/courses/106/105/106105191/ [Paid]
6. https://education.oracle.com/java-se-8-fundamentals/courP_3348 [Paid]
14. Real Time Applications

• Android Apps

• Scientific Applications

• Financial Applications

• Games

• Desktop Applications

• Web Applications

89
15.Content Beyond Syllabus - Java Thread Pool
• A thread pool is a collection of pre-initialized threads. Generally, the
size of the collection is fixed, but it is not mandatory. It facilitates the
execution of N number of tasks using the same threads. If there are more
tasks than threads, then tasks need to wait in a queue like structure (FIFO –
First in first out).
• When any thread completes its execution, it can pickup a new task from the
queue and execute it. When all tasks are completed the threads remain active
and wait for more tasks in the thread pool.

• A watcher keep watching queue (usually BlockingQueue) for any new tasks.
As soon as tasks come, threads again start picking up tasks and execute
them.

ThreadPoolExecutor
• Since Java 5, the Java concurrency API provides a mechanism Executor
framework. This is around the Executor interface, its sub interface
ExecutorService, and the ThreadPoolExecutor class that implements both
interfaces.

• ThreadPoolExecutor separates the task creation and its execution.


With ThreadPoolExecutor, you only have to implement the Runnable objects
and send them to the executor. It is responsible for their execution,
instantiation, and running with necessary threads.
• It goes beyond that and improves performance using a pool of threads. When
you send a task to the executor, it tries to use a pooled thread for the
execution of this task, to avoid continuous spawning of threads.
Java Concurrency
• Java Concurrency is a term that covers multithreading, concurrency and
parallelism on the Java platform. That includes the Java concurrency tools,
problems and solutions. This Java concurrency tutorial covers the core
concepts of multithreading, concurrency constructs, concurrency problems,
costs, benefits related to multithreading in Java.

• Concurrency is the ability to run several programs or several parts of a


program in parallel. Concurrency enable a program to achieve high
performance and throughput by utilizing the untapped capabilities of
underlying operating system and machine hardware. e.g. modern computers
has several CPU’s or several cores within one CPU, program can utilize all
cores for some part of processing; thus completing task much before in time
in comparison to sequential processing.
• The backbone of java concurrency are threads. A thread is a lightweight
process which has its own call stack, but can access shared data of other
threads in the same process. A Java application runs by default in one
process. Within a Java application you can work with many threads to achieve
parallel processing or concurrency.
16. ASSESSMENT SCHEDULE
Tentative schedule for the Assessment During 2022-2023 EVEN
semester

S.NO Name of the Start Date End Date Portion


Assessment

1 Unit Test 1 - - UNIT 1

2 IAT 1 06.05.2023 12.05.2023 UNIT 1 & 2

3 Unit Test 2 - - UNIT 3

4 IAT 2 10.06.2023 16.06.2023 UNIT 3 & 4

5 Revision 1 - - UNIT 5 , 1 &


2

6 Revision 2 - - UNIT 3 & 4

7 Model 05.07.2023 14.07.2023 ALL 5 UNITS


17. Text Books & References
TEXT BOOKS
1. Herbert Schildt, “Java The complete reference”, 11th Edition, McGraw Hill
Education, 2019.

REFERENCES
1. Cay S. Horstmann, Gary cornell, “Core Java Volume –I Fundamentals”, 9th Edition,
Prentice Hall, 2019.
2. Paul Deitel, Harvey Deitel, “Java SE 8 for programmers”, 3rd Edition, Pearson,
2015.
3. Steven Holzner, “Java 2 Black book”, Dreamtech press, 2011.
4. Timothy Budd, “Understanding Object-oriented programming with Java”, Updated
Edition, Pearson Education, 2008.
5. https://www.tutorialspoint.com/java/index.htm
6. https://www.javatpoint.com/java-tutorial
7. https://www.w3schools.com/java/
8. https://www.geeksforgeeks.org/java-tutorial/
9. https://docs.oracle.com/javase/tutorial/
18.Mini Project
Interest Calculator
Calculate interest based on the type of the account and the status of the
account holder. The rates of interest changes according to the amount
(greater than or less than 1 crore), age of account holder (General or
Senior citizen) and number of days if the type of account is FD or RD.
Some sample rates are given in the below tables: Rate of FD citizen) and
interest for amounts below 1 Crore:

Hint: Use necessary Built-in and User defined Exceptions and


multithreading concept
Current Rates of interest
Maturity Period General Senior Citizen
7 days to 14 days 4.50 5.00
15 days to 29 days 4.75 5.25
30 days to 45 days 5.50 6.00
45 days to 60 days 7 7.50
61 days to 184 days 7.50 8.00
185 days to 1 year 8.00 8.50

Rate of FD interest for amounts above 1 Crore:

Maturity Period Interest Rate


7 days to 14 days 6.50
15 days to 29 days 6.75
30 days to 45 days 6.75
45 days to 60 days 8
61 days to 184 days 8.50
185 days to 1 year 10.00
Rate of RD interests:

Current Rates of interest


Maturity Period General Senior Citizen
6 months 7.50 8.00
9 months 7.75 8.25
12 months 8.00 8.50
15 months 8.25 8.75
18 months 8.50 9.00
21 months 8.75 9.25

SB Account interest rates:


Type of Account Interest Rate
Normal 4%
NRI 6%

Requirements:

1. Separate classes should be created for the different types of accounts.


2. All classes should be derives from an abstract class named ‘Account’
which contains a method called ‘calculateInterest’.
3. Implement the calculateInterest method according to the type of the
account, interest rates, amount and age of the account holder.
4. If the user is entering any invalid value (For eg. Negative value) in any
fields, raise a user defined exception.

Sample class structure is given below:

Account(Abstract)

double interestRate

double amount
abstract double
calculateInterest()

FDAccount
double interestRate
double amount
int noOfDays
ageOfACHolder
abstract double
calculateInterest()

SBAccount
double interestRate
double amount
abstract double
calculateInterest()

RDAccount
double interestRate
double amount
int noOfMonths;
double
monthlyAmount;
abstract double
calculateInterest()
Sample Output:

Select the option:

1. Interest Calculator –SB


2. Interest Calculator –FD
3. Interest Calculator –RD
4. Exit
1

Enter the Average amount in your account: 10000


Interest gained: Rs. 400 Select the option:
1. Interest Calculator –SB
2. Interest Calculator –FD
3. Interest Calculator –RD
4. Exit
2

Enter the FD amount: 10000

Enter the number of days: 91

Enter your age: 65

Interest gained is: 800 Select the option:

1. Interest Calculator –SB


2. Interest Calculator –FD
3. Interest Calculator –RD
4. Exit
2

Enter the FD amount:


10000

Enter the number of days: 91

Enter your age: 34

Interest gained is: 750

Select the option:

1. Interest Calculator –SB


2. Interest Calculator –FD
3. Interest Calculator –RD
4. Exit

Enter the FD amount: 10000

Enter the number of days: -7

Enter your age: 78

Invalid Number of days. Please enter correct values.


Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.

You might also like