22CS202 JAVA PROGRAMMING UNIT-3
22CS202 JAVA PROGRAMMING UNIT-3
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
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
12 Part B Questions 89
13 Online Certifications 90
16 Assessment Schedule 94
5
2. Course Objectives
L T P C
22CS202 JAVA PROGRAMMING
3 0 2 4
OBJECTIVES:
6
3. PRE REQUISITES
• Pre-requisite Chart
7
4. Syllabus
L T P C
22CS202 JAVA PROGRAMMING
3 0 2 4
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.
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:
CO2 Develop Java programs with the packages, interfaces, and exceptions. K3
Build java applications with I/O streams, threads, and generics
CO3 programming. 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
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
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:
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?
Ans:d
3.What will be the output of the following Java code?
classmultithreaded_programing
{
Thread t = Thread.currentThread();
System.out.println(t);
Ans: Thread[main,5,main]
ACTIVITY BASED LEARNING – UNIT III
Ans:a
Ans:c
9. Lecture Notes
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.
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
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.
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.
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.
Example:
public class Demo extends Thread
{
public void run()
{
System.out.println("Inside run method");
}
Thread Priorities
+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
Thread()
Thread(String name)
Thread(Runnable r)
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:
}
}
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
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
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:
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
}
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
}
}
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
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
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
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.
• 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.
notifyAll() wakes up all the threads that called wait() on the same
object.
• 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
• Producer should not try to add data into the buffer when it is full
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();
}
}
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 5; i++) {
value = buff.get();
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 −
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
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
Let's see the code to print output and an error message to the console.
System.out.println("simple message");
System.err.println("error message");
3.1.2 Reading and Writing Console
There are three different ways for reading input from the user in the command line
environment(console).
BufferedReader(Reader inputReader)
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:
{
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);
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
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 :
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;
Program output:
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.
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.
• DataOutputStream
Example
Following is the example to demonstrate InputStream and OutputStream.
import java.io.*;
public class fileStreamTest {
try {
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
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.
}
}
Output:
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' };
{
public boolean equals(T value)
{
return first.equals(value) && second.equals(value); . . .
}
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
wait() sleep()
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
1. Byte Stream : It is used for handling input and output of 8 bit bytes. The
frequently
33. List out the predefined streams available in Java. (K3, CO3)
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
37. What are the two variations of write() method? (K1, CO3)
public void write(byte[] bytes, int offset, int length) throws IOException
1. What is a thread? Describe the lifecycle and states of thread with example. (K1,
K4, 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)
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)
• 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.
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:
Requirements:
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:
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.