MATRUSRI ENGINEERING COLLEGE�DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
SUBJECT NAME: OOP USING JAVA
BE III SEM 2022-23
FACULTY NAME: A V MURALI KRISHNA
MATRUSRI
ENGINEERING COLLEGE
UNIT-3
MATRUSRI
ENGINEERING COLLEGE
Collections: Overview of Java Collection frame work, commonly used Collection classes – ArrayList, Linked List, Hash Set, Tree Set, Collection Interfaces – Collection, List, Set. Accessing Collection via iterator, working with Map. Legacy classes and interfaces – Vector, Hashtable, Stack,Dictionary, Enumeration interface.
Other Utility classes: String Tokenizer, Date, Calendar, Gregorian Calendar, ScannerJavaInput/Output:exploring java.io, Java I/O classes and interfaces, File, Stream classes, bytestream,character stream, serialization.
Syllabus
INTRODUCTION:��
PRELIMINARY CONCEPTS
MATRUSRI
ENGINEERING COLLEGE
OUTCOMES:
The important points about Java Collections class are: Java Collection class supports the polymorphic algorithms that operate on collections. Java Collection class throws a NullPointerException if the collections or class objects provided to them are null program library
Course Objective: To understand fundamentals of object-oriented programming in Java which includes defining classes, invoking methods, difference between applet and application programs, using class libraries.
Â
Develop the ability to solve real-world problems through software development in high-level programming language using Large APIs of Java as well as the Java standard class library.
CONTENTS:�1) Collections�2) Other utility classes���
OUTCOMES:
Create Java application programs using sound OOP practices e.g. Inheritance, interfaces and proper program structuring by using packages, access control specifiers
MODULE-I
MATRUSRI
ENGINEERING COLLEGE
commonly used Collection classes:
List of Collection Classes:
1) Array List
2) Linked List
3) Vector
4) Stack
5) Priority Queue
6) Array Deque
7) Hash Set
8) Tree Set
9) LinkedHashSet
10) SortedSetÂ
MATRUSRI
ENGINEERING COLLEGE
MATRUSRI
ENGINEERING COLLEGE
// Java program to demonstrate the
// working of ArrayList
import java.io.*;
import java.util.*;
class GFG {
// Main Method
public static void main(String[] args)
{ // Declaring the ArrayList with
// initial size n
ArrayList<Integer> al = new ArrayList<Integer>();
// Appending new elements at
// the end of the list
for (int i = 1; i <= 5; i++)
al.add(i);
// Printing elements
System.out.println(al);
// Remove element at index 3
al.remove(3);
// Displaying the ArrayList
// after deletion
System.out.println(al);
// Printing elements one by one
for (int i = 0; i < al.size(); i++)
System.out.print(al.get(i) + " ");
}}
MATRUSRI
ENGINEERING COLLEGE
COLLECTION INTERFACES
1. Collection interface
2. List interface
3. Set interface
4. SortedSet interface
5. Map interface
6. Map.Entry Interface
7. SortedMap interface
8. Queue interface
9. Deque interface
10. Enumeration interface
MATRUSRI
ENGINEERING COLLEGE
// Java program to Demonstrate Set Interface
import java.util.Set;
import java.util.HashSet;
class Main {
public static void main(String[] args) {
// Creating a set using the HashSet class
Set<Integer> set1 = new HashSet<>();
// Add elements to the set1
set1.add(2);
set1.add(3);
System.out.println("Set1: " + set1);
// Creating another set using the HashSet class
Set<Integer> set2 = new HashSet<>();
// Add elements
set2.add(1);
set2.add(2);
System.out.println("Set2: " + set2);
// Union of two sets
set2.addAll(set1);
System.out.println("Union is: " + set2);
}}
MATRUSRI
ENGINEERING COLLEGE
ACCESSING COLLECTION VIA ITERATOR
Java Iterator Interface of java collections allows us to access elements of the collection and is used to iterate over the elements in the collection(Map, List or Set). It helps to easily retrieve the elements of a collection and perform operations on each element. Iterator is a universal iterator as it can be applied to any Collection object. We can traverse only in the forward direction using iterator. Using ListIterator which extends Iterator, can traverse in both directions. Both read and remove operations can be performed by the iterator interface.
while (itr.hasNext()) {
// Returns the next element.
System.out.println(itr.next());
MATRUSRI
ENGINEERING COLLEGE
WORKING WITH MAP
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as
an entry. A Map contains unique keys.A Map is useful if you have to search, update or delete elements on the basis of a key. There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap, LinkedHashMap, and TreeMap.
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
1.11
LEGACY CLASSES AND INTERFACES
It only defined several classes and interfaces that provide methods for storing objects. When collections framework were added in J2SE 1.2, the original classes were reengineered to support the collection interface. These classes are also known as Legacy classes. All the legacy classes are synchronized. The java.util package defines the following legacy classes:
List of Legacy Classes:
MATRUSRI
ENGINEERING COLLEGE
MATRUSRI
ENGINEERING COLLEGE
import java.util.*;
public class VectorExample
{
public static void main(String[] args)
{ Vector<String> vec = new Vector<String>();
vec.add("Emma");
vec.add("Adele");
vec.add("Aria");
vec.add("Aidan");
vec.add("Adriana");
vec.add("Ally");
Enumeration<String> data = vec.elements();
while(data.hasMoreElements())
{ System.out.println(data.nextElement()); } }}
MATRUSRI
ENGINEERING COLLEGE
STRING TOKENIZER
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to break a String. It is a legacy class of Java. It doesn't provide the facility to differentiate numbers, quoted
strings, identifiers etc. In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens.
StringTokenizer st = new StringTokenizer("my name is Matrusri"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
MATRUSRI
ENGINEERING COLLEGE
DATE
The class Date represents a specific instant in time, with millisecond precision. The Date class of java.util package implements Serializable, Cloneable and Comparable interface. It provides constructors and methods to deal with date and time with java.
Constructors:
Date(int year, int month, int date)
Date(int year, int month, int date, int hrs, int min)
Date(int year, int month, int date, int hrs, int min, int sec)
Date(String s)
MATRUSRI
ENGINEERING COLLEGE
CALENDAR AND GREGORIAN CALENDAR
Calendar class in Java is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and implements the Comparable, Serializable, Cloneable interfaces.As it is an Abstract class, so we cannot use a constructor to create an instance. Instead, we will have to use the static method Calendar.getInstance() to instantiate and implement a sub-class.
Calendar.getInstance(): return a Calendar instance based on the current time in the default time zone
with the default locale.
Calendar.getInstance(TimeZone zone)
Calendar.getInstance(Locale aLocale)
Calendar.getInstance(TimeZone zone, Locale aLocale)
import java.util.*;
public class Calendar1 {
public static void main(String args[])
{ Calendar c = Calendar.getInstance();
System.out.println("The Current Date is:" + c.getTime());
}}
MATRUSRI
ENGINEERING COLLEGE
SCANNER JAVA INPUT/OUTPUT
Scanner is a class in java.util package used for obtaining the input of the primitive types like int,double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient. if you want an input method for scenarios where time is a constraint like in competitive programming. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file. To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort(). To read strings, we use nextLine(). To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
} }
MATRUSRI
ENGINEERING COLLEGE
EXPLORING JAVA.IO
Java programming language comes with a variety of APIs that helps the developers to code more efficiently. One of those APIs is Java IO API. Java IO API helps the users to read and write data. In simple words, we can say that the Java IO helps the users to take the input and produce output based on that input. Almost every application or code requires some input and output produced based on that input.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 operations fast. The java.io package contains all the classes required for input and output operations. We can perform file handling in Java by Java I/O API.
MATRUSRI
ENGINEERING COLLEGE
FILE
In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file.File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it. In simple words, file handling means reading and writing data to a file.
// Importing File Class
import java.io.File;
class GFG {
public static void main(String[] args)
{
// File name specified
File obj = new File("myfile.txt");
System.out.println("File Created!");
}}
MATRUSRI
ENGINEERING COLLEGE
STREAM CLASSES
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are A stream is not a data structure instead it takes input from the collections, Arrays or I/O channels. Streams don’t change the original data structure, they only provide the result as per the pipelined methods. Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
MATRUSRI
ENGINEERING COLLEGE
BYTE STREAM
ByteStream classes are used to read bytes from the input stream and write bytes to the output stream. In other words, we can say that Byte Stream classes read/write the data of 8-bits. We can store video,audio, characters, etc., by using ByteStream classes. These classes are part of the java.io package.
MATRUSRI
ENGINEERING COLLEGE
CHARACTER STREAM
The java.io package provides CharacterStream classes to overcome the limitations of ByteStream classes, which can only handle the 8-bit bytes and is not compatible to work directly with the Unicode characters. CharacterStream classes are used to work with 16-bit Unicode characters. They can perform operations on characters, char arrays and Strings.
MATRUSRI
ENGINEERING COLLEGE
SERIALIZATION
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This
mechanism is used to persist the object.The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform. To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.
Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.
END OF UNIT - III
23