3 Mech - Java Programming Unit 4
3 Mech - Java Programming Unit 4
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.
JAVA PROGRAMMING
Created by :
Dr J.Sathiamoorthy Associate Professor / CSE
Date : 08.08.2022
4
1. CONTENTS
Page
S. No. Contents
No
1 Contents 5
2 Course Objectives 6
3 Pre Requisites 7
4 Syllabus 8
5 Course outcomes 9
7 Lecture Plan 11
9 Lecture Notes 15
10 Assignments 52
12 Part B Questions 61
16 Assessment Schedule 70
5
2. COURSE OBJECTIVES
6
3. PRE REQUISITES
Pre-requisite Chart
7
4. SYLLABUS
OUTCOMES:
At the end of this course, the students will be able to:
CO1: Understand the Object Oriented Programming concepts and fundamentals of Java
CO2: Develop Java programs with the packages, inheritance and interfaces
CO3: Build applications using Exceptions and Threads.
CO4: Build Java applications with I/O streams and generics classes
CO5: Use Strings and Collections in applications
8
5. Course Outcomes
CO4 Build Java applications with I/O streams and generics classes K3
POs/PSOs
PS O
COs PO PO PO PO PO PO PO PO PO 9 PO1 PO1 PO1 PSO 1PSO 2 3
1 2 3 4 5 6 7 8 0 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 – IV
PPT/
tGeneric Methods CO3
6 Demo K2
PPT/
Generic Restrictions. CO3
8 Demo K2
PPT/
Generic Restrictions. CO3
9 Demo K3
LECTURE PLAN – UNIT IV
Across
3. Which of these class can be used to implement the input stream that uses a
character array as the source?
4. keyword is used to explicitly throw an exception
5. block is used to enclose the code that might throw an exception. It must be used
within the method.
7. divide any number by zero, there occurs
8. The wrong formatting of any value may occur
11. When does Exceptions in Java arises in code sequence?
13. Which of these classes can return more than one character to be returned to
input stream?
Down
1. inserting any value in the wrong index of array, it would result in
2. Which of these stream contains the classes which can work on character stream?
6. Which of these class is used to read characters in a file?
9. block is always executed whether an exception is handled or not
10. Which of these method of FileReader class is used to read characters from a file?
12. keyword is used to apply restrictions on class, method, and variable.
SCRAMBLED WORDS
ENCETPIOX _________________________
YTR __________________________
CTAHC __________________________
WORTH __________________________
NITUP __________________________
TSCAK __________________________
RARYNIEDX __________________________
UNMREBOFRAMT __________________________
LIEF __________________________
TSERAM __________________________
Input / Output
Basics - Streams
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
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 −
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 {
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
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.
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");
Reading and
Writing Console
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:
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);
}
}
Writing Console Output
• 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.
Reading and
Writing Files
Reading and Writing Files
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.
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.
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();
class diagrams that connects classes described above with abstract classes like
Reader and Writer:
Quiz
1. Which of these is used to perform all input & output operations in Java?
A. streams
B. Variables
C. classes
D. Methods
3. Which of these classes are used by Byte streams for input and output
operation?
A. InputStream
B. InputOutputStream
C. Reader
D. All of the mentioned
4. Which of these classes are used by character streams for input and output
operations?
A. InputStream
B. Writer
C. ReadStream
D. InputOutputStream
5. Which exception is thrown by read() method?
A. IOException
B. InterruptedException
C. SystemException
D. SystemInputException
A
6. Which of these is used to read a string from the input stream?
A. get()
B. getLine()
C. read()
D. readLine()
7. Which of these class is used to read characters and strings in Java from
console?
A. BufferedReader
B. StringReader
C. BufferedStreamReader
D. InputStreamReader
8. Which of these classes are used by Byte streams for input and output
operation?
A. InputStream
B. InputOutputStream
C. Reader
D. All of the mentioned
9. Which of these class contains the methods print() & println()?
A. System
B. System.out
C. BUfferedOutputStream
D. PrintStream
11. Which of these class is used to create an object whose character sequence is
mutable?
A. String()
B. StringBuffer()
C. Both of the mentioned
D. None of the mentioned
Advantages
There are 3 main advantages of Java generics
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());
}
}
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.
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' };
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.
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.
4. 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
5. 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
1. Explain the concept of streams and its byte stream classes in detail. (K2, CO3)
2. Explain the use of File stream classes and file modes. Write an example program
for file manipulation. (K2, CO3)
3. Explain I/O streams with suitable examples. (K2, CO3)
• Android Apps
• Scientific Applications
• Financial Applications
• Games
• Desktop Applications
• Web Applications
64
15. Content Beyond Syllabus
Implement Queue in Java using Array and Generics
The queue is a linear data structure that follows the FIFO rule (first in
first out). We can implement Queue for not only Integers but also
Strings, Float, or Characters. There are 5 primary operations in
Queue:
• enqueue() adds element x to the front of the queue
• dequeue() removes the last element of the queue
• front() returns the front element
• rear() returns the rear element
• empty() returns whether the queue is empty or not
// Importing input output classes
import java.io.*;
// Importing all utility classes
import java.util.*;
// Class 1
// Helper Class(user defined - generic queue class)
class queue<T> {
// front and rear variables are initially initiated to
// -1 pointing to no element that control queue
int front = -1, rear = -1;
// Creating an object of ArrayList class of T type
ArrayList<T> A = new ArrayList<>();
// Method 1
// Returns value of element at front
T front()
{
// If it is not pointing to any element in queue
if (front == -1)
return null;
Name of the
S.NO Start Date End Date Portion
Assessment
114
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 with Generics
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:
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
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()
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.