Java Mid
Java Mid
JAVA MID
UNIT 3
1A. What are the methods in list iterator. Explain
JAVA MID 1
The List interface provides a listIterator() method that returns
an instance of the ListIterator interface.
Methods of ListIterator:
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);
JAVA MID 2
}
}
Output
ArrayList: [1, 3, 2]
Next Element: 1
Position of Next Element: 1
Is there any next element? true
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:
StringTokenizer.nextToken()
JAVA MID 3
public String nextToken()
Example:
import java.util.StringTokenizer;
Output:
Welcome
to
Javatpoint
2A. What are the difference between for each and for loop
Syntax:
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
// Class
class GFG {
// 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:
GFG
GFG
GFG
GFG
GFG
JAVA MID 5
Case 2: Presence of second for-loop
Output explanation:
Syntax:
JAVA MID 6
// Code to be executed
}
Example:
// Class
class GFG {
Output
1
2
3
4
5
6
JAVA MID 7
Normal for-loop Enhanced for-loop
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:
class GFG {
public static void main(String[] args)
{
ArrayList<Integer> alist = new ArrayList<>();
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
JAVA MID 10
Creating Map Objects
// Main class
class GFG {
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
JAVA MID 12
// Java program Illustrating Set Interface
// Main class
public class GFG {
Output
JAVA MID 13
[Set, Example, Geeks, For]
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.
class CollectionDemo {
JAVA MID 14
// Adding the element into the
// hashtable
h.put(1, "geeks");
h.put(2, "4geeks");
Output:
1
1
geeks
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.
JAVA MID 16
Before understanding the different components in the above
framework, let’s first understand a class and an interface.
Method Description
JAVA MID 17
Method Description
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.
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;
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 {}
Important Methods
Method Description
JAVA MID 20
Method Description
ObjectInputStream class
Important Methods
Method Description
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
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
Device failure
Code errors
Exception 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.
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:
3. Propagation of Errors
Keyword Description
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
JAVA MID 26