0% found this document useful (0 votes)
9 views12 pages

Eee - Java Key

The document contains various Java programming tasks, including implementing a stack interface, explaining StringBuilder and ListIterator methods, discussing string tokenization, and defining errors and exceptions. It also compares checked and unchecked exceptions, explains byte and character streams, and describes file reading and writing operations. Additionally, it covers AWT container hierarchy and thread management in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views12 pages

Eee - Java Key

The document contains various Java programming tasks, including implementing a stack interface, explaining StringBuilder and ListIterator methods, discussing string tokenization, and defining errors and exceptions. It also compares checked and unchecked exceptions, explains byte and character streams, and describes file reading and writing operations. Additionally, it covers AWT container hierarchy and thread management in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

5A)Write a java program to implement stack interface in java collection?

[7M,CO3,Apply]

[Program:5M+explanation:2M=7M]
import java.util.EmptyStackException;

interface Stack<T> {
void push(T element);
T pop();
T peek();
boolean isEmpty();
int size();
}

class ArrayStack<T> implements Stack<T> {


private Object[] array;
private int size;
private static final int DEFAULT_CAPACITY = 10;

public ArrayStack() {
array = new Object[DEFAULT_CAPACITY];
size = 0;
}

@Override
public void push(T element) {
if (size == array.length) {
resizeArray();
}
array[size++] = element;
}

@Override
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
@SuppressWarnings("unchecked")
T element = (T) array[--size];
array[size] = null; // dereference to avoid memory leaks
return element;
}

@Override
public T peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
@SuppressWarnings("unchecked")
T element = (T) array[size - 1];
return element;
}

@Override
public boolean isEmpty() {
return size == 0;
}

@Override
public int size() {
return size;
}

private void resizeArray() {


int newSize = array.length * 2;
Object[] newArray = new Object[newSize];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
}

public class Main {


public static void main(String[] args) {
Stack<Integer> stack = new ArrayStack<>();
stack.push(1);
stack.push(2);
stack.push(3);

System.out.println("Size of stack: " + stack.size());


System.out.println("Top element: " + stack.peek());

System.out.println("Popping elements:");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}

5B) what are the methods in String builder? Explain with suitable example? ?
[7M,CO3,Understand]
[Any 3 methods :3*2=6+Syntax:1M=7M]

The StringBuilder class in Java provides a mutable sequence of characters. Unlike String, objects
of StringBuilder can be modified. Here are some of the methods provided by the StringBuilder class
along with examples:
1. append(String str): Appends the specified string to the end of the StringBuilder.
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World");
System.out.println(sb.toString()); // Output: Hello World
2.insert(int offset, String str): Inserts the specified string at the specified position in the
StringBuilder.
StringBuilder sb = new StringBuilder("Hello World");
sb.insert(5, "Beautiful ");
System.out.println(sb.toString()); // Output: Hello Beautiful World

3.delete(int start, int end): Deletes the characters in a substring of the


StringBuilder.
StringBuilder sb = new StringBuilder("Hello World");
sb.delete(5, 12);
System.out.println(sb.toString()); // Output: Hello

4. deleteCharAt(int index): Deletes the character at the specified position.


StringBuilder sb = new StringBuilder("Hello World");
sb.deleteCharAt(5);
System.out.println(sb.toString()); // Output: Helloworld

5. replace(int start, int end, String str): Replaces the characters in a substring of the StringBuilder
with characters in the specified string.
StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb.toString()); // Output: Hello Java

6. reverse(): Reverses the sequence of characters in the StringBuilder.


StringBuilder sb = new StringBuilder("Hello World");
sb.reverse();
System.out.println(sb.toString()); // Output: dlroW olleH

7. charAt(int index): Returns the character at the specified index.


StringBuilder sb = new StringBuilder("Hello World");
char ch = sb.charAt(6);
System.out.println(ch); // Output: W

6A) what are the methods in Listiterater? Explain with suitable example? ?
[7M, CO3, Understand]
[Any 3 methods :3*2=6+Syntax:1M=7M]

The ListIterator interface in Java provides a way to iterate over the elements of a list
bidirectionally, allowing you to traverse the list in both forward and backward directions. It extends
the Iterator interface and provides additional methods for list manipulation. Here are some of the
methods provided by the ListIterator interface along with examples:
1. hasNext(): Returns true if there are more elements in the list when traversing in the forward
direction.

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


list.add("Apple");
list.add("Banana");
list.add("Orange");

ListIterator<String> iterator = list.listIterator();


while (iterator.hasNext()) {
System.out.println(iterator.next());
}
2. next(): Returns the next element in the list and advances the cursor position.
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

ListIterator<String> iterator = list.listIterator();


while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
3. hasPrevious(): Returns true if there are more elements in the list when traversing in the
backward direction.
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

ListIterator<String> iterator = list.listIterator(list.size());


while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}

4. previous(): Returns the previous element in the list and moves the cursor position backward.
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

ListIterator<String> iterator = list.listIterator(list.size());


while (iterator.hasPrevious()) {
String element = iterator.previous();
System.out.println(element);
}
5.remove(): Removes the last element returned by next() or previous() from the list.
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

ListIterator<String> iterator = list.listIterator();


while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("Banana")) {
iterator.remove(); // Remove Banana from the list
}
}

System.out.println(list); // Output: [Apple, Orange]


6B) How to break a string in to string into tokens in java? Discuss? [7M, CO3, Remember]
[String Tokenize object :r: 2M+ explanation:2M+example: 3M=7M]

StringTokenizer is a class in Java that allows you to break a string into tokens based on
specified delimiters.
Import java.util.StringTokenizer;

String str = "Hello, World! How are you?";


StringTokenizer tokenizer = new StringTokenizer(str, ",! ?");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(token);
}
1. In this example, the string str is broken into tokens using delimiters ,, !, , and ?.
2. Using split() method: The split() method of the String class splits a string into an array of
substrings based on a regular expression.
String str = "Hello, World! How are you?";
String[] tokens = str.split("[,! ?]+");
for (String token : tokens) {
System.out.println(token);
}
1. In this example, the string str is split into tokens using the regular expression [,! ?]+, which
matches one or more occurrences of ,, !, , or ?.
When choosing between StringTokenizer and split(), consider the following:
 StringTokenizer:
 More versatile for handling complex delimiters.
 Allows you to retrieve delimiters as tokens if needed.
 Can be more efficient when dealing with large strings.
 split():
 Simpler to use, especially for basic tokenization needs.
 Returns an array of tokens directly.
 Relies on regular expressions, which can be powerful for complex patterns.
In most cases, if you have simple tokenization requirements, the split() method is preferred due to
its simplicity. However, if you need more control over delimiters or need to handle complex
tokenization scenarios, StringTokenizer might be more suitable.

7A) Define error and Exception? Explain different types of Exceptions with example?
[10M, CO4, Understand]
[Error: 2M+Exception: 2M+types: 2M+Example: 4M=10M]
Errors:
Errors are exceptional conditions that are not expected to be caught under normal circumstances by
the application. They usually indicate serious problems that are unlikely to be recoverable, such as
out-of-memory errors or virtual machine failures.

public class Main {


public static void main(String[] args) {
while (true) {
new Thread(() -> {
while (true) {
// Infinite loop consuming memory
}
}).start();
}
}
}
Exceptions:
Exceptions are events that occur during the execution of a program that disrupts the normal flow of
instructions. They are typically caused by conditions that occur at runtime and are usually
recoverable.
Checked Exceptions:
Checked exceptions are exceptions that are checked by the compiler at compile time. They typically
represent conditions that a well-behaved application should anticipate and recover from.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class Main {


public static void main(String[] args) {
try {
File file = new File("example.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
Unchecked Exceptions (Runtime Exceptions):
Unchecked exceptions are exceptions that are not checked at compile time. They usually represent
programming errors or unexpected conditions.
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // ArrayIndexOutOfBoundsException
}
}

7B) Compare and contrast Checked vs Unchecked Exceptions in Java? [4M,CO4,Understand]


[Any 4 Points:4M=7M]
8A) What is the necessity of both streams byte streams and Character streams? Provide
implementation of these? [7M,CO4,Understand]
[Byte Streams and Character streams definations:4M+example:3M=7M]
Byte Streams:
Byte streams are used to perform I/O operations for raw binary data. They are suitable for reading
and writing data that doesn't have a character encoding associated with it, such as images, audio
files, or binary data.
Necessity of Byte Streams:
1. Efficiency: Byte streams are more efficient when dealing with binary data because they work
directly with the raw bytes without any encoding or decoding overhead.
2. Versatility: Byte streams can handle any type of data, including text and binary data.
3. Platform Independence: Byte streams are platform-independent, making them suitable for
transferring binary data between different systems.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteStreamExample {


public static void main(String[] args) {
try {
// Writing binary data to a file
FileOutputStream outputStream = new FileOutputStream("data.bin");
outputStream.write(new byte[]{65, 66, 67, 68, 69}); // Writing ASCII values of A, B, C, D, E
outputStream.close();

// Reading binary data from a file


FileInputStream inputStream = new FileInputStream("data.bin");
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data); // Converting byte to char for printing
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Character Streams:
Character streams are used to perform I/O operations for text-based data. They are designed to
handle characters and provide character encoding and decoding capabilities.
Necessity of Character Streams:
1. Character Encoding: Character streams handle character encoding and decoding
automatically, ensuring proper conversion between bytes and characters.
2. Text Processing: Character streams are suitable for reading and writing text-based data, such
as text files, XML, or JSON.
3. Localization: Character streams support proper handling of characters from different
character sets, making them suitable for internationalization and localization.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CharacterStreamExample {


public static void main(String[] args) {
try {
// Writing text data to a file
FileWriter writer = new FileWriter("data.txt");
writer.write("Hello, World!\n");
writer.write("How are you?");
writer.close();

// Reading text data from a file


FileReader reader = new FileReader("data.txt");
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
8B)explain read and write operations in File System in java? [7M,CO4,Understand]

[Package:1M+read and write explanation:3M+Example Program:3M= 7M]


reading and writing operations on the file system are typically performed using classes from
the java.io or java.nio packages. These classes provide various methods and functionalities to
interact with files and directories on the file system. Below, I'll explain the basic read and write
operations using both java.io and java.nio packages.
Reading and Writing Files using java.io Package:
Reading Files:
To read from a file, you typically use classes like FileInputStream, BufferedReader, or Scanner. These
classes allow you to read data from files byte by byte or line by line.
Example using FileInputStream:

import java.io.FileInputStream;
import java.io.IOException;

public class FileReaderExample {


public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream("example.txt");
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writing Files:
To write to a file, you typically use classes like FileOutputStream, BufferedWriter, or
PrintWriter. These classes allow you to write data to files byte by byte or line by line.
Example using FileOutputStream:
import java.io.FileOutputStream;
import java.io.IOException;

public class FileWriterExample {


public static void main(String[] args) {
try {
FileOutputStream outputStream = new FileOutputStream("example.txt");
String data = "Hello, World!";
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

9A) Explain AWT container Hierarchy? [7M, CO5, Understand]


[Diagram:3M+ Container and Components discriptions:4M=7M]
 Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
 Containers: AWT provides containers like panels, frames, and dialogues to organize and
group components in the Application.
 Layout Managers: Layout Managers are responsible for arranging data in the containers
some of the layout managers are BorderLayout, FlowLayout, etc.
 Event Handling: AWT allows the user to handle the events like mouse clicks, key presses, etc.
using event listeners and adapters.
 Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert images and
write text in the components of a Java Application.
There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents a graphical window or dialog box.
The Window class extends the Container class, which means it can contain other
components, such as buttons, labels, and text fields.
2. Panel: Panel is a container class in Java. It is a lightweight container that can be used for
grouping other components together within a window or a frame.
3. Frame: The Frame is the container that contains the title bar and border and can have menu
bars.
4. Dialog: A dialog box is a temporary window an application creates to retrieve user input.

9B) what is Thread? How to assign the Priority to the thread? Can two threads have same priority?
[7M, CO5, Understand]
[Definition:2M+Priority: 3M+Explanation:2M=7M]

A thread in Java represents a separate path of execution within a program. It allows


concurrent execution of tasks, enabling the program to perform multiple operations simultaneously.
Threads are lightweight processes that share the same memory space and resources within a
process.
Assigning Priority to Threads:
In Java, you can assign priority to threads using the setPriority() method of the Thread class.
Thread priorities are represented by integer values ranging from 1 to 10, where 1 is the lowest
priority and 10 is the highest priority. The default priority of a thread is 5.
Thread thread = new Thread();

thread.setPriority(Thread.MAX_PRIORITY); // Set priority to the maximum (10)


Yes, two or more threads can have the same priority. In Java, thread
priorities are used to influence the scheduling behavior of the underlying
operating system, but they do not strictly determine the order of execution. The
thread scheduler may choose to execute threads with higher priority over
threads with lower priority, but it's not guaranteed. Additionally, thread priorities
may behave differently on different platforms or JVM implementations.
Thread thread1 = new Thread();
Thread thread2 = new Thread();
thread1.setPriority(Thread.MIN_PRIORITY); // Set priority to the minimum (1)
thread2.setPriority(Thread.MIN_PRIORITY); // Set priority to the minimum (1)

10A) Define GUI and AWT? Explain Component and Container class in java?
[7M, CO5, Understand]
[Definition:2M+
GUI stands for Graphical User Interface, which is a type of interface that allows users to
interact with electronic devices through graphical icons and visual indicators, rather than text-based
interfaces, typed command labels, or text navigation. GUIs are commonly used in software
applications to provide a user-friendly and intuitive way for users to interact with the program's
functionalities.
AWT (Abstract Window Toolkit) is a set of classes in Java that provides a platform-
independent framework for building graphical user interfaces (GUIs). It was the original GUI toolkit
for Java and is part of the Java Foundation Classes (JFC). AWT components are lightweight, meaning
they rely on the native platform's GUI components for rendering, which can lead to differences in
appearance and behavior across different operating systems.
 Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
public class TextField extends TextComponent

Types of Containers in Java AWT


There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents a graphical window or dialog box.
The Window class extends the Container class, which means it can contain other
components, such as buttons, labels, and text fields.
2. Panel: Panel is a container class in Java. It is a lightweight container that can be used for
grouping other components together within a window or a frame.
3. Frame: The Frame is the container that contains the title bar and border and can have menu
bars.
4. Dialog: A dialog box is a temporary window an application creates to retrieve user input.

10B) Diffrence between Process and Thread?Why thread is called light weight process?Explain?
[7M, CO5, Understand]
[Process and Thread Diffrence:3M+Thread importance and Resion:4M=7M]
A thread is often referred to as a lightweight process because it shares some similarities with a
traditional process, but it is lighter in terms of memory and resources overhead. Here's why:
1. Shared Resources: Like processes, threads have their own execution context, including a
program counter, a set of registers, and a stack. However, threads within the same process
share the same memory space, allowing them to communicate and synchronize more
efficiently compared to separate processes, which have their own independent memory
spaces.
2. Lower Overhead: Creating and managing threads typically have lower overhead compared to
creating and managing processes. This is because threads within the same process share the
same address space and resources, such as file descriptors and memory, reducing the need
for expensive context switching and memory allocation.
3. Faster Context Switching: Context switching between threads is generally faster than context
switching between processes since threads within the same process share the same memory
space and resources. As a result, switching between threads involves primarily switching the
execution context, such as the program counter and registers, without the need to switch
memory spaces or reload the process image.
4. Scalability: Due to their lightweight nature, threads are more scalable than processes. It is
often more efficient to create multiple threads within the same process to perform
concurrent tasks than to create multiple independent processes. This makes threads suitable
for applications that require high levels of concurrency and parallelism.

You might also like