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

Unit 5

The document outlines the course objectives and learning outcomes for a Java Programming course at Pimpri Chinchwad University, focusing on fundamental programming concepts, object-oriented principles, exception handling, multithreading, and GUI design. It provides an overview of the Java Collections Framework, including its benefits, core interfaces, and various implementations such as List, Set, and Map. Additionally, it covers file input/output operations in Java, highlighting the differences between byte and character streams.

Uploaded by

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

Unit 5

The document outlines the course objectives and learning outcomes for a Java Programming course at Pimpri Chinchwad University, focusing on fundamental programming concepts, object-oriented principles, exception handling, multithreading, and GUI design. It provides an overview of the Java Collections Framework, including its benefits, core interfaces, and various implementations such as List, Set, and Map. Additionally, it covers file input/output operations in Java, highlighting the differences between byte and character streams.

Uploaded by

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

1

PCET’S Pimpri Chinchwad University

Department of Computer Science and Engineering


Course Name : Java Programming
Course Code/Course Type : UBTCE212/PCC
SY. B.Tech

Prepared By: Java Trainer

PIMPRI CHINCHWAD UNIVERSITY


2

Course Objectives (CO):


• The objectives of Java Programming are:
To learn the fundamentals of the Java programming language.
To learn object-oriented principles like abstraction, encapsulation,
inheritance, and polymorphism and apply them in solving problems using
java.
To apply the concepts of exception handling, multithreading and collection
classes using java.

To develop software applications using JDBC connectivity.


To design the Graphical User Interface using applets and swing controls.
PIMPRI CHINCHWAD UNIVERSITY
3

Course Learning Outcomes (CLO):


• Students would be able to:
To grasp the fundamentals programming concepts of Java programming
language.

To apply object-oriented principles like abstraction, encapsulation,


inheritance, polymorphism in solving problems using java.
To perform exception handling, multithreading code using java.
To develop software applications using JDBC connectivity.
To design the Graphical User Interface using event handling.

PIMPRI CHINCHWAD UNIVERSITY


UNIT- V
Collections, File & Event Handling
The Java Collections Framework
• We will consider the Java Collections Framework as a good example of how to apply the
principles of objectoriented software engineering to the design of classical data
structures.
• A coupled set of classes and interfaces that implement commonly reusable collection data
structures.
• Designed and developed primarily by Joshua Bloch
What is a Collection & Collection Framework?
• An object that groups multiple elements into a single unit.
• Sometimes called a container.

• A unified architecture for representing and manipulating collections is called collection


framework.
• Includes-
• Interfaces: A hierarchy of ADTs.
• Implementations
• Algorithms: The methods that perform useful computations, such as searching and sorting, on objects that
implement collection interfaces.
• These algorithms are polymorphic: that is, the same method can be used on many different implementations
of the appropriate collection interface.
Benefits of Collections Framework
• Reduces programming effort: By providing useful data structures and algorithms, the
Collections Framework frees you to concentrate on the important parts of your program
rather than on the low-level "plumbing" required to make it work.
• Increases program speed and quality: Provides high performance, high-quality
implementations of useful data structures and algorithms.
• Allows interoperability among unrelated APIs: APIs can interoperate seamlessly, even
though they were written independently.
• Reduces effort to learn and to use new APIs
• Reduces effort to design new APIs
• Fosters software reuse: New data structures that conform to the standard collection
interfaces are by nature reusable.
Where is the Java Collections Framework?
• Package java.util.

• For additional details, please see


• Javadoc, provided with your java distribution.
• Comments and code in the specific java.util.*.java files, provided with your java distribution.
• The Collections Java tutorial, available at http://docs.oracle.com/javase/tutorial/collections/index.html
Where is the Java Collections Framework?
• Package java.util.

• For additional details, please see


• Javadoc, provided with your java distribution.
• Comments and code in the specific java.util.*.java files, provided with your java distribution.
• The Collections Java tutorial, available at http://docs.oracle.com/javase/tutorial/collections/index.html
Core Collection Interfaces
Operations

Basic collection operations:


• Check if collection is empty
• Check if an object exists in collection.
• Retrieve an object from collection
• Add object to collection
• Remove object from collection
• Iterate collection and inspect each object
Each operation has a corresponding method implementation for each
collection type
Traversing Collections in Java
• There are two ways to traverse collections:
– using Iterators.
– with the (enhanced) for-each construct
• An Iterator is an object that enables you to traverse through a collection and to remove
elements from the collection selectively, if desired. An Iterator for a collection by calling
its iterator method.
• Suppose collection is an instance of a Collection. Then to print out each element on a
separate line:
Iterator<E> it = collection.iterator();
while (it.hasNext())
System.out.println(it.next());

• Note that next() does two things:


1. Returns the current element (initially the first element)
2. Steps to the next element and makes it the current element.
Iterators
• Iterator Interface
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional
}

• hasNext() returns true if the iteration has more elements


• next() returns the next element in the iteration.
– throws exception if iterator has already visited all elements.
• remove() removes the last element that was returned by next.
– remove may be called only once per call to next
– otherwise throws an exception.
– Iterator.remove is the only safe way to modify a collection during iteration
Implementing Iterators
• Could make a copy of the collection.
– Good: could make copy private – no other objects could change it from under you.
– Bad: construction is O(n).
• Could use the collection itself (the typical choice).
– Good: construction, hasNext and next are all O(1).
– Bad: if another object makes a structural change to the collection, the results are
unspecified.
• Syntax:
Iterator <variable> = <CollectionObject>.iterator();
The Enhanced For-Each Statement
• Suppose collection is an instance of a Collection. Then
for (Object o : collection)
System.out.println(o);
prints each element of the collection on a separate line.
• This code is just shorthand: it compiles to use o.iterator().
Collections Hierarchy- Set and List
Collection

implements

Set List

implements extends implements

HashSet
SortedSet

extends
implements

LinkedHashSet TreeSet LinkedList Vector ArrayList


Collections Hierarchy- Map
Map

extends
implements

SortedMap

implements

Hashtable HashMap TreeMap

extends

LinkedHashMap
Collection Implementations

List : Lists of things (classes that implement List)

Set : Unique things (classes that implement Set)

Map : Things with a unique ID (classes that implement Map)


List

value “Paul” “Mark” “John” “Paul” “Luke”

index 0 1 2 3 4

A List cares about the index.


ArrayList

ArrayList Vector LinkedList


List Implementations-Array List

import java.util.ArrayList;
One
public class MyArrayList { Two
public static void main(String args[ ]) { Three

ArrayList alist = new ArrayList( );


alist.add(new String("One"));
alist.add(new String("Two"));
alist.add(new String("Three"));
System.out.println(alist.get(0));
System.out.println(alist.get(1));
System.out.println(alist.get(2));
}
}
List Implementations - Vector
import java.util.Vector; 1
public class MyVector { 2
3
public static void main(String args[ ]) {
Vector vecky = new Vector( );
vecky.add(new Integer(1));
vecky.add(new Integer(2));
vecky.add(new Integer(3));
for(int x=0; x<3; x++) {
System.out.println(vecky.get(x));
}
}
}
List Implementations -Linked List
import java.util.LinkedList;
1.0
public class MyLinkedList { 2.0
3.0
public static void main(String args[ ]) {
LinkedList link = new LinkedList( );
link.add(new Double(2.0));
link.addLast(new Double(3.0));
link.addFirst(new Double(1.0));
Object array[ ] = link.toArray( );
for(int x=0; x<3; x++) {
System.out.println(array[x]);
}
}
}
Set

“John” “Luke”
“Paul”
“Mark” “Fred”
“Peter”

A Set cares about uniqueness, it doesn’t allow duplicates.

HashSet LinkedHashSet TreeSet


Set Implementations - Hash Set
import java.util.*;
d
public class MyHashSet { a
c
public static void main(String args[ ]) { b
HashSet hash = new HashSet( );
hash.add("a");
hash.add("b");
hash.add("c");
hash.add("d");
Iterator iterator = hash.iterator( );
while(iterator.hasNext( )) {
System.out.println(iterator.next( ));
}
}
}
Set Implementations - Linked Hash Set
import java.util.LinkedHashSet;
One
public class MyLinkedHashSet { Two
public static void main(String args[ ]) { Three

LinkedHashSet lhs = new LinkedHashSet();


lhs.add(new String("One"));
lhs.add(new String("Two"));
lhs.add(new String("Three"));
Object array[] = lhs.toArray( );
for(int x=0; x<3; x++) {
System.out.println(array[x]);
}
}
}
Set Implementations - Tree Set
import java.util.TreeSet; Jody
import java.util.Iterator;
Philippe
public class MyTreeSet { Reggie
public static void main(String args[ ]) { Remiel

TreeSet tree = new TreeSet();


tree.add("Jody");
tree.add("Remiel");
tree.add("Reggie");
tree.add("Philippe");
Iterator iterator = tree.iterator( );
while(iterator.hasNext( )) {
System.out.println(iterator.next( ).toString( ));
}
}
}
Map

key “Pl” “Ma “Jn” “ul” “Le”


value “Paul” “Mark” “John” “Paul” “Luke”

A Map cares about unique identifiers.

HashMap Hashtable LinkedHashMap TreeMap


Map Implementations- Hash Map
import java.util.HashMap;
public class MyHashMap { Name: Jody
ID: 446
public static void main(String args[ ]) {
Address: Manila
HashMap map = new HashMap( );
map.put("name", "Jody");
map.put("id", new Integer(446));
map.put("address", "Manila");
System.out.println("Name: " + map.get("name"));
System.out.println("ID: " + map.get("id"));
System.out.println("Address: " + map.get("address"));
}
}
Map Implementations- Hash table
import java.util.Hashtable;
public class MyHashtable {
public static void main(String args[ ]) {
Hashtable table = new Hashtable( );
table.put("name", "Jody");
table.put("id", new Integer(1001));
table.put("address", new String("Manila"));
System.out.println("Table of Contents:" + table);
}
}

Table of Contents:
{address=Manila, name=Jody, id=1001}
Map Implementations - Linked Hash Map
Jody
import java.util.*;
446
public class MyLinkedHashMap { Manila
public static void main(String args[ ]) { Savings
int iNum = 0;
LinkedHashMap myMap = new LinkedHashMap( );
myMap.put("name", "Jody");
myMap.put("id", new Integer(446));
myMap.put("address", "Manila");
myMap.put("type", "Savings");
Collection values = myMap.values( );
Iterator iterator = values.iterator( );
while(iterator.hasNext()) {
System.out.println(iterator.next( ));
}
}
}
Map Implementations- Tree Map
import java.util.*;
Printing the VALUES....
public class MyTreeMap {
Manila
public static void main(String args[])446
{
Jody
TreeMap treeMap = new TreeMap( );
treeMap.put("name", "Jody");
treeMap.put("id", new Integer(446));
treeMap.put("address", "Manila");
Collection values = treeMap.values()
Iterator iterator = values.iterator( );
System.out.println("Printing the
VALUES....");
while (iterator.hasNext()) {
System.out.println(iterator.next(
));
}
}
}
Collection Classes Summary
Class Map Set List Ordered Sorted
HashMap X No No
Hashtable X No No
TreeMap X Sorted By natural order or custom
comparison rules
LinkedHashMap X By insertion order or No
last access order
HashSet X No No
TreeSet X Sorted By natural order or custom
comparison rules
LinkedHashSet X By insertion order or No
last access order
ArrayList X By index No
Vector X By index No
LinkedList X By index No
I/O Stream
• Input Stream: It is a stream which may be connected with different i/p devices like
keyboard, file or network socket. It is used to generate data.
• Output Stream: It is used to produce data and may be connected with different output
devices like monitor, file, network socket.
Files and Streams
• File processing with classes in package java.io
• FileInputStream for
byte-by-byte input from a file
• FileOutputStream for
byte-by-byte output to a file
• FileReader for char-by-char
input from a file
• FileWriter for char-by-char
output to a file
Difference
byte Stream char Stream
1. It deals with byte. 1. It deals with char or Strings.
2. Used to manipulate data in 2. Used to manipulate data in
binary format. Unicode.
3. Mainly uses audio, video, img, 3. Can be used only with txt files.
txt files. 4. Reader & Writer are top two
4. InputStream and OutputStream abstract classes of char Stream.
are top two abstract classes of
byte Stream.
byte-by-byte
• Constructors, Methods Of FileInputStream
• CONSTRUCTORS:
• FileInputStream(String fname);
• FileInputStream(File F);
• FileInputStream(String fold, String fname);
• METHODS:
• int read(); // n= fis.read(); // n is the byte read.

• Constructors, Methods Of FileOutputStream


• CONSTRUCTORS:
• FileOutputStream(String fname);
• FileOutputStream(File F);
• FileOutputStream(String fname, boolean app);
• METHODS:
• void write(int n); //write(n); //n is the byte to be written
• void write(byte []b); // writes the array contents to file.
Example: FileInputStream
import java.io.*;
public class ReadStringFromFile { while( (ch = fin.read()) != -1)
public static void main(String[] args) strContent.append((char)ch);
{ fin.close();
File file = new File("C://FileIO//ReadString.txt"); }
int ch; catch(Exception e){
StringBuffer strContent = new StringBuffer(""); System.out.println(e);
FileInputStream fin = null; }
try System.out.println("File contents :");
{ System.out.println(strContent);
fin = new FileInputStream(file); }
}
Example: FileOutputStream
import java.io.FileInputStream;
import java.io.FileOutputStream; fos.flush();
import java.io.IOException; FileInputStream fis = new
public class FileOutputStreamDemo { FileInputStream("C://test.txt");
public static void main(String[] args) throws while((i=fis.read())!=-1) {
IOException c=(char)i;
{ System.out.print(c); }
byte[] b = {65,66,67,68,69}; }catch(Exception ex)
int i=0; {ex.printStackTrace(); }
char c; finally{
try{ if(fos!=null)
FileOutputStream fos=new fos.close();
FileOutputStream("C://test.txt"); if(fis!=null)
fos.write(b); fis.close(); }
}}
char-by-char
• Constructors, Methods Of FileReader
• CONSTRUCTORS:
• FileReader(String fname);
• FileReader(File F);
• FileReader(String fold, String fname);
• METHODS:
• int read(); // n= fis.read(); // n is the char read.
• int read(char [] c, int offset, int len); // reads character into an array and returns the number of chars read.

• Constructors, Methods Of FileWriter


• CONSTRUCTORS:
• FileWriter(String fname);
• FileWriter(File F);
• FileWriter(String fold, String fname);
• METHODS:
• void write(String n); // write(n); //n is the String to be written to file.
• public void write(char [] c, int offset, int len); // Writes a portion of an array of characters starting from offset and
with a length of len.
• public void write(String s, int offset, int len);
Example: FileReader
import java.io.*;
public class FileRead {
public static void main(String args[]) throws
IOException {
File file = new File("Hello1.txt");
file.createNewFile(); //returns true if file is created
FileWriter fw = new FileWriter(file);
fw.write("This\n is\n an\n example\n");
fw.flush();
fw.close();
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); //reads content to array
for(char c : a)
System.out.print(c);
fr.close(); }
}
Example: FileReader using BufferedReader
import java.io.*;
public class Reader {
public static void main(String[]args) throws
IOException{
FileReader fr = new FileReader("C:/test.txt");
BufferedReader br = new BufferedReader(in);
while (br.readLine() != null)
{ System.out.println(br.readLine()); }
fr.close();
}
Example: FileWriter
import java.io.*; import java.io.BufferedWriter;
class Simple{ import java.io.File;
public static void main(String args[]){ import java.io.FileWriter;
import java.io.IOException;
try{
public class BufferedWriterDemo {
FileWriter fw=new FileWriter("abc.txt");
public static void main(String[] args) throws
fw.write(“Hello World"); IOException {
fw.close(); File f = new File("java2learn.txt");
} System.out.println(f.exists());
catch(Exception e) {System.out.println(e);} BufferedWriter bw = new BufferedWriter(new
System.out.println(“Success"); FileWriter(f));
} char[] ch1 = { 'a', 'b', 'c', 'd' };
} bw.write(ch1);
} }
Event Handling
• Event handling is fundamental to Java programming because it is used to create event
driven programs eg:
• Applets
• GUI based windows application
• Web Application
• Event handling mechanism have been changed significantly between the original version
of Java (1.0) and all subsequent versions of Java.
Event Handling
• Event Handling is the mechanism that controls the event and decides what should happen
if an event occurs .
• This mechanism have the code which is known as event handler that is executed when an
event occurs.
• Java Uses the Delegation Event Model to handle the events.
• This model defines the standard mechanism to generate and handle the events Let's have
a brief introduction to this model.
Event
• What is Event ?
• Change in the state of an object is known as event i e event describes the change in state of source
• Events are generated as result of user interaction with the graphical user interface components.
• For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item
from list, scrolling the page are the activities that causes an event to happen.
• Types of Event:
• The events can be broadly classified into two categories
• Foreground Events :Those events which require the direct interaction of user
• They are generated as consequences of a person interacting with the graphical components in Graphical User
Interface
• For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an
item from list, scrolling the page etc.
• Background Events: Those events that require the interaction of end user are known as background events
• Operating system interrupts, hardware or software failure, timer expires, an operation completion are the
example of background events
Source & Listener
• The Delegation Event Model has the following key participants namely
• Source The source is an object on which event occurs
• Source is responsible for providing information of the occurred event to it's handler Java provides classes for
source object.
• Listener It is also known as event handler
• Listener is responsible for generating response to an even t From java implementation point of view the listener is
also an object. Listener waits until it receives an event Once the event is received the listener process the event an
then returns.
• Its concept is quite simple a source generates an event and sends it to one or more
listeners In this scheme, the listener simply waits until it receives an event.
• Once an event is received, the listener processes the event and then returns.
• This provides an important benefit notifications are sent only to listeners that
• want to receive them.
• To perform Event Handling, we need to register the source with the listener
Registering Listener
• A source must register listeners in order for the listeners to receive notifications about a
specific type of event Each type of event has its own registration method Here is the
general form
• public void addTypeListener(TypeListener el)
• Type is the name of the event, and el is a reference to the event listener
• For example, the method that registers a keyboard event listener is called addKeyListener
The method that registers a mouse motion listener is called addMouseMotionListener
Delegation Event Model
Event Classes in Java
Event Classes in Java
Event Classes in Java
Event Listener Interfaces
• The delegation event model has two parts sources and listeners
• Listeners are created by implementing one or more of the interfaces defined by the java
awt event package
• When an event occurs, the event source invokes the appropriate method defined by the
listener and provides an event object as its argument
Event Listener Interfaces
Event Listener Interfaces
Java MouseListener Interface
• T he Java MouseListener is notified whenever you change the state of mouse It is
notified against MouseEvent.
• The MouseListener interface is found in java awt event package It has five methods.
• The signature of 5 methods found in MouseListener interface are given below:
• public abstract void mouseClicked MouseEvent e);
• public abstract void mouseEntered MouseEvent e);
• public abstract void mouseExited MouseEvent e);
• public abstract void mousePressed MouseEvent e);
• public abstract void mouseReleased MouseEvent e);
MouseListener Sample Program
48

Assignment Questions
Write a Java program to create an ArrayList of integers and perform the following operations:
• Add 5 integers entered by the user.
• Remove the element at index 2.
• Update the value at index 1.
• Print the final ArrayList.
Write a Java program that demonstrates the use of a Vector to store student names. Perform the following
operations:
• Add 4 student names to the Vector.
• Insert a new student at index 2.
• Remove the last student from the Vector.
• Display the Vector before and after modifications.
Write a Java program using a Hashtable to store employee IDs (Integer) and their corresponding names
(String). Perform the following:
• Add 3 employee records.
• Remove an employee using their ID.
• Search for an employee using an ID and display their name.
PIMPRI CHINCHWAD UNIVERSITY
49

Assignment Questions
Write a Java program to implement a stack using the Stack class. The program should allow:
• Pushing 5 integer values onto the stack.
• Popping the top 2 values from the stack.
• Displaying the stack after each operation.
Write a Java program that demonstrates the use of Lambda Expressions to:
• Create a list of integers.
• Use the forEach method with a Lambda expression to print each element.
• Use a Lambda expression to filter and display only even numbers.
Write a Java program to copy the contents of one file to another using FileInputStream and
FileOutputStream (byte stream).
• Read data from source.txt and write it to destination.txt.
• Ensure proper exception handling.

PIMPRI CHINCHWAD UNIVERSITY


49

Assignment Questions
Write a Java program to implement a stack using the Stack class. The program should allow:
• Pushing 5 integer values onto the stack.
• Popping the top 2 values from the stack.
• Displaying the stack after each operation.
Write a Java program that demonstrates the use of Lambda Expressions to:
• Create a list of integers.
• Use the forEach method with a Lambda expression to print each element.
• Use a Lambda expression to filter and display only even numbers.
Write a Java program to copy the contents of one file to another using FileInputStream and
FileOutputStream (byte stream).
• Read data from source.txt and write it to destination.txt.
• Ensure proper exception handling.

PIMPRI CHINCHWAD UNIVERSITY


50

Assignment Questions
Write a Java program that reads a text file using FileReader and BufferedReader, counts the
number of lines, and displays the total count.
• Example: If data.txt has 10 lines, the program should output Total lines: 10.
Write a Java program using the File class to:
• Check if a file named example.txt exists.
• If it does not exist, create the file.
• Display the file's absolute path, size (in bytes), and whether it is readable/writable.
Write a GUI program using Swing to create a window with a button labeled "Click Me!".
• When the button is clicked, display a message "Button Clicked!" using an ActionListener.
Write a Java program using MouseListener to:
• Detect when the user clicks, enters, or exits a JFrame window.
• Display messages like "Mouse Clicked!", "Mouse Entered!", etc. in the console.

PIMPRI CHINCHWAD UNIVERSITY

You might also like