Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

📦

JAVA MID
UNIT 3
1A. What are the methods in list iterator. Explain

The ListIterator interface of the Java collections framework


provides the functionality to access elements of a list. It
is bidirectional. This means it allows us to iterate elements
of a list in both the direction. It extends
the Iterator interface.

JAVA MID 1
The List interface provides a listIterator() method that returns
an instance of the ListIterator interface.

Methods of ListIterator:

The ListIterator interface provides methods that can be used to


perform various operations on the elements of a list.

hasNext() - returns true if there exists an element in the


list

next() - returns the next element of the list

nextIndex() returns the index of the element that


the next() method will return

previous() - returns the previous element of the list

previousIndex() - returns the index of the element that


the previous() method will return

- removes the element returned by


remove()

either next() or previous()

- replaces the element returned by


set()

either next() or previous() with the specified element

import java.util.ArrayList;
import java.util.ListIterator;

class Main {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(2);
System.out.println("ArrayList: " + numbers);

// Creating an instance of ListIterator


ListIterator<Integer> iterate = numbers.listIterator();
iterate.next();
iterate.next();

// Using the previous() method


int number1 = iterate.previous();
System.out.println("Previous Element: " + number1);

// Using the previousIndex()


int index1 = iterate.previousIndex();
System.out.println("Position of the Previous element: " + index1);

JAVA MID 2
}
}

Output

ArrayList: [1, 3, 2]
Next Element: 1
Position of Next Element: 1
Is there any next element? true

1B. How to break a string into tokens. Discuss

Java StringTokenizer is a legacy class that is defined in


java.util package. It allows us to split the string into
tokens. It is not used by the programmer because the split()
method of the String class does the same work. So, the
programmer prefers the split() method instead of the
StringTokenizer class. We use the following two methods of
the class:

StringTokenizer.hasMoreTokens()

The method iterates over the string and checks if there are
more tokens available in the tokenizer string. It returns
true if there is one token is available in the string after
the current position, else returns false. It internally calls
the nextToken() method if it returns true and the nextToken()
method returns the token.

Syntax:

public boolean hasMoreTokens()

StringTokenizer.nextToken()

It returns the next token from the string tokenizer. It


throws NoSuchElementException if the tokens are not available
in the string tokenizer.
Syntax:

JAVA MID 3
public String nextToken()

Example:

import java.util.StringTokenizer;

public class SplitStringExample6 {


public static void main(String[] args) {
// defining a String object
String str = "Welcome/to/Javatpoint";
// constructor of the StringTokenizer class
StringTokenizer tokens = new StringTokenizer(str, "/");
// checks if the string has more tokens or not
while (tokens.hasMoreTokens()) {
// prints the tokens
System.out.println(tokens.nextToken());
}
}
}

Output:

Welcome
to
Javatpoint

2A. What are the difference between for each and for loop

Java for-loop is a control flow statement that iterates a


part of the program multiple times. For-loop is the most
commonly used loop in java. If we know the number of
iteration in advance then for-loop is the best choice.

Syntax:

for( initializationsection ; conditional check ; increment/decrement section)


{
// Code to be executed
}

Curly braces in for loop is optional without


curly braces in for-loop we can take only one

JAVA MID 4
statement under for-loop which should not be a
declarative statement and if we write
declarative statement there then we will get
compile-time error.

Example

// Java Program to illustrate the use of


// for loop

// Importing all input output classes


import java.io.*;
// Importing all classes from
// java.util package
import java.util.*;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{

// 1st for-loop
// Iteration ocer 5 elements using for loop
for (int i = 1; i <= 5; i++) {

// Print statement
System.out.println("GFG!");
}

// 2nd for-loop
// Declaring and initialization a variable
// so we will get compile time error
for (int i = 1; i <= 1; i++)
int x = 0;
}
}

Output:

Case 1: Absence of second for-loop

GFG
GFG
GFG
GFG
GFG

JAVA MID 5
Case 2: Presence of second for-loop

prog.java:28: error: variable declaration not allowed here


int x=0;
^
1 error

Output explanation:

In the Initialization section, This part will be executed


only once in the loop life cycle. Here we can declare and
initialize a local variable for loop. Here we can declare
any number of variables but should have the same type by
mistake if we are trying to declare a different data type
then we will get a compile–time error. In this section, we
can take any valid java statement including
‘System.out.println()’.

During the condition check, we can take any valid java


expression that should be of type boolean. This part is
optional and if we are not taking anything
then the compiler will always place a true value here.

In the Increment/Decrement section, we can either


increment or decrement we can the initialized value. In
this section we can take any valid java statement
including ‘System.out.println()’ and this section is also
optional.

Enhanced for loop(for-each loop)

This for-loop was introduced in java version 1.5 and it is


also a control flow statement that iterates a part of the
program multiple times. This for-loop provides another way
for traversing the array or collections and hence it is
mainly used for traversing array or collections. This loop
also makes the code more readable and reduces the chance of
bugs in the code.

Syntax:

for(data-type variable : array | collection)


{

JAVA MID 6
// Code to be executed
}

Example:

// Java Program to show usage of for-each loop

// Importing all classes from


// java.util package
// Importing all input output classes
import java.io.*;
import java.util.*;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Declaring and initializing the integer array


// Custom integer entries in an array
int[] array = { 1, 2, 3, 4, 5, 6 };

// Accessing the element of array


// using for-each loop
for (int a : array) {
// Print all elements of an array
System.out.println(a);
}
}
}

Output

1
2
3
4
5
6

Normal for-loop Enhanced for-loop

This for-loop is present This for loop is present


from JDK1 from JDK5

JAVA MID 7
Normal for-loop Enhanced for-loop

In a normal for-loop, we But enhanced for loop


can increase the counter as will execute in a
per our wish by using sequential manner i.e
i=i+x( where x is any counter will always
constant x=1,2,3…) increase by one.

We can only iterate on


Using this for loop we can
that container by using
iterate on any container
this loop to implement
object.
the iterable interface.

In this for-loop, we can But in this for-loop, we


iterate in both decrement can iterate only in
or increment order. increment order.

But in this for-loop, we


In this for-loop, we can don’t have access to the
replace elements at any index, so we cannot
specific index. replace elements at any
specific index.

But in the for-each


By using normal for-loop we
loop, we can print array
can print array elements
element only in the
either in the original
original order, not in
order or in reverse order.
reverse order
Example: Printing element Example: Printing
in a 1D array int[ ] x= element in a 1D array
{1,2,3}; for(int using for-each loop
i=0;i<x.length;i++) { int[ ] x={1,2,3};
System.out.println(x[i]); for(int a : x) {
} System.out.println(a); }

Example: Printing element


Example: Printing
in a 2D array using for
element in a 2D array
loop int[ ][ ] x={{1,2,3},
using for-each loop int[
{4,5,6}}; for(int
][ ] x={{1,2,3},{4,5,6}}
i=0;i<x.length;i++){
; for(int[ ] x1 :x){
for(int j=0;
for(int x2 : x1) {
j<x[i].length;j++){
System.out.println(x2);
System.out.println(x[i]
} }
[j]); } }

2B. How to traverse the elements of a list in forward


direction with iterator in java

JAVA MID 8
ArrayList is a part of the collection framework and is
present in java.util package. It provides us with dynamic
arrays in Java. The listIterator() method of
java.util.ArrayList class is used to return a list iterator
over the elements in this list (in a proper organized
sequence). ArrayList can be traversed in the forward
direction using multiple ways.
Example:

Input :ArrayList: [5, 6, 8, 10]


Output:
Value is : 5
Value is : 6
Value is : 8
Value is : 10

Using listIterator Method

1. Create a list iterator object of a given ArrayList.

2. Use while loop with the condition as hasNext() method.

3. If hasNext() method returns false, loop breaks.

4. Else print the value using object.next() method.

// Traverse through ArrayList in


// forward direction using Java
import java.util.*;
import java.io.*;

class GFG {
public static void main(String[] args)
{
ArrayList<Integer> alist = new ArrayList<>();

// adding element to arrlist


alist.add(5);
alist.add(6);
alist.add(8);
alist.add(10);

ListIterator<Integer> it = alist.listIterator();

while (it.hasNext()) {
System.out.println("Value is : " + it.next());
}

JAVA MID 9
}
}

Output

Value is : 5
Value is : 6
Value is : 8
Value is : 10

3A. Write a java program to implement map interface and set


interface
Map Interface

The map interface is present in java.util package represents


a mapping between a key and a value. The Map interface is not
a subtype of the Collection interface. Therefore it behaves a
bit differently from the rest of the collection types. A map
contains unique keys.

Maps are perfect to use for key-value association mapping


such as dictionaries. The maps are used to perform lookups by
keys or when someone wants to retrieve and update elements by
keys. Some common scenarios are as follows:

A map of error codes and their descriptions.

A map of zip codes and cities.

A map of managers and employees. Each manager (key) is


associated with a list of employees (value) he manages.

A map of classes and students. Each class (key) is


associated with a list of students (value).

JAVA MID 10
Creating Map Objects

Since Map is an interface, objects cannot be created of the


type map. We always need a class that extends this map in
order to create an object. And also, after the introduction
of Generics in Java 1.5, it is possible to restrict the type
of object that can be stored in the Map.

Syntax: Defining Type-safe Map

Map hm = new HashMap();


// Obj is the type of the object to be stored in Map

// Java Program to Demonstrate


// Working of Map interface

// Importing required classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an empty HashMap
Map<String, Integer> hm
= new HashMap<String, Integer>();

// Inserting pairs in above Map


// using put() method
hm.put("a", new Integer(100));
hm.put("b", new Integer(200));
hm.put("c", new Integer(300));
hm.put("d", new Integer(400));

JAVA MID 11
// Traversing through Map using for-each loop
for (Map.Entry<String, Integer> me :
hm.entrySet()) {

// Printing keys
System.out.print(me.getKey() + ":");
System.out.println(me.getValue());
}
}
}

a:100
b:200
c:300
d:400

Set interface

The set interface is present in java.util package and extends


the Collection interface is an unordered collection of
objects in which duplicate values cannot be stored. It is an
interface that implements the mathematical set. This
interface contains the methods inherited from the Collection
interface and adds a feature that restricts the insertion of
the duplicate elements. There are two interfaces that extend
the set implementation namely SortedSet and NavigableSet.

JAVA MID 12
// Java program Illustrating Set Interface

// Importing utility classes


import java.util.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Demonstrating Set using HashSet
// Declaring object of type String
Set<String> hash_Set = new HashSet<String>();

// Adding elements to the Set


// using add() method
hash_Set.add("Geeks");
hash_Set.add("For");
hash_Set.add("Geeks");
hash_Set.add("Example");
hash_Set.add("Set");

// Printing elements of HashSet object


System.out.println(hash_Set);
}
}

Output

JAVA MID 13
[Set, Example, Geeks, For]

3B. Collection hierarchy

Collections in Java
Any group of individual objects which are represented as a
single unit is known as the collection of the objects. In
Java, a separate framework named the “Collection
Framework” has been defined in JDK 1.2 which holds all the
collection classes and interface in it.

The Collection interface (java.util.Collection) and Map


interface (java.util.Map) are the two main “root” interfaces
of Java collection classes.

A framework is a set of classes and interfaces which provide


a ready-made architecture. In order to implement a new
feature or a class, there is no need to define a framework.
However, an optimal object-oriented design always includes a
framework with a collection of classes such that all the
classes perform the same kind of task.

// Java program to demonstrate


// why collection framework was needed
import java.io.*;
import java.util.*;

class CollectionDemo {

public static void main(String[] args)


{
// Creating instances of the array,
// vector and hashtable
int arr[] = new int[] { 1, 2, 3, 4 };
Vector<Integer> v = new Vector();
Hashtable<Integer, String> h = new Hashtable();

// Adding the elements into the


// vector
v.addElement(1);
v.addElement(2);

JAVA MID 14
// Adding the element into the
// hashtable
h.put(1, "geeks");
h.put(2, "4geeks");

// Array instance creation requires [],


// while Vector and hastable require ()
// Vector element insertion requires addElement(),
// but hashtable element insertion requires put()

// Accessing the first element of the


// array, vector and hashtable
System.out.println(arr[0]);
System.out.println(v.elementAt(0));
System.out.println(h.get(1));

// Array elements are accessed using [],


// vector elements using elementAt()
// and hashtable elements using get()
}
}

Output:

1
1
geeks

As we can observe, none of these collections(Array, Vector,


or Hashtable) implements a standard member access interface,
it was very difficult for programmers to write algorithms
that can work for all kinds of Collections. Another drawback
is that most of the ‘Vector’ methods are final, meaning we
cannot extend the ’Vector’ class to implement a similar kind
of Collection. Therefore, Java developers decided to come up
with a common interface to deal with the above-mentioned
problems and introduced the Collection Framework in JDK 1.2
post which both, legacy Vectors and Hashtables were modified
to conform to the Collection Framework.
Advantages of the Collection Framework: Since the lack of a
collection framework gave rise to the above set of
disadvantages, the following are the advantages of the
collection framework.

JAVA MID 15
1. Consistent API: The API has a basic set
of interfaces like Collection, Set, List, or Map, all the
classes (ArrayList, LinkedList, Vector, etc) that
implement these interfaces have some common set of
methods.

2. Reduces programming effort: A programmer doesn’t have to


worry about the design of the Collection but rather he
can focus on its best use in his program. Therefore, the
basic concept of Object-oriented programming (i.e.)
abstraction has been successfully implemented.

3. Increases program speed and quality: Increases performance


by providing high-performance implementations of useful
data structures and algorithms because in this case, the
programmer need not think of the best implementation of a
specific data structure. He can simply use the best
implementation to drastically boost the performance of
his algorithm/program.

Hierarchy of the Collection


Framework
The utility package, (java.util) contains all the classes and
interfaces that are required by the collection framework. The
collection framework contains an interface named an iterable
interface which provides the iterator to iterate through all
the collections. This interface is extended by the main
collection interface which acts as a root for the collection
framework. All the collections extend this collection
interface thereby extending the properties of the iterator
and the methods of this interface. The following figure
illustrates the hierarchy of the collection framework.

JAVA MID 16
Before understanding the different components in the above
framework, let’s first understand a class and an interface.

Class: A class is a user-defined blueprint or prototype


from which objects are created. It represents the set of
properties or methods that are common to all objects of
one type.

Interface: Like a class, an interface can have methods and


variables, but the methods declared in an interface are by
default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is
the blueprint of the class.

Methods of the Collection Interface


This interface contains various methods which can be directly
used by all the collections which implement this interface.

Method Description

This method is used to add an object to the


add(Object)
collection.

This method adds all the elements in the


addAll(Collection c)
given collection to this collection.

This method removes all of the elements from


clear()
this collection.
This method returns true if the collection
contains(Object o)
contains the specified element.

JAVA MID 17
Method Description

This method returns true if the collection


containsAll(Collection
contains all of the elements in the given
c)
collection.

This method compares the specified object


equals(Object o)
with this collection for equality.
This method is used to return the hash code
hashCode()
value for this collection.

This method returns true if this collection


isEmpty()
contains no elements.

This method returns an iterator over the


iterator()
elements in this collection.

This method is used to return the maximum


max()
value present in the collection.

This method returns a parallel Stream with


parallelStream()
this collection as its source.
This method is used to remove the given
object from the collection. If there are
remove(Object o)
duplicate values, then this method removes
the first occurrence of the object.
This method is used to remove all the
removeAll(Collection
objects mentioned in the given collection
c)
from the collection.

This method is used to remove all the


removeIf(Predicate
elements of this collection that satisfy the
filter)
given predicate.

This method is used to retain only the


retainAll(Collection
elements in this collection that are
c)
contained in the specified collection.

This method is used to return the number of


size()
elements in the collection.

This method is used to create


spliterator() a Spliterator over the elements in this
collection.

This method is used to return a sequential


stream()
Stream with this collection as its source.

This method is used to return an array


toArray() containing all of the elements in this
collection.

JAVA MID 18
UNIT 4
1A. serialization
Serialization in Java is a mechanism of writing the state of
an object into a byte-stream. It is mainly used in Hibernate,
RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is
called deserialization where byte-stream is converted into an
object. The serialization and deserialization process is
platform-independent, it means you can serialize an object on
one platform and deserialize it on a different platform.
For serializing the object, we call the writeObject() method
of ObjectOutputStream class, and for deserialization we call
the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for
serializing the object.

Advantages of Java Serialization


It is mainly used to travel object's state on the network
(that is known as marshalling).

java.io.Serializable interface
Serializable is a marker interface (has no data member and
method). It is used to "mark" Java classes so that the

JAVA MID 19
objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.
The Serializable interface must be implemented by the class
whose object needs to be persisted.
The String class and all the wrapper classes implement
the java.io.Serializable interface by default.

import java.io.Serializable;

public class Student implements Serializable {


int id;
String name;

public Student(int id, String name) {


this.id = id;
this.name = name;
}
}

In the above example, Student class implements Serializable


interface.

ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data
types, and Java objects to an OutputStream. Only objects that
support the java.io.Serializable interface can be written to
streams.
Constructor
public ObjectInputStream(InputStream in) throws IOException {}

It creates an ObjectInputStream that reads from the specified


InputStream.

Important Methods

Method Description

1) public final void


It writes the specified object to
writeObject(Object obj) throws
the ObjectOutputStream.
IOException {}

2) public void flush() throws It flushes the current output


IOException {} stream.

JAVA MID 20
Method Description

3) public void close() throws It closes the current output


IOException {} stream.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data


written using an ObjectOutputStream.
Constructor

Important Methods

Method Description

1) public final Object readObject()


It reads an object from the
throws IOException,
input stream.
ClassNotFoundException{}

2) public void close() throws


It closes ObjectInputStream.
IOException {}

Example of Java Serialization


In this example, we are going to serialize the object
of Student class from above code. The writeObject() method of
ObjectOutputStream class provides the functionality to
serialize the object. We are saving the state of the object
in the file named f.txt.
Persist.java

import java.io.*;

class Persist {
public static void main(String args[]) {
try {
// Creating the object
Student s1 = new Student(211, "ravi");
// Creating stream and writing the object
FileOutputStream fout = new FileOutputStream("f.txt");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
// closing the stream
out.close();
System.out.println("success");
} catch (Exception e) {
System.out.println(e);
}
}
}

JAVA MID 21
Output:
success

1B. deserialization
Deserialization is the process of reconstructing the object
from the serialized state. It is the reverse operation of
serialization. Let's see an example where we are reading the
data from a deserialized object.
Deserialization is the process of reconstructing the object
from the serialized state. It is the reverse operation of
serialization. Let's see an example where we are reading the
data from a deserialized object.
Depersist.java

import java.io.*;

class Depersist {
public static void main(String args[]) {
try {
// Creating stream to read the object
ObjectInputStream in = new ObjectInputStream(new FileInputStream("f.txt"));
Student s = (Student) in.readObject();
// printing the data of the serialized object
System.out.println(s.id + " " + s.name);
// closing the stream
in.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Output:

211 ravi

2A. Exception and different types of exception (14M)


Exception Handling in Java is one of the effective means to
handle the runtime errors so that the regular flow of the
application can be preserved. Java Exception Handling is a

JAVA MID 22
mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Exception is an unwanted or unexpected event, which occurs
during the execution of a program, i.e. at run time, that
disrupts the normal flow of the program’s instructions.
Exceptions can be caught and handled by the program. When an
exception occurs within a method, it creates an object. This
object is called the exception object. It contains
information about the exception, such as the name and
description of the exception and the state of the program
when the exception occurred.
Major reasons why an exception Occurs

Invalid user input

Device failure

Loss of network connection

Physical limitations (out of disk memory)

Code errors

Opening an unavailable file

Errors represent irrecoverable conditions such as Java


virtual machine (JVM) running out of memory, memory leaks,
stack overflow errors, library incompatibility, infinite
recursion, etc. Errors are usually beyond the control of the
programmer, and we should not try to handle errors.
Let us discuss the most important part which is
the differences between Error and Exception that is as
follows:

Error: An Error indicates a serious problem that a


reasonable application should not try to catch.

Exception: Exception indicates conditions that a


reasonable application might try to catch.

Exception Hierarchy

All exception and error types are subclasses of


class Throwable, which is the base class of the hierarchy.

JAVA MID 23
One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time
system(JVM) to indicate errors having to do with the run-time
environment itself(JRE). StackOverflowError is an example of
such an error.

Types of Exceptions
Exceptions can be categorized in two ways:

1. Built-in Exceptions

Checked Exception

Unchecked Exception

2. User-Defined Exceptions

1. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in
Java libraries. These exceptions are suitable to explain
certain error situations.

Checked Exceptions: Checked exceptions are called compile-


time exceptions because these exceptions are checked at
compile-time by the compiler.

Unchecked Exceptions: The unchecked exceptions are just


opposite to the checked exceptions. The compiler will not
check these exceptions at compile time. In simple words,
if a program throws an unchecked exception, and even if we
didn’t handle or declare it, the program would not give a
compilation error.

Note: For checked vs unchecked exception,


see Checked vs Unchecked Exceptions

B. User-Defined Exceptions:

JAVA MID 24
Sometimes, the built-in exceptions in Java are not able to
describe a certain situation. In such cases, users can also
create exceptions, which are called ‘user-defined
Exceptions’.
The advantages of Exception Handling in Java are as follows:

1. Provision to Complete Program Execution

2. Easy Identification of Program Code and Error-Handling


Code

3. Propagation of Errors

4. Meaningful Error Reporting

5. Identifying Error Types

Java Exception Keywords


Java provides five keywords that are used to handle the
exception. The following table describes each.

Keyword Description

The "try" keyword is used to specify a block where we


should place an exception code. It means we can't use
try
try block alone. The try block must be followed by
either catch or finally.

The "catch" block is used to handle the exception. It


must be preceded by try block which means we can't use
catch
catch block alone. It can be followed by finally block
later.

The "finally" block is used to execute the necessary


finally code of the program. It is executed whether an
exception is handled or not.

throw The "throw" keyword is used to throw an exception.

The "throws" keyword is used to declare exceptions. It


specifies that there may occur an exception in the
throws
method. It doesn't throw an exception. It is always
used with method signature.

JAVA MID 25
3A. How do you propagate unchecked exception in Java

3B. compare and contrast between class not found and no class
definition found error

4. no class definition error

5. develop a multiple catch clause classes in Java

6. explain the terms try, catch, finally and implement the


program

JAVA MID 26

You might also like