0% found this document useful (0 votes)
4 views44 pages

Unit 4 Java Question Bank

The document contains a Java Unit 4 question bank with very short answer type questions and short answer type questions related to file handling in Java. It includes code snippets, explanations of classes like File, BufferedReader, FileWriter, and comparisons between different input/output streams. The document aims to assess understanding and practical skills in file operations using Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views44 pages

Unit 4 Java Question Bank

The document contains a Java Unit 4 question bank with very short answer type questions and short answer type questions related to file handling in Java. It includes code snippets, explanations of classes like File, BufferedReader, FileWriter, and comparisons between different input/output streams. The document aims to assess understanding and practical skills in file operations using Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Unit 4 Question bank

Very Short Answer type Questions carying 1 Marks


1. What will be the output of the following code?

File file = new File("[Link]");


[Link]([Link]());
Ans. false

2. Error finding: What is wrong with the following code?

BufferedReader br = new BufferedReader(new FileReader("[Link]"));


String line = [Link]();
[Link]();

Ans. Missing exception handling (e.g., IOException)

3. What will be the output of the following code?

File file = new File("[Link]");


[Link]([Link]());

Ans. true or false (depending on file permissions)

4. output of the following code?

File file = new File("[Link]");


[Link]([Link]());

Ans. true or false (depending on file permissions)

5. Error finding: What is wrong with the following code?

FileWriter fw = new FileWriter("[Link]");


[Link]("Hello, World!");

Ans. Missing close() method to close the FileWriter

6. What will be the output of the following code?

File file = new File("[Link]");


[Link]([Link]());
Ans. [Link]

Page 10 of 49
7. What will be the output of the following code?

List<String> list = new ArrayList<>();


[Link]("A");
[Link]("B");
[Link]([Link]());

Ans. 2

8. What will be the output of the following code?

Set<String> set = new HashSet<>();


[Link]("A");
[Link]("B");
[Link]("A");
[Link]([Link]());

Ans. 2

9. What will be the output of the following code?

Map<String, Integer> map = new HashMap<>();


[Link]("A", 1);
[Link]("B", 2);
[Link]([Link]("A"));

Ans. 1

10. What will be the output of the following code?

List<String> list = new LinkedList<>();


[Link]("A");
[Link]("B");
for (String s : list) {
[Link](s + " ");
}

Ans. A B

11. What will be the output of the following code?

List<Integer> list = new ArrayList<>();


[Link](1);
[Link](2);
[Link](3);
[Link](list, [Link]());
Page 10 of 49
[Link](list);

Ans. [3, 2, 1]

12. What will be the output of the following code?

Set<String> set = new TreeSet<>();


[Link]("B");
[Link]("A");
[Link]("C");
[Link](set);

Ans. [A, B, C]

13. What will be the output of the following code?

List<Integer> list = [Link](1, 2, 3, 4, 5);


[Link]([Link](3));

Ans. true

14. What will be the output of the following code?

List<String> list = new ArrayList<>();


[Link]("X");
[Link]("Y");
[Link]("Z");
[Link](list);
[Link](list);
Ans. [X, Y, Z]

15. What will be the output of the following code?

List<Integer> list = new LinkedList<>();


[Link](5);
[Link](10);
[Link](15);
[Link]([Link](1));
Ans. 10

16. What will be the output of the following code?


Set<String> set = new HashSet<>();
[Link]("D");
[Link]("E");
[Link]("D");
[Link]([Link]());

Ans. 2
Page 10 of 49
17. What will be the output of the following code?

List<String> list = new ArrayList<>();


[Link]("Java");
[Link]("Python");
[Link]("C++");
[Link]([Link]("Python"));

Ans. 1

Page 10 of 49
Short Answer Type Questions carying 5 Marks
1. Describe the purpose and usage of the File class in Java.

Ans. The File class in Java is used to represent file and directory pathnames. It
provides methods to create, delete, and query information about files and direc-
tories. The File class does not represent the contents of a file, only its name
and directory path. Key methods include:

• exists(): Checks if the file or directory exists.


• isDirectory(): Checks if the path is a directory.
• isFile(): Checks if the path is a file.
• mkdir(): Creates a new directory.
• delete(): Deletes the file or directory.
• length(): Returns the length of the file in bytes.

Example usage:

File file = new File("[Link]");


if ([Link]()) {
[Link]("File exists");
} else {
[Link]("File does not exist");
}

2. Explain how to read data from a file using BufferedReader in Java.

Ans. The BufferedReader class in Java is used to read text from an input stream, buffer-
ing characters for efficient reading. It provides methods like readLine() to read
data line by line. Here’s an example:

import [Link];
import [Link];
import [Link];

public class ReadFileExample {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}

Page 10 of 49
}
}

This code reads each line from the file [Link] and prints it to the console.

3. Write a code snippet to write data to a file using FileWriter in Java.

Ans. The FileWriter class in Java is used to write character data to a file. It can write
individual characters, arrays, or strings. Here’s an example:

import [Link];
import [Link];

public class WriteFileExample {


public static void main(String[] args) {
try (FileWriter writer = new FileWriter("[Link]")) {
[Link]("Hello, World!");
} catch (IOException e) {
[Link]();
}
}
}

This code creates or overwrites the file [Link] with the text ”Hello, World!”.

4. Compare and contrast FileInputStream and FileReader in Java.

Ans. FileInputStream and FileReader are both used to read data from files in Java, but
they have different purposes and handle data differently.

• FileInputStream: This class is used to read raw byte streams from a file.
It is suitable for reading binary data such as image or audio files. Methods
include read(), read(byte[] b), and available().
• FileReader: This class is used to read character streams from a file. It is
suitable for reading text data. Methods include read(), read(char[] cbuf),
and readLine().

Example usage:

// Using FileInputStream
try (FileInputStream fis = new FileInputStream("[Link]")) {
int data;
while ((data = [Link]()) != -1) {
[Link]((char) data);
}
} catch (IOException e) {

Page 11 of 44
[Link]();
}

// Using FileReader
try (FileReader fr = new FileReader("[Link]")) {
int data;
while ((data = [Link]()) != -1) {
[Link]((char) data);
}
} catch (IOException e) {
[Link]();
}

5. Discuss the advantages of using BufferedWriter over FileWriter for writing text
to a file in Java.

Ans. BufferedWriter is a subclass of Writer that buffers characters to provide efficient


writing of text to a file. It offers several advantages over FileWriter:

• Performance: BufferedWriter reduces the number of I/O operations by


buffering the characters, which improves performance when writing large
amounts of text.
• Efficient Line Writing: It provides the newLine() method, which makes it
easier to write platform-independent newline characters.
• Reduced System Calls: By buffering the characters, it minimizes the num-
ber of system calls, which can be costly in terms of performance.

Example usage:

import [Link];
import [Link];
import [Link];

public class BufferedWriterExample {


public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"))) {
[Link]("Hello, World!");
[Link]();
[Link]("BufferedWriter is efficient.");
} catch (IOException e) {
[Link]();
}
}
}

Page 12 of 44
6. Write a code snippet to copy the contents of one file to another using FileInputStream
and FileOutputStream in Java.

Ans. The FileInputStream and FileOutputStream classes are used for reading and writ-
ing binary data. Here’s an example to copy the contents of one file to another:

import [Link];
import [Link];
import [Link];

public class FileCopyExample {


public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("[Link]");
FileOutputStream fos = new FileOutputStream("[Link]")) {
byte[] buffer = new byte[1024];
int length;
while ((length = [Link](buffer)) > 0) {
[Link](buffer, 0, length);
}
} catch (IOException e) {
[Link]();
}
}
}

This code reads data from [Link] and writes it to [Link] in chunks
of 1024 bytes.

7. Explain the concept of Random Access in files and its usage in Java.

Ans. Random access in files allows reading from and writing to any part of a file rather
than sequentially from the beginning to the end. This is useful for applications
like databases where records may need to be updated in place. In Java, the
RandomAccessFile class supports random access. Key methods include:

• seek(long pos): Moves the file pointer to the specified position.


• read(): Reads a byte of data from the file.
• write(int b): Writes a byte of data to the file.
• readFully(byte[] b): Reads bytes from the file into the specified byte array.
• writeBytes(String s): Writes a string as a sequence of bytes.

Example usage:

import [Link];
import [Link];

Page 13 of 44
public class RandomAccessFileExample {
public static void main(String[] args) {
try (RandomAccessFile raf = new RandomAccessFile("[Link]", "rw")) {
// Move the file pointer to position 10
[Link](10);
// Write data at position 10
[Link]("Hello, Random Access!");
// Move the file pointer to the beginning
[Link](0);
// Read data from the file
byte[] buffer = new byte[20];
[Link](buffer);
[Link](new String(buffer));
} catch (IOException e) {
[Link]();
}
}
}

8. Describe how to set file permissions in Java using the File class.

Ans. The File class in Java provides methods to set file permissions such as read,
write, and execute. These methods include:

• setReadable(boolean readable): Sets the read permission.


• setWritable(boolean writable): Sets the write permission.
• setExecutable(boolean executable): Sets the execute permission.

Example usage:

import [Link];

public class FilePermissionExample {


public static void main(String[] args) {
File file = new File("[Link]");
// Set read, write, and execute permissions
[Link](true);
[Link](true);
[Link](false);
[Link]("Read permission: " + [Link]());
[Link]("Write permission: " + [Link]());
[Link]("Execute permission: " + [Link]());
}
}

Page 14 of 44
9. Write a code snippet to list all files and directories in a specified directory in Java.

Ans. The File class in Java provides methods to list all files and directories in a spec-
ified directory. Here’s an example:

import [Link];

public class ListFilesExample {


public static void main(String[] args) {
File directory = new File("exampleDirectory");
if ([Link]()) {
File[] files = [Link]();
if (files != null) {
for (File file : files) {
[Link]([Link]());
}
}
}
}
}

This code lists all files and directories in the exampleDirectory directory.

10. Explain the difference between BufferedInputStream and FileInputStream in Java.

Ans. BufferedInputStream and FileInputStream are both used to read data from files,
but they differ in their handling of data:

• FileInputStream: This class reads raw bytes from a file one byte at a time,
which can be inefficient for large files due to frequent I/O operations.
• BufferedInputStream: This class wraps a FileInputStream and buffers the
input data, reducing the number of I/O operations by reading larger chunks
of data at once. It provides faster performance for reading large files.

Example usage:

// Using FileInputStream
try (FileInputStream fis = new FileInputStream("[Link]")) {
int data;
while ((data = [Link]()) != -1) {
[Link]((char) data);
}
} catch (IOException e) {
[Link]();
}

Page 15 of 44
// Using BufferedInputStream
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("example.t
int data;
while ((data = [Link]()) != -1) {
[Link]((char) data);
}
} catch (IOException e) {
[Link]();
}

11. Discuss the advantages and disadvantages of using character streams versus
byte streams in Java.

Ans. Character streams and byte streams are used to handle I/O operations in Java.
Each has its own advantages and disadvantages:

• Character Streams:
– Advantages:
* Designed for handling character data (text).
Automatically handles character encoding and decoding.
* Suitable for reading and writing text files.
*
– Disadvantages:
* Less efficient for binary data such as images or audio files.
• Byte Streams:
– Advantages:
* Designed
Suitable
for handling binary data.
for reading and writing binary files.
* More efficient for non-text data.
*
– Disadvantages:
* Does not automatically handle character encoding and decoding.
* Requires additional processing for text data.
12. Write a code snippet to read data from a file and display its contents on the
console using BufferedReader and FileReader.

Ans. The BufferedReader and FileReader classes are used to read text data from a file
efficiently. Here’s an example:

import [Link];
import [Link];
import [Link];

public class BufferedReaderExample {


public static void main(String[] args) {

Page 16 of 44
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}

This code reads each line from the file [Link] and prints it to the console.

13. Explain how to create a new directory in Java using the File class.

Ans. The File class in Java provides methods to create new directories. The mkdir()
method creates a single directory, while the mkdirs() method creates the direc-
tory and any necessary but nonexistent parent directories. Example usage:

import [Link];

public class CreateDirectoryExample {


public static void main(String[] args) {
File directory = new File("newDirectory");
if ([Link]()) {
[Link]("Directory created successfully");
} else {
[Link]("Failed to create directory");
}

File nestedDirectory = new File("parentDirectory/childDirectory");


if ([Link]()) {
[Link]("Nested directories created successfully");
} else {
[Link]("Failed to create nested directories");
}
}
}

This code demonstrates creating a single directory and nested directories.

14. What are the key methods provided by the FileInputStream class in Java?

Ans. The FileInputStream class in Java provides several key methods for reading data
from files:

Page 17 of 44
• read(): Reads a single byte of data from the input stream.
• read(byte[] b): Reads bytes from the input stream into the specified byte
array.
• read(byte[] b, int off, int len): Reads up to len bytes from the input
stream into the specified byte array, starting at the specified offset.
• available(): Returns an estimate of the number of bytes that can be read
from the input stream without blocking.
• close(): Closes the input stream and releases any system resources asso-
ciated with it.

Example usage:

import [Link];
import [Link];

public class FileInputStreamExample {


public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("[Link]")) {
int data;
while ((data = [Link]()) != -1) {
[Link]((char) data);
}
} catch (IOException e) {
[Link]();
}
}
}

15. Write a code snippet to append data to an existing file using FileWriter in Java.

Ans. The FileWriter class in Java can be used to append data to an existing file by
specifying the true flag in its constructor. Here’s an example:

import [Link];
import [Link];

public class AppendFileExample {


public static void main(String[] args) {
try (FileWriter writer = new FileWriter("[Link]", true)) {
[Link]("\nAppended text.");
} catch (IOException e) {
[Link]();
}
}

Page 18 of 44
}

This code appends the text ”


nAppended text.” to the file [Link].

16. Explain the use of BufferedOutputStream in Java and how it differs from FileOutputStream.

Ans. BufferedOutputStream is a subclass of OutputStream that buffers the data before


writing it to the output stream, reducing the number of I/O operations and im-
proving performance. It wraps a FileOutputStream to provide buffering. Key
differences between BufferedOutputStream and FileOutputStream:

• FileOutputStream: Writes raw bytes to a file one byte at a time, which can
be inefficient for large files due to frequent I/O operations.
• BufferedOutputStream: Buffers data and writes it to the file in larger
chunks, reducing the number of I/O operations and improving performance.

Example usage:

// Using FileOutputStream
try (FileOutputStream fos = new FileOutputStream("[Link]")) {
[Link]("Hello, World!".getBytes());
} catch (IOException e) {
[Link]();
}

// Using BufferedOutputStream
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("exampl
[Link]("Hello, Buffered World!".getBytes());
} catch (IOException e) {
[Link]();
}

17. Discuss the benefits and limitations of using RandomAccessFile in Java.

Ans. RandomAccessFile allows reading from and writing to any part of a file, making it
useful for applications like databases and file systems. Key benefits and limita-
tions include:

• Benefits:
– Supports both reading and writing.
– Allows random access to file contents, enabling efficient updates.
– Provides methods to read and write various data types (e.g., readInt(),
writeDouble()).
• Limitations:

Page 19 of 44
– Not suitable for all file operations (e.g., appending data).
– Does not support buffering, which may lead to performance issues for
large files.
– Platform-dependent behavior for file locking.

Example usage:

import [Link];
import [Link];

public class RandomAccessFileExample {


public static void main(String[] args) {
try (RandomAccessFile raf = new RandomAccessFile("[Link]", "rw")) {
// Write data at position 10
[Link](10);
[Link]("Hello, Random Access!");
// Read data from the beginning
[Link](0);
byte[] buffer = new byte[20];
[Link](buffer);
[Link](new String(buffer));
} catch (IOException e) {
[Link]();
}
}
}

18. Write a code snippet to navigate through directories and print all files with a
specific extension using the File class in Java.

Ans. The File class in Java provides methods to navigate through directories and
filter files based on their extensions. Here’s an example to list all .txt files in a
directory:

import [Link];

public class ListFilesWithExtension {


public static void main(String[] args) {
File directory = new File("exampleDirectory");
if ([Link]()) {
File[] files = [Link]((dir, name) -> [Link](".txt"));
if (files != null) {
for (File file : files) {
[Link]([Link]());
}

Page 20 of 49
}
}
}
}

This code lists all .txt files in the exampleDirectory directory.

19. Describe the process of reading and writing properties using the Properties class
in Java.

Ans. The Properties class in Java is a subclass of Hashtable that is used to maintain
lists of values in which the key and value are both strings. It is often used for
configuration and resource bundles. Key methods include:

• load(InputStream inStream): Loads properties from an input stream.


• store(OutputStream out, String comments): Writes properties to an output
stream.
• getProperty(String key): Retrieves the value associated with the specified
key.
• setProperty(String key, String value): Sets the property with the specified
key and value.

Example usage:

import [Link];
import [Link];
import [Link];
import [Link];

public class PropertiesExample {


public static void main(String[] args) {
Properties properties = new Properties();
// Load properties from a file
try (FileInputStream in = new FileInputStream("[Link]")) {
[Link](in);
} catch (IOException e) {
[Link]();
}
// Print a property
[Link]("username: " + [Link]("username"));
// Set a new property
[Link]("password", "secret");
// Store properties to a file
try (FileOutputStream out = new FileOutputStream("[Link]")) {
[Link](out, "Configuration Settings");

Page 21 of 44
} catch (IOException e) {
[Link]();
}
}
}

20. What are the key methods provided by the FileOutputStream class in Java?

Ans. The FileOutputStream class in Java provides several key methods for writing data
to files:

• write(int b): Writes the specified byte to the output stream.


• write(byte[] b): Writes [Link] bytes from the specified byte array to the
output stream.
• write(byte[] b, int off, int len): Writes len bytes from the specified byte
array, starting at the specified offset.
• close(): Closes the output stream and releases any system resources asso-
ciated with it.
• flush(): Flushes the output stream and forces any buffered output bytes to
be written out.

Example usage:

import [Link];
import [Link];

public class FileOutputStreamExample {


public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("[Link]")) {
[Link]("Hello, World!".getBytes());
} catch (IOException e) {
[Link]();
}
}
}

21. Describe the purpose and usage of the ArrayList class in Java.

Ans. The ArrayList class in Java is part of the [Link] package and implements the
List interface. It provides a resizable array that can grow and shrink as needed.
The ArrayList class allows duplicate elements and maintains insertion order. Key
methods include:

• add(E e): Appends the specified element to the end of the list.

Page 22 of 44
• get(int index): Returns the element at the specified position in the list.
• remove(int index): Removes the element at the specified position in the list.
• size(): Returns the number of elements in the list.
• clear(): Removes all elements from the list.

Example usage:

import [Link];

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("List: " + list);
[Link]("Element at index 1: " + [Link](1));
[Link](1);
[Link]("List after removal: " + list);
[Link]("Size of the list: " + [Link]());
}
}

22. Explain how to create a HashSet and add elements to it in Java.

Ans. The HashSet class in Java is part of the [Link] package and implements the
Set interface. It uses a hash table for storage, ensuring that elements are unique
and not in any particular order. Key methods include:

• add(E e): Adds the specified element to the set if it is not already present.
• remove(Object o): Removes the specified element from the set if it is present.
• contains(Object o): Returns true if the set contains the specified element.
• size(): Returns the number of elements in the set.
• clear(): Removes all elements from the set.

Example usage:

import [Link];

public class HashSetExample {


public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
[Link]("A");
[Link]("B");

Page 23 of 44
[Link]("C");
[Link]("Set: " + set);
[Link]("Contains 'B': " + [Link]("B"));
[Link]("B");
[Link]("Set after removal: " + set);
[Link]("Size of the set: " + [Link]());
}
}

23. Write a code snippet to create a PriorityQueue and add elements to it in Java.

Ans. The PriorityQueue class in Java is part of the [Link] package and implements
the Queue interface. It orders elements according to their natural ordering or by
a specified comparator. Key methods include:

• add(E e): Inserts the specified element into the priority queue.
• peek(): Retrieves, but does not remove, the head of the queue.
• poll(): Retrieves and removes the head of the queue.
• size(): Returns the number of elements in the queue.
• clear(): Removes all elements from the queue.

Example usage:

import [Link];

public class PriorityQueueExample {


public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](10);
[Link](20);
[Link](15);
[Link]("PriorityQueue: " + pq);
[Link]("Peek: " + [Link]());
[Link]("Poll: " + [Link]());
[Link]("PriorityQueue after poll: " + pq);
}
}

24. Compare and contrast HashMap and TreeMap in Java.

Ans. HashMap and TreeMap are both part of the [Link] package and implement the
Map interface, but they differ in their implementation and behavior:

• HashMap:

Page 24 of 44
– Stores key-value pairs in a hash table.
– Allows null keys and values.
– Does not maintain any order of the elements.
– Provides constant-time performance for basic operations (e.g., get() and
put()) assuming the hash function disperses the elements properly.
• TreeMap:
– Stores key-value pairs in a red-black tree.
– Does not allow null keys, but allows null values.
– Maintains elements in a sorted order according to their natural ordering
or a specified comparator.
– Provides log-time performance for basic operations (e.g., get() and put()).

Example usage:

// Using HashMap
import [Link];
import [Link];

public class MapExample {


public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
[Link]("A", 1);
[Link]("C", 3);
[Link]("B", 2);
[Link]("HashMap: " + hashMap);

// Using TreeMap
TreeMap<String, Integer> treeMap = new TreeMap<>();
[Link]("A", 1);
[Link]("C", 3);
[Link]("B", 2);
[Link]("TreeMap: " + treeMap);
}
}

25. Discuss the advantages of using generics in Java Collections.

Ans. Generics in Java Collections provide several advantages:

• Type Safety: Generics ensure that only the specified type of objects can be
added to a collection, preventing runtime errors and reducing the need for
type casting.
• Code Reusability: Generics allow the creation of generic classes, inter-
faces, and methods, making the code more flexible and reusable for different
data types.

Page 25 of 44
• Compile-Time Checking: Generics provide compile-time type checking,
catching errors early in the development process and reducing runtime er-
rors.
• Improved Performance: Generics eliminate the need for type casting,
improving performance and making the code more readable.

Example usage:

import [Link];
import [Link];

public class GenericsExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
for (String s : list) {
[Link](s);
}
}
}

26. Write a code snippet to sort a List of integers in descending order using the
Collections class in Java.

Ans. The Collections class in Java provides utility methods for sorting and manipu-
lating collections. Here’s an example to sort a List of integers in descending
order:

import [Link];
import [Link];
import [Link];

public class SortListExample {


public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
[Link](5);
[Link](2);
[Link](8);
[Link](1);
[Link]("Original List: " + list);
[Link](list, [Link]());
[Link]("Sorted List in Descending Order: " + list);
}

Page 26 of 44
}

This code sorts the list in descending order using the [Link]()
comparator.

27. Explain the purpose of the Iterator interface in Java Collections Framework.

Ans. The Iterator interface in Java Collections Framework provides a way to traverse
the elements of a collection sequentially. It allows for the removal of elements
during iteration and ensures that the iteration process is consistent and safe.
Key methods include:

• hasNext(): Returns true if the iteration has more elements.


• next(): Returns the next element in the iteration.
• remove(): Removes the last element returned by the iterator.

Example usage:

import [Link];
import [Link];
import [Link];

public class IteratorExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
Iterator<String> iterator = [Link]();
while ([Link]()) {
String element = [Link]();
[Link](element);
if ([Link]("B")) {
[Link]();
}
}
[Link]("List after removal: " + list);
}
}

This code demonstrates the use of Iterator to traverse a list and remove an
element during iteration.

28. What are the key methods provided by the Comparator interface in Java?

Page 27 of 44
Ans. The Comparator interface in Java is used to define custom ordering for objects. It
provides the following key methods:

• compare(T o1, T o2): Compares its two arguments for order. Returns a neg-
ative integer, zero, or a positive integer as the first argument is less than,
equal to, or greater than the second.
• reversed(): Returns a comparator that imposes the reverse of the natural
ordering.
• thenComparing(Comparator<? super T> other): Returns a lexicographic-order
comparator with another comparator.

Example usage:

import [Link];
import [Link];
import [Link];
import [Link];

class Person {
String name;
int age;

Person(String name, int age) {


[Link] = name;
[Link] = age;
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class ComparatorExample {


public static void main(String[] args) {
List<Person> people = new ArrayList<>();
[Link](new Person("Alice", 30));
[Link](new Person("Bob", 25));
[Link](new Person("Charlie", 35));
// Sort by age
[Link](people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return [Link]([Link], [Link]);
}
});

Page 28 of 44
[Link]("Sorted by age: " + people);
// Sort by name
[Link](people, [Link](p -> [Link]));
[Link]("Sorted by name: " + people);
}
}

This code demonstrates the use of Comparator to sort a list of Person objects by
age and name.

29. Write a code snippet to synchronize an ArrayList in Java.

Ans. The Collections class in Java provides methods to make collections thread-safe.
Here’s an example to synchronize an ArrayList:

import [Link];
import [Link];
import [Link];

public class SynchronizedListExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
// Synchronize the ArrayList
List<String> synchronizedList = [Link](list);
synchronized (synchronizedList) {
for (String s : synchronizedList) {
[Link](s);
}
}
}
}

This code synchronizes the ArrayList using [Link]().

30. Explain the difference between Comparable and Comparator interfaces in Java.

Ans. Comparable and Comparator interfaces are both used to define the order of objects
in Java, but they differ in their implementation and usage:

• Comparable:
– Used to define the natural ordering of objects.
– Implemented by the class whose instances are being compared.

Page 29 of 44
– Contains a single method, compareTo(T o), which compares the current
object with the specified object.
• Comparator:
– Used to define custom ordering of objects.
– Implemented by a separate class that defines the comparison logic.
– Contains a single method, compare(T o1, T o2), which compares the two
specified objects.

Example usage:

// Using Comparable
class Person implements Comparable<Person> {
String name;
int age;

Person(String name, int age) {


[Link] = name;
[Link] = age;
}

@Override
public int compareTo(Person other) {
return [Link]([Link], [Link]);
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

// Using Comparator
class PersonNameComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return [Link]([Link]);
}
}

public class ComparisonExample {


public static void main(String[] args) {
List<Person> people = new ArrayList<>();
[Link](new Person("Alice", 30));
[Link](new Person("Bob", 25));
[Link](new Person("Charlie", 35));

Page 30 of 49
// Sort by age using Comparable
[Link](people);
[Link]("Sorted by age: " + people);
// Sort by name using Comparator
[Link](people, new PersonNameComparator());
[Link]("Sorted by name: " + people);
}
}

This code demonstrates the use of Comparable for natural ordering and Comparator
for custom ordering.

31. Discuss the importance of the Collections class in Java.

Ans. The Collections class in Java provides static utility methods for operating on
collections. It is part of the [Link] package and includes methods for sorting,
searching, reversing, and synchronizing collections, among others. Key methods
include:

• sort(List<T> list): Sorts the specified list into ascending order.


• reverse(List<?> list): Reverses the order of the elements in the specified
list.
• binarySearch(List<? extends Comparable<? super T>> list, T key): Searches
the specified list for the specified key using binary search.
• shuffle(List<?> list): Randomly permutes the elements in the specified
list.
• synchronizedList(List<T> list): Returns a synchronized (thread-safe) list
backed by the specified list.

The Collections class simplifies common operations on collections, making code


more readable and maintainable. Example usage:

import [Link];
import [Link];
import [Link];

public class CollectionsExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
// Shuffle the list
[Link](list);
[Link]("Shuffled List: " + list);

Page 31 of 44
// Sort the list
[Link](list);
[Link]("Sorted List: " + list);
// Reverse the list
[Link](list);
[Link]("Reversed List: " + list);
// Synchronized list
List<String> synchronizedList = [Link](list);
[Link]("Synchronized List: " + synchronizedList);
}
}

32. Write a code snippet to remove all elements from a LinkedList in Java.

Ans. The LinkedList class in Java is part of the [Link] package and implements the
List and Deque interfaces. It provides methods to manipulate the list. Here’s an
example to remove all elements from a LinkedList:

import [Link];

public class LinkedListExample {


public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("Original List: " + list);
// Remove all elements
[Link]();
[Link]("List after removal: " + list);
}
}

This code removes all elements from the LinkedList using the clear() method.

Page 32 of 44
Long answer type questions carying 10 Marks
1. Explain the different methods provided by the File class in Java. Write a
code snippet to demonstrate how to create a new file, check if it exists,
and delete it if it does. (5+5)
Ans. The File class in Java provides several methods to interact with the file system.
Some key methods include:
• exists(): Checks if the file or directory exists.
• createNewFile(): Creates a new, empty file if it does not already exist.
• delete(): Deletes the file or directory.
• isDirectory(): Checks if the path is a directory.
• isFile(): Checks if the path is a file.
• length(): Returns the length of the file in bytes.
• mkdir(): Creates a new directory.
• listFiles(): Lists the files and directories in the directory.

Example usage:

import [Link];
import [Link];

public class FileExample {


public static void main(String[] args) {
File file = new File("[Link]");
try {
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
if ([Link]()) {
[Link]("File exists.");
if ([Link]()) {
[Link]("File deleted.");
} else {
[Link]("Failed to delete the file.");
}
}
} catch (IOException e) {
[Link]();
}
}
}

Page 33 of 44
2. Describe the steps to read data from a file using BufferedReader and write
data to a file using BufferedWriter in Java. Write a code snippet for each.
(4+6)

Ans. BufferedReader and BufferedWriter are used for reading and writing text data
efficiently by buffering characters. They provide methods like readLine() and
write() for easy manipulation of text data.
Reading data using BufferedReader:

import [Link];
import [Link];
import [Link];

public class BufferedReaderExample {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (IOException e) {
[Link]();
}
}
}

Writing data using BufferedWriter:

import [Link];
import [Link];
import [Link];

public class BufferedWriterExample {


public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"))) {
[Link]("Hello, World!");
[Link]();
[Link]("BufferedWriter is efficient.");
} catch (IOException e) {
[Link]();
}
}
}

Page 34 of 44
3. Discuss the concept of random access in files using RandomAccessFile in
Java. Write a code snippet to demonstrate reading and writing at a spe-
cific position in the file. (5+5)

Ans. RandomAccessFile in Java allows reading from and writing to any part of a file,
providing random access to file contents. It supports seek() to move the file
pointer to a specific position, read() to read data, and write() to write data.
Example usage:

import [Link];
import [Link];

public class RandomAccessFileExample {


public static void main(String[] args) {
try (RandomAccessFile raf = new RandomAccessFile("[Link]", "rw")) {
// Write data at position 10
[Link](10);
[Link]("Hello, Random Access!");
// Read data from the beginning
[Link](0);
byte[] buffer = new byte[20];
[Link](buffer);
[Link](new String(buffer));
} catch (IOException e) {
[Link]();
}
}
}

4. Explain the use of FileInputStream and FileOutputStream for handling binary


data in Java. Write a code snippet to copy a binary file using these
classes. (5+5)

Ans. FileInputStream and FileOutputStream are used to handle binary data in Java.
FileInputStream reads raw bytes from a file, while FileOutputStream writes raw
bytes to a file. They are suitable for reading and writing binary files like images
and audio.
Example usage:

import [Link];
import [Link];
import [Link];

public class FileCopyExample {


public static void main(String[] args) {

Page 35 of 44
try (FileInputStream fis = new FileInputStream("[Link]");
FileOutputStream fos = new FileOutputStream("[Link]")) {
byte[] buffer = new byte[1024];
int length;
while ((length = [Link](buffer)) > 0) {
[Link](buffer, 0, length);
}
} catch (IOException e) {
[Link]();
}
}
}

5. What are the various file attributes and permissions that can be set using
the File class in Java? Demonstrate with a code snippet to set a file as
readable, writable, and executable. (5+5)

Ans. The File class in Java provides methods to set file attributes and permissions.
Key methods include:

• setReadable(boolean readable): Sets the read permission.


• setWritable(boolean writable): Sets the write permission.
• setExecutable(boolean executable): Sets the execute permission.
• canRead(): Checks if the file is readable.
• canWrite(): Checks if the file is writable.
• canExecute(): Checks if the file is executable.

Example usage:

import [Link];

public class FilePermissionExample {


public static void main(String[] args) {
File file = new File("[Link]");
// Set read, write, and execute permissions
[Link](true);
[Link](true);
[Link](true);
[Link]("Read permission: " + [Link]());
[Link]("Write permission: " + [Link]());
[Link]("Execute permission: " + [Link]());
}
}

Page 36 of 44
6. Explain how to navigate directories and list all files and subdirectories
using the File class in Java. Write a code snippet to list all files in a
directory and its subdirectories. (4+6)

Ans. The File class in Java provides methods to navigate directories and list files and
subdirectories. Key methods include:

• listFiles(): Returns an array of File objects representing the files and


directories in the directory.
• isDirectory(): Checks if the path is a directory.

Example usage:

import [Link];

public class ListFilesExample {


public static void main(String[] args) {
File directory = new File("exampleDirectory");
listFiles(directory);
}

public static void listFiles(File dir) {


if ([Link]()) {
File[] files = [Link]();
if (files != null) {
for (File file : files) {
if ([Link]()) {
[Link]("Directory: " + [Link]());
listFiles(file);
} else {
[Link]("File: " + [Link]());
}
}
}
}
}
}

7. Discuss the use of character streams in Java with examples of FileReader


and FileWriter. Write a code snippet to read a text file using FileReader
and write to another text file using FileWriter. (5+5)

Ans. Character streams in Java are used to handle text data. FileReader and FileWriter
are subclasses of Reader and Writer respectively and are used to read and write
text files.
Reading data using FileReader:

Page 37 of 44
import [Link];
import [Link];

public class FileReaderExample {


public static void main(String[] args) {
try (FileReader fr = new FileReader("[Link]")) {
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
} catch (IOException e) {
[Link]();
}
}
}

Writing data using FileWriter:

import [Link];
import [Link];

public class FileWriterExample {


public static void main(String[] args) {
try (FileWriter fw = new FileWriter("[Link]")) {
[Link]("Hello, World!\n");
[Link]("FileWriter is convenient for writing text data.");
} catch (IOException e) {
[Link]();
}
}
}

8. Explain the differences between BufferedReader and BufferedWriter in Java.


Write a code snippet to copy contents from one file to another using
these classes. (5+5)

Ans. BufferedReader and BufferedWriter are used for efficient reading and writing of
text data by buffering characters. BufferedReader buffers input, making it faster
to read lines or characters. BufferedWriter buffers output, making it faster to
write lines or characters.
Copying file contents using BufferedReader and BufferedWriter:

import [Link];
import [Link];

Page 38 of 44
import [Link];
import [Link];
import [Link];

public class FileCopyExample {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"));
BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
[Link]();
}
} catch (IOException e) {
[Link]();
}
}
}

9. Discuss the concept of file permissions and attributes in Java. Write a


code snippet to display the read, write, and execute permissions of a
file. (5+5)

Ans. File permissions in Java determine the actions that can be performed on a file
(read, write, execute). File attributes provide metadata about the file, such as
its size and modification time. The File class provides methods to check and set
these permissions.
Example usage:

import [Link];

public class FilePermissionsExample {


public static void main(String[] args) {
File file = new File("[Link]");
// Check file permissions
[Link]("Read permission: " + [Link]());
[Link]("Write permission: " + [Link]());
[Link]("Execute permission: " + [Link]());
// Set file permissions
[Link](true);
[Link](true);
[Link](true);
[Link]("Permissions updated.");
[Link]("Read permission: " + [Link]());
[Link]("Write permission: " + [Link]());

Page 39 of 44
[Link]("Execute permission: " + [Link]());
}
}

10. Explain the use of byte streams in Java with examples of FileInputStream
and FileOutputStream. Write a code snippet to read a binary file and write
its contents to another binary file using these classes. (5+5)

Ans. Byte streams in Java are used to handle binary data. FileInputStream and FileOutputStream
are subclasses of InputStream and OutputStream respectively and are used to read
and write binary files.
Reading data using FileInputStream:

import [Link];
import [Link];

public class FileInputStreamExample {


public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("[Link]")) {
int byteData;
while ((byteData = [Link]()) != -1) {
[Link](byteData + " ");
}
} catch (IOException e) {
[Link]();
}
}
}

Writing data using FileOutputStream:

import [Link];
import [Link];

public class FileOutputStreamExample {


public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("[Link]")) {
[Link](new byte[] {1, 2, 3, 4, 5});
} catch (IOException e) {
[Link]();
}
}
}

Page 40 of 49
11. Explain the various collection interfaces in the Java Collections Frame-
work. Write a code snippet to demonstrate the usage of the List, Set,
and Map interfaces. (5+5)

Ans. The Java Collections Framework provides several interfaces to represent different
types of collections:

• List: An ordered collection that allows duplicate elements. Common imple-


mentations include ArrayList, LinkedList, and Vector.
• Set: An unordered collection that does not allow duplicate elements. Com-
mon implementations include HashSet, LinkedHashSet, and TreeSet.
• Map: A collection that maps keys to values, with no duplicate keys. Common
implementations include HashMap, LinkedHashMap, and TreeMap.

Example usage:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class CollectionsExample {


public static void main(String[] args) {
// List example
List<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("List: " + list);

// Set example
Set<String> set = new HashSet<>();
[Link]("A");
[Link]("B");
[Link]("A"); // Duplicate element
[Link]("Set: " + set);

// Map example
Map<String, Integer> map = new HashMap<>();
[Link]("A", 1);
[Link]("B", 2);
[Link]("C", 3);
[Link]("Map: " + map);
}

Page 41 of 44
}

12. Describe the different implementations of the List interface in Java. Write
a code snippet to demonstrate the differences between ArrayList and
LinkedList. (5+5)

Ans. The List interface in Java has several implementations, each with different per-
formance characteristics:

• ArrayList: Provides fast random access and is suitable for most use cases.
However, it has slower insertion and deletion operations compared to LinkedList.
• LinkedList: Provides fast insertion and deletion operations but slower ran-
dom access compared to ArrayList.
• Vector: Similar to ArrayList but synchronized, making it thread-safe but
slower.

Example usage:

import [Link];
import [Link];
import [Link];

public class ListExample {


public static void main(String[] args) {
// ArrayList example
List<String> arrayList = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("ArrayList: " + arrayList);

// LinkedList example
List<String> linkedList = new LinkedList<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("LinkedList: " + linkedList);
}
}

13. Explain the differences between HashSet, LinkedHashSet, and TreeSet in Java.
Write a code snippet to demonstrate their usage. (5+5)

Ans. HashSet, LinkedHashSet, and TreeSet are implementations of the Set interface,
each with different characteristics:

Page 42 of 44
• HashSet: Provides constant-time performance for basic operations (e.g., add,
remove, contains) and does not maintain any order.
• LinkedHashSet: Maintains insertion order while providing constant-time per-
formance for basic operations.
• TreeSet: Maintains elements in sorted order and provides log-time perfor-
mance for basic operations.

Example usage:

import [Link];
import [Link];
import [Link];
import [Link];

public class SetExample {


public static void main(String[] args) {
// HashSet example
Set<String> hashSet = new HashSet<>();
[Link]("B");
[Link]("A");
[Link]("C");
[Link]("HashSet: " + hashSet);

// LinkedHashSet example
Set<String> linkedHashSet = new LinkedHashSet<>();
[Link]("B");
[Link]("A");
[Link]("C");
[Link]("LinkedHashSet: " + linkedHashSet);

// TreeSet example
Set<String> treeSet = new TreeSet<>();
[Link]("B");
[Link]("A");
[Link]("C");
[Link]("TreeSet: " + treeSet);
}
}

14. Discuss the concept of sorting collections in Java. Write a code snippet
to sort a List of strings in ascending and descending order using the
Collections class. (5+5)

Ans. Sorting collections in Java is often done using the Collections class, which pro-
vides static methods for sorting. The sort() method can sort a list in natural

Page 43 of 44
order or using a specified comparator.
Example usage:

import [Link];
import [Link];
import [Link];

public class SortExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("Banana");
[Link]("Apple");
[Link]("Cherry");
[Link]("Original List: " + list);

// Sort in ascending order


[Link](list);
[Link]("Sorted List (Ascending): " + list);

// Sort in descending order


[Link](list, [Link]());
[Link]("Sorted List (Descending): " + list);
}
}

15. Explain the purpose of the Queue interface in Java Collections Framework.
Write a code snippet to demonstrate the usage of PriorityQueue. (5+5)

Ans. The Queue interface in Java represents a collection designed for holding elements
prior to processing. It follows the FIFO (First-In-First-Out) principle, although
exceptions exist (e.g., PriorityQueue).
PriorityQueue orders elements according to their natural ordering or by a speci-
fied comparator.
Example usage:

import [Link];
import [Link];

public class QueueExample {


public static void main(String[] args) {
Queue<Integer> priorityQueue = new PriorityQueue<>();
[Link](10);
[Link](20);
[Link](15);

Page 44 of 44
[Link]("PriorityQueue: " + priorityQueue);

// Retrieve and remove the head of the queue


[Link]("Poll: " + [Link]());
[Link]("PriorityQueue after poll: " + priorityQueue);

// Retrieve but do not remove the head of the queue


[Link]("Peek: " + [Link]());
[Link]("PriorityQueue after peek: " + priorityQueue);
}
}

16. Describe the Map interface in Java Collections Framework and its imple-
mentations. Write a code snippet to demonstrate the usage of HashMap
and TreeMap. (5+5)

Ans. The Map interface in Java represents a collection of key-value pairs, where each
key maps to exactly one value. Common implementations include:

• HashMap: Provides constant-time performance for basic operations and does


not maintain any order.
• TreeMap: Maintains keys in sorted order and provides log-time performance
for basic operations.
• LinkedHashMap: Maintains insertion order while providing constant-time per-
formance.

Example usage:

import [Link];
import [Link];
import [Link];

public class MapExample {


public static void main(String[] args) {
// HashMap example
Map<String, Integer> hashMap = new HashMap<>();
[Link]("Apple", 3);
[Link]("Banana", 2);
[Link]("Cherry", 5);
[Link]("HashMap: " + hashMap);

// TreeMap example
Map<String, Integer> treeMap = new TreeMap<>();
[Link]("Apple", 3);
[Link]("Banana", 2);

Page 45 of 44
[Link]("Cherry", 5);
[Link]("TreeMap: " + treeMap);
}
}

17. Explain the concepts of Comparable and Comparator interfaces in Java. Write
a code snippet to demonstrate their usage for sorting a list of custom
objects. (5+5)

Ans. The Comparable and Comparator interfaces in Java are used to define the order of
objects:

• Comparable: Used to define the natural ordering of objects. A class imple-


menting Comparable must override the compareTo() method.
• Comparator: Used to define custom ordering of objects. A class implementing
Comparator must override the compare() method.

Example usage:

// Using Comparable
class Person implements Comparable<Person> {
String name;
int age;

Person(String name, int age) {


[Link] = name;
[Link] = age;
}

@Override
public int compareTo(Person other) {
return [Link]([Link], [Link]);
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

// Using Comparator
class PersonNameComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
return [Link]([Link]);

Page 46 of 44
}
}

public class ComparisonExample {


public static void main(String[] args) {
List<Person> people = new ArrayList<>();
[Link](new Person("Alice", 30));
[Link](new Person("Bob", 25));
[Link](new Person("Charlie", 35));
// Sort by age using Comparable
[Link](people);
[Link]("Sorted by age: " + people);
// Sort by name using Comparator
[Link](people, new PersonNameComparator());
[Link]("Sorted by name: " + people);
}
}

18. Discuss the importance of iterators in Java Collections Framework. Write


a code snippet to demonstrate the usage of an Iterator to traverse and
remove elements from a list. (5+5)

Ans. Iterators in Java Collections Framework provide a way to traverse and manipulate
elements in a collection. The Iterator interface provides methods like hasNext(),
next(), and remove() for safe and consistent iteration.
Example usage:

import [Link];
import [Link];
import [Link];

public class IteratorExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("Original List: " + list);

Iterator<String> iterator = [Link]();


while ([Link]()) {
String element = [Link]();
if ([Link]("B")) {
[Link]();
}

Page 47 of 44
}
[Link]("List after removal: " + list);
}
}

19. Explain the use of the Collections utility class in Java. Write a code snip-
pet to demonstrate the usage of [Link]() and [Link]().
(5+5)

Ans. The Collections utility class in Java provides static methods for operating on
collections. It includes methods for sorting, searching, reversing, and shuffling
collections, among others.
Example usage:

import [Link];
import [Link];
import [Link];

public class CollectionsUtilityExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("Banana");
[Link]("Apple");
[Link]("Cherry");
[Link]("Original List: " + list);

// Sort the list


[Link](list);
[Link]("Sorted List: " + list);

// Reverse the list


[Link](list);
[Link]("Reversed List: " + list);
}
}

20. Describe the concept of synchronizing collections in Java. Write a code


snippet to create a synchronized ArrayList and demonstrate thread-safe
access. (5+5)

Ans. Synchronizing collections in Java ensures thread-safe access to elements, pre-


venting concurrent modification issues. The Collections utility class provides
methods to synchronize collections.
Example usage:

Page 48 of 44
import [Link];
import [Link];
import [Link];

public class SynchronizedCollectionExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");

// Create a synchronized list


List<String> synchronizedList = [Link](list);

// Thread-safe access
synchronized (synchronizedList) {
for (String s : synchronizedList) {
[Link](s);
}
}
}
}

Page 49 of 44

You might also like