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

3 Mech - Java Programming Unit 4

Uploaded by

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

3 Mech - Java Programming Unit 4

Uploaded by

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

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.
JAVA PROGRAMMING

Department : Mechanical Engineering

Batch / Year :2021-2025 / II Year

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

6 CO- PO/PSO Mapping 10

7 Lecture Plan 11

8 Activity based learning 13

9 Lecture Notes 15

10 Assignments 52

11 Part A Questions & Answers 54

12 Part B Questions 61

13 Supportive online Certification courses 63

14 Real time Applications 64

15 Contents beyond the Syllabus 65

16 Assessment Schedule 70

17 Prescribed Text Books & Reference Books 71

18 Mini Project Suggestions 72

5
2. COURSE OBJECTIVES

• To understand Object Oriented Programming concepts and


fundamentals of Java
• To know the principles of packages, inheritance and
interfaces
• To define exceptions and multithreading
• To develop a java application with I/O streams and generics
classes
• To use the functionalities of Strings and Collections

6
3. PRE REQUISITES

Pre-requisite Chart

20CS302 – OBJECT ORIENTED


PROGRAMMING

20GE101 – PROBLEM SOLVING AND C


PROGRAMMING

7
4. SYLLABUS

20CS304 JAVA PROGRAMMING LTPC3003


OBJECTIVES:
• To understand Object Oriented Programming concepts and fundamentals of Java
• To know the principles of packages, inheritance and interfaces
• To define exceptions and multithreading
• To develop a java application with I/O streams and generics classes
• To use the functionalities of Strings and Collections
UNIT I : INTRODUCTION TO OOP AND JAVA FUNDAMENTALS 9
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.
UNIT II - INHERITANCE, PACKAGE AND INTERFACES 9
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
UNIT III - MULTITHREADING, I/O AND GENERIC PROGRAMMING 9
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. Multithreaded Programming: Thread Creation
UNIT IV I/O AND GENERIC PROGRAMMING 9
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.
UNIT V STRING HANDLING AND COLLECTIONS 9
String Handling – Collections: The Collection Interfaces, The Collection Classes – List,
Array List, Set, Iterator – Map.
TOTAL: 45 PERIODS

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

COURSE OUTCOMES HKL


Understand the Object Oriented Programming concepts and
CO1 K2
fundamentals of Java

Develop Java programs with the packages, inheritance and


CO2 K3
interfaces

CO3 Build applications using Exceptions and Threads. K3

CO4 Build Java applications with I/O streams and generics classes K3

CO5 Use Strings and Collections in applications K3


6. CO-PO/PSO Mapping

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

S. Scheduled Actual Date Mode of Taxonomy


Topic CO
No. Date of Completion Delivery Level
Video/
I/O Basics CO3
1 PPT K1
Reading Console Input, PPT/
CO3 K1
2 Writing Console Output Demo
PPT/
Reading and Writing Files CO3 K1
3 Demo
PPT/
4 Generics: Introduction CO3 K1
Demo
PPT/
Bounded Types CO3
5 Demo K2

PPT/
tGeneric Methods CO3
6 Demo K2

Generic Interfaces CO3 PPT/


7 Demo K3

PPT/
Generic Restrictions. CO3
8 Demo K2

PPT/
Generic Restrictions. CO3
9 Demo K3
LECTURE PLAN – UNIT IV

• ASSESSMENT COMPONENTS MODE OF DELEIVERY


• AC 1. Unit Test MD 1. Oral presentation
• AC 2. Assignment MD 2. Tutorial
• AC 3. Course Seminar MD 3. Seminar
• AC 4. Course Quiz MD 4 Hands On
• AC 5. Case Study MD 5. Videos
• AC 6. Record Work MD 6. Field Visit
• AC 7. Lab / Mini Project
• AC 8. Lab Model Exam
• AC 9. Project Review
ACTIVITY BASED LEARNING – UNIT IV

COMPLETE THE PUZZLES GIVEN BELOW

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

• 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 −
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
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");
Reading and
Writing Console
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);
}
}
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.
Reading and
Writing Files
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:
Quiz
1. Which of these is used to perform all input & output operations in Java?
A. streams
B. Variables
C. classes
D. Methods

2. Which of these is a type of stream in Java?


A. Integer stream
B. Short stream
C. Byte stream
D. Long stream

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

10. Which of these methods can be used to writing console output?


A. print()
B. println()
C. write()
D. All of the mentioned

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

12. Which of these method of class StringBuffer is used to reverse sequence of


characters?
A. reverse()
B. reverseall()
C. Reverse()
D. reverseAll()

13. Can System.out.println() be used to write data to a file?


Yes No
• 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 = input1.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?
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
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
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.
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

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

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.

 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.

 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:
10. Assignment
1. Write a program to read text from a file character by
character and display it on the screen.

2. Write a program to illustrate Generic Method and


Generic Clsss
11. PART – A
Question and Answers
PART - A

1. 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

2. 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.

3. 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.
PART – A

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

6. 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

7. 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


PART – A
8. 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).

9. 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);

10. 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 – A
11. What are Generics? (K1, CO4)
• Generics are used to create Generic Classes and Generic methods which can
work with different Types(Classes).
12. 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.
13. 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
}
14. 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
}
15. 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
16. 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
17. 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
18. 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.
19. 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.
20. 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>
21. Is it Possible to Declared a Multiple Bounded Type Parameter? (K1,
CO4)
• Yes, Declaring multiple bounds for our generic types is possible.
PART – A
22. 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
23. 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
24. 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
25. 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
12. PART – B
Questions
PART - B

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)

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


5. Explain briefly about generic classes and methods in java programming. (K5,
CO4)
6. Evaluate how generic methods and generic expressions are translated. (K6, CO4)
7. 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)
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

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;

// else return the front element


return A.get(front);
}
Implement Queue in Java using Array and Generics
// Method 2
// Returns value of element at rear
T rear()
{
// If it is not pointing to any element in queue
if (rear == -1)
return null;
return A.get(rear);
}
// Method 3
// Inserts element at the front of queue
void enqueue(T X)
{
// If queue is empty
if (this.empty()) {
front = 0;
rear = 0;
A.add(X);
}
// If queue is not empty
else {
front++;
if (A.size() > front) {
// Mov front pointer to next
A.set(front, X);
}
else
// Add element to the queue
A.add(X);
}
}
Implement Queue in Java using Array and Generics
// Method 4
// Deletes elements from the rear from queue
void dequeue()
{
// if queue doesn't have any elements
if (this.empty())
// Display message when queue is already empty
System.out.println("Queue is already empty");
// If queue has only one element
else if (front == rear) {
// Both are pointing to same element
front = rear = -1;
}
// If queue has more than one element
else {
// Incrememnt the rear
rear++;
}
}
// Method 5
// Checks whether the queue is empty
boolean empty()
{
// Both are initialized to same value
// as assigned at declaration means no queue made
if (front == -1 && rear == -1)
return true;
return false;
}
Implement Queue in Java using Array and Generics
// Method 6
// Print the queue
// @Override
public String toString()
{
if (this.empty())
return "";
String Ans = "";
for (int i = rear; i < front; i++) {
Ans += String.valueOf(A.get(i)) + "->";
}
Ans += String.valueOf(A.get(front));
return Ans;
}
}
// Class 2
// Main class
class Main {

// Main driver method


public static void main(String args[])
{
// Case 1 : Integer Queue

// Creating object of queue Class (user defined)


// Declaring object of integer type
queue<Integer> q1 = new queue<>();

// Pushing elements to the integer object created


// Custom input integer entries
q1.enqueue(5);
q1.enqueue(10);
q1.enqueue(20);
Implement Queue in Java using Array and Generics
// Print the queue after inserting integer elements
System.out.println(
"q1 after enqueue of 3 elements:\n" + q1);
q1.dequeue();
System.out.println("q1 after dequeue :\n" + q1);
// Case 2 : String Queue
// Creating object of queue Class (user defined)
// Declaring object of string type
queue<String> q2 = new queue<>();
// Pushing elements to the String object created
// Custom input string entries
q2.enqueue("hello");
q2.enqueue("world");
q2.enqueue(“Dear Students");
// Print the queue after inserting string elements
System.out.println(
"\nq2 after enqueue of 3 elements:\n" + q2);
// Printing front and rear of the above queue
System.out.println("q2 front = " + q2.front()
+ ", q2 rear = " + q2.rear());
// Case 3 : Float Queue
// Creating object of queue Class (user defined)
// Declaring object of float type
queue<Float> q3 = new queue<>();
// Display message only
System.out.println(
"\nCreated new Float type queue q3...");
// Display whether queue is empty or not
// using the empty() method
System.out.println(
"Checking if queue is empty or not :\n"
+ q3.empty());
}
}
16. Assessment Schedule
• Tentative schedule for the Assessment During
2021-2022 odd semester

Name of the
S.NO Start Date End Date Portion
Assessment

1 IAT 1 20.09.2021 25.09.2021 UNIT 1 & 2

2 IAT 2 22.10.2021 28.10.2021 UNIT 3 & 4

3 REVISION 13.11.2021 16.11.2021 UNIT 5 , 1 & 2

4 MODEL 18.11.2021 29.11.2021 ALL 5 UNITS

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:

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
General Senior Citizen
Period
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
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()

Hint: Use method overriding


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

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