[Go to site: main page, start]

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

Java Lab Programmes

The document outlines a series of lab programs focused on Java programming using Eclipse, including steps to create and execute simple Java programs, a calculator applet, and factorial applet. It also includes a set of viva questions related to Java concepts such as platform independence, JIT compiler, and applet lifecycle. Additionally, it provides example code snippets and outputs for practical understanding.

Uploaded by

sai lalitha
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)
9 views74 pages

Java Lab Programmes

The document outlines a series of lab programs focused on Java programming using Eclipse, including steps to create and execute simple Java programs, a calculator applet, and factorial applet. It also includes a set of viva questions related to Java concepts such as platform independence, JIT compiler, and applet lifecycle. Additionally, it provides example code snippets and outputs for practical understanding.

Uploaded by

sai lalitha
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

Lab Programmes

PROGRAM -1
Steps To Execute Simple Java Program Using Eclipse Step1: Begin by creating a new Java
project. There are few different ways of accomplishing this. Click the arrow next to the left-
most icon on the toolbar and select “Project” from the drop-down menu. Alternately Start a new
Java Project by choosing “File” then “New” followed by “Java Project”. Also use the shortcut
Alt+Shift+N
Step2:
Enter a Project Name You will see a window titled “Create a Java Project”. The buttons “Next”
and “Finish” at the bottom of the window will be grayed out until a project name is entered in
the first field. To processed, give project name and enter it into this field then click “Finish”.
New project will appear on the left-hand side of the screen under “Package Explorer” among
existing projects. Projects are listed in alphabetical order.

Step3:
Start a new java class. Before begin writing code, need to create a new Java class. A class is a
blueprint for an object. It defines the data stored in the object as well as its actions. Create a
class by clicking the “New Java Class” icon, which looks like a green circle with the letter “C”
in the center of it.

4: Enter the name of your class.


You will see a window titled “Java Class.” To proceed, enter the name of class into the field
“Name”. Since the class will be main class of the simple project, check the selection box
labeled “public static void main(String[] args)” to include the method stub. Afterwards, click
“Finish”.
Step5: Enter Java Code.
Here new class [Link] is created. It appears with the method stub “public static void
main(String[] args)” along with some automatically generated comments. A method will
contain a sequence of instructions to be executed by the program. A comment is a statement that
is ignored by the compiler. Comments are used by programmers to document their code. Edit
this file and insert the code for Java Program
Step6: Watch out for errors in code.
Any errors will be underlined in red, and icon with an ”X” will show up on the left. Fix errors.
By mousing over an error [Link] see a suggestion box that lists the ways can fix the error.
Step7:
Ensure that entire program is free of errors. There are three types of errors must beware of:
syntax errors, run-time errors and logic errors. The compiler will alert syntax errors. Examples
of syntax errors are misspelled variable names or missing semi-colons. Until remove all syntax
errors from code program will not compile. The compiler will not catch run-time errors or logic
errors.

Step8:
Compile Java Program. Now the program is free for errors, click the triangular icon to run
program. Another way to run program is to select “Run” from the main menu and then select
“Run” again from the drop-down menu. The shortcut is Ctrl+F11.

Step9:
Verify the output is what you expected. When program runs, the output will be displayed on
console at the bottom of the screen.

Step10:
Fix any run-time or logic errors. If the output is different from what you excepted, then there
might have been an error even though the program compiled. For example, if the output was
zero instead of four, then there was a mistake in the program’s calculation.
2)Aim: Use Eclipse or Net bean platform and acquaint with the various menus. Create a testproject,
add a test class, and run it. See how you can use auto suggestions, auto fill. Try code formatter and
code refactoring like renaming variables, methods, and classes. Try debug step by step with a small
program of about 10 to 15 lines which contains at least one if else condition and a for loop.

Program:

public class Testclass {


public static void main(String[] args) {
int sum=0;
for(int i=0;i<=5; i++)
{
if(i%2==0)
{
sum+=i;
[Link](i+"is even,adding to sum");
}
else
{
[Link](i+" is odd,skipping");
}
}
[Link]("Total sum of even numbers:" + sum);
}
}
Output:
0is even,adding to sum
1 is odd,skipping
2is even,adding to sum
3 is odd,skipping
4is even,adding to sum
5 is odd,skipping
Total sum of even numbers:6

VIVA QUESTIONS:

1. What do you mean by Platform Independence?


Platform Independence you can run and compile program in one platform and can execute in
any other platform.
2. What is JIT Compiler?
Just-In-Time(JIT) compiler is used to improve the performance. JIT compiles parts of the byte
code that have similar functionality at the same time
3. What all memory areas are allocated by JVM?
Heap, Stack, Program Counter Register and Native Method Stack

4. What is the base class of all classes?


[Link]
5. What are two different ways to call garbage collector?
[Link]() OR [Link]().gc().
6. Use of finalize() method in java?
finalize() method is used to free the allocated resource.
7. List two java ID Es?
[Link], [Link] beans and [Link]
8. What are java buzzwords?
Java buzzwords explain the important features of java. They are Simple,Secured, Portable,
architecture neutral, high performance, dynamic, robust,interpreted etc.
9. Is byte code is similar to .obj file in C? Yes, both are machine understandable codes No, .obj
file directly understood by machine, byte code requires JVM.
[Link] are length and length( ) in Java? Both gives number of char/elements, length is
variable defined in Array class,length( ) is method defined in String class

2. Aim: Write a java program that works as a simple calculator. Use a GridLayout to
arrangeButtons for digits and for the + - * % operations. Add a text field to display
the result. Handle any possible exceptions like divide by zero.
THEORY: GridLayout is one of the Layout managers.A layout manager
automatically arranges your controls with in a window by using some type of
[Link] Layout lays out component in a two dimensional grid. When you
instantiate a GridLayout,you define the number of rows and columns
Program:

import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleCalculator extends JFrame implements ActionListener {
private JTextField display;
private String currentInput = "";
private double firstOperand = 0;
private String operator = "";

public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);

display = new JTextField();


[Link](false);
[Link](new Font("Arial", [Link], 24));
add(display, [Link]);

// Buttons panel
JPanel panel = new JPanel();
[Link](new GridLayout(5, 4, 5, 5));

String[] buttonLabels = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", "%", "/", "=",
"C"
};

for (String label : buttonLabels) {


JButton button = new JButton(label);
[Link](new Font("Arial", [Link], 20));
[Link](this);
[Link](button);
}

add(panel, [Link]);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String input = [Link]();

if ([Link]("\\d")) { // If it's a digit


currentInput += input;
[Link](currentInput);
} else if ([Link]("[+\\-*/%]")) { // If it's an operator
try {
firstOperand = [Link](currentInput);
operator = input;
currentInput = "";
} catch (NumberFormatException ex) {
[Link]("Error");
currentInput = "";
}
} else if ([Link]("=")) {
try {
double secondOperand = [Link](currentInput);
double result = 0;

switch (operator) {
case "+": result = firstOperand + secondOperand; break;
case "-": result = firstOperand - secondOperand; break;
case "*": result = firstOperand * secondOperand; break;
case "/":
if (secondOperand == 0) {
[Link]("Cannot divide by zero");
currentInput = "";
return;
}
result = firstOperand / secondOperand;
break;
case "%":
if (secondOperand == 0) {
[Link]("Cannot modulo by zero");
currentInput = "";
return;
}
result = firstOperand % secondOperand;
break;
}

[Link]([Link](result));
currentInput = [Link](result); // Allow chaining
} catch (NumberFormatException ex) {
[Link]("Error");
currentInput = "";
}
} else if ([Link]("C")) {
currentInput = "";
firstOperand = 0;
operator = "";
[Link]("");
}
}

public static void main(String[] args) {


[Link](SimpleCalculator::new);
}
}

Output:
Viva questions:
[Link] is object cloning?

The object cloning is used to create the exact copy of an object.

2. When parseInt() method can be used?

This method is used to get the primitive data type of a certain String.

3. [Link] consists of which classes?

[Link] consists of three classes − Pattern class, Matcher class and PatternSyntaxException class.

4. Which package is used for pattern matching with regular expressions?

[Link] package is used for this purpose.

[Link] immutable object?

An immutable object can‟t be changed once it is created.

[Link] Set Interface?


It is a collection of element which cannot contain duplicate elements. The Set interface contains only methods
inherited from Collection and adds the restriction that duplicate elements are prohibited.
[Link] is function overloading? If a class has multiple functions by same name but different parameters, it is
known as Method Overloading.

[Link] is function overriding?

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is
known as Method Overriding.

[Link] is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it
returns to the waiting state.

[Link] are Wrapper classes?

These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double,
Boolean etc.

PROGRAM -3(a)

Simple Applet Creation

Aim: Write an applet program that displays a simple message

THEORY:
Applets are designed to bring the web [Link] function to add animation sound and eventually
complete multi media into HTML [Link] is also part of the future of interfacing with virtual-
reality environments implemented via [Link] present ,java is limited only by the capabilities of the
internet [Link] are java programs that are specialized for use over the Web.
//Save file name as [Link]
//run in cmd “javac [Link]”
//after that run in cmd “appletviewer [Link]”
<!DOCTYPE html>
<html>
<head>
<title>Simple Applet Example</title>
</head>
<body>
<h1>My Java Applet</h1>
<applet code="[Link]" width="300" height="200">
Your browser does not support Java applets.
</applet>
</body>
</html>

//save file as [Link]


import [Link].*;
import [Link].*;

public class SimpleMessageApplet extends Applet {


public void paint(Graphics g) {
// Set the color and font for the message
[Link]([Link]);
Font font = new Font("Serif", [Link], 24);
[Link](font);

// Draw the message at a specific coordinate


[Link]("Hello from Applet!", 50, 50);
}
}
OutPut:

PROGRAM -3(b)

Factorial using applet

Aim: Write a java program that Develop an applet that receives an integer in one text field,
and computes its factorial Value and returns it in another text field, when the button named
“Compute” is clicked.

THEORY: Applets are designed to bring the web [Link] function to add animation
sound and eventually complete multi media into HTML [Link] is also part of the future of
interfacing with virtual-reality environments implemented via [Link] present ,java is limited only
by the capabilities of the internet [Link] are java programs that are specialized for use over the
Web. The Appplet life cycle The init()Method: The init()method is where your applet does much of its
setup,such as defined its layout,parsingparameters,or setting the background colors. The starts()
Method: The start()method is used mainly when implementing threads in java. The stop() Mehtod:
The stop() method is used to do what its name suggests: stop what is going on. The destroy() method:
when it is called,the applet is told to free up system resources.
Program:

3)b)Develop an applet that receives an integer in one text field,


And computes its factorial Value and returns it in another text field, when
theT thebutton named “Compute” is clicked

[Link]

//Save file name as [Link]


//run in cmd “javac [Link]”
//after that run in cmd “appletviewer [Link]”

<!-- [Link] -->


<html>
<body>
<applet code="[Link]" width="400" height="200">
</applet>
</body>
</html>

import [Link];
import [Link].*;
import [Link].*;
public class FactorialApplet extends Applet implements ActionListener {
TextField inputField, resultField;
Button computeButton;

public void init() {


// Initialize components
Label inputLabel = new Label("Enter an integer:");
inputField = new TextField(10);

computeButton = new Button("Compute");


[Link](this);

Label resultLabel = new Label("Factorial:");


resultField = new TextField(20);
[Link](false);

// Add components to applet


add(inputLabel);
add(inputField);
add(computeButton);
add(resultLabel);
add(resultField);
}

public void actionPerformed(ActionEvent e) {


try {
int num = [Link]([Link]());
if (num < 0) {
[Link]("Invalid input! Enter non-negative.");
return;
}
long fact = 1;
for (int i = 2; i <= num; i++) {
fact *= i;
}
[Link]([Link](fact));
} catch (NumberFormatException ex) {
[Link]("Invalid input! Enter a valid integer.");
}
}
}

OutPut:
VIVA QUESTIONS:

1. What is an applet? How does applet differ from applications?


What is an applet? How does applet differ from applications? - A program that a Java enabled
browser can download and run is an Applet.
2. What are the attributes of Applet tags? Explain the purposes?
What are the attributes of Applet tags? - height: Defines height of applet, width: Defines
width of applet.

3. How will you initialize an Applet?


Write my initialization code in the applets init method or applet constructor.
4. What is the sequence for calling the methods by AWT for applets?
When an applet begins, the AWT calls the following methods, in this sequence:

► init()
► start()
► paint()

When an applet is terminated, the following sequence of method calls takes place :

► stop()
► destroy()
5. What is AppletStub Interface?
The applet stub interface provides the means by which an applet and the browser communicate.
Your code will not typically implement this interface.

6. What is the base class for all swing components?


JComponent (except top-level containers)

7. How will you communicate between two Applets?

All the applets on a given page share the same AppletContext. We obtain this applet context as
follows:

AppletContext ac = getAppletContext();

AppletContext provides applets with methods such as getApplet(name), getApplets(),


getAudioClip(url), getImage(url), showDocument(url) and showStatus(status).
8. What is exception propagation ?

Forwarding the exception object to the invoking method is known as exception propagation.

9. What is the meaning of immutable in terms of String?

The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been
created, its value can't be changed.
PROGRAM -4
Creates a User Interface to perform Integer Divisions

Aim: Write a program that creates a user interface to perform integer divisions. The userenters
two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in
the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the
program would throw Number Format Exception. If Num2 were Zero, the program would throwan
Arithmetic Exception Display the exception in a message dialog box.
THEORY: The AWT supports a rich assortment of graphics methods. All graphics are drawn
relative to a window. this can the main window of an applet, a child window of an applet, or a stand
alone application window. The origin of each window is at the top-left corner and is 0,0cordinates
are specified in pixels. All output to a window takes place through a graphics context

Program:

import [Link].*;
import [Link].*;
import [Link].*;

public class IntegerDivisionGUI extends JFrame {

private JTextField num1Field, num2Field, resultField;


private JButton divideButton;

public IntegerDivisionGUI() {
// Set up the GUI
setTitle("Integer Division");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2, 10, 10));

// Create components
JLabel num1Label = new JLabel("Num1:");
JLabel num2Label = new JLabel("Num2:");
JLabel resultLabel = new JLabel("Result:");

num1Field = new JTextField();


num2Field = new JTextField();
resultField = new JTextField();
[Link](false);

divideButton = new JButton("Divide");

// Add components to the frame


add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(resultLabel);
add(resultField);
add(new JLabel()); // empty cell
add(divideButton);

// Add button action


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int num1 = [Link]([Link]());
int num2 = [Link]([Link]());

if (num2 == 0) {
throw new ArithmeticException("Division by zero");
}

int result = num1 / num2;


[Link]([Link](result));
} catch (NumberFormatException ex) {
[Link](null, "Please enter valid integers.",
"Input Error", JOptionPane.ERROR_MESSAGE);
} catch (ArithmeticException ex) {
[Link](null, "Cannot divide by zero.",
"Math Error", JOptionPane.ERROR_MESSAGE);
}
}
});

setVisible(true);
}

public static void main(String[] args) {


new IntegerDivisionGUI();
}
}

OutPut:

VIVA QUESTIONS:

1. What is Exception Handling?

Exception Handling is a mechanism to handle runtime [Link] is mainly used to handle checked
exceptions.
2. What is difference between Checked Exception and Unchecked Exception?

i). Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions [Link],SQLException etc. Checked exceptions are checked at compile-time.

ii). Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at compile-
time.

3. What is the base class for Error and Exception?


Throwable.

4. What is finally block?


finally block is a block that is always executed

5. Can finally block be used without catch?


Yes, by try block. finally must be followed by either try or catch.

6. Is there any case when finally will not be executed?


finally block will not be executed if program exits(either by calling [Link]() or by causing a
fatal error that causes the process to abort)

7. What is exception propagation ?


Forwarding the exception object to the invoking method is known as exception propagation.

8. What is nested class?

A class which is declared inside another class is known as nested class. There are 4 types of
nested class member inner class, local inner class, annonymous inner class and static nested class.
9. What is nested interface ?

Any interface i.e. declared inside the interface or class, is known as nested interface. It is static by
default.

10. Can an Interface have a class?

Yes, they are static implicitely


PROGRAM -5: Multithreaded Program

Aim : Write a Java program that implements a multithreaded program has three threads. First thread generates a
random integer every 1 second and if the value is even, second thread computes the square of the number and
prints. If the value is odd the third thread will print the value of cube of the number.

THEORY: The java run-time system depends on the threads for many things, and all the class libraries are
designed with multithreading in mind. In fact ,java uses threads to enable the entire environment to be
asynchronous. This helps reduce inefficiency by preventing the waste of CPU cycles. The benefits of java‟s
multithreading is that the main loop/polling mechanism is eliminated. one thread can pause without stopping
other parts of your program. when a thread blocks in a java program, only the single thread that is blocked
pauses. All other threads continue to run.

import [Link];

class NumberGenerator extends Thread {


public void run() {

Random rand = new Random();

while (true) {

int num = [Link](100); // generate random int from 0 to 99

[Link]("\nGenerated Number: " + num);

if (num % 2 == 0) {

new SquareThread(num).start();
} else {

new CubeThread(num).start();

try {

[Link](1000); // wait for 1 second


} catch (InterruptedException e) {

[Link](e);

}
}

class SquareThread extends Thread {

int number;

SquareThread(int num) {

[Link] = num;

public void run() {

[Link]("Square of " + number + " = " + (number * number));

class CubeThread extends Thread {

int number;

CubeThread(int num) {
[Link] = num;

public void run() {

[Link]("Cube of " + number + " = " + (number * number * number));

public class MultithreadExample {

public static void main(String[] args) {


NumberGenerator generator = new NumberGenerator();

[Link]();

}
}

Output:
Generated Number: 12

Square of 12 = 144

Generated Number: 7

Cube of 7 = 343

VIVA QUESTIONS
1) What is multithreading? Multithreading is a process of executing multiple threads simultaneously. Its main
advantage is: o Threads share the same address space. o Thread is lightweight. o Cost of communication
between process is low.

2) What is thread? A thread is a lightweight [Link] is a separate path of [Link] is called separate
path of execution because each thread runs in a separate stack frame.
3)What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the
highest priority task executes until it enters the waiting or dead states or a higher priority task comes into
existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready
tasks. The scheduler then determines which task should execute next, based on priority and other factors.

4) What does join() method? The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.

5) Is it possible to start a thread twice? No, there is no possibility to start a thread twice. If we does, it throws an
exception.

6) Can we call the run() method instead of start()? yes, but it will not work as a thread rather it will work as a
normal object so there will not be context-switching between the threads.

7) What about the daemon threads? The daemon threads are basically the low priority threads that provides the
background support to the user threads. It provides services to the user threads.

8) Can we make the user thread as daemon thread if thread is started? No, if you do so, it will throw
IllegalThreadStateException
9)What is shutdown hook? The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts
down. So we can use it perform clean up resource.

10)When should we interrupt a thread? We should interrupt a thread if we want to break out the sleep or wait
state of a thread.

PROGRAM -6 : Aim: Write a Java program for the following:


i) Create a doubly linked list of elements.

ii) ii) Delete a given element from the above list.

iii) iii) Display the contents of the list after deletion

THEORY: A doubly-linked list is a linked data structure that consists of a set of sequentially linked records
called nodes. Each node contains two fields, called links, that are references to the previous and to the next node
in the sequence of nodes. The beginning and ending nodes previous and next links, respectively, point to some
kind of terminator, typically a sentinel node or null, to facilitate traversal of the list. If there is only one sentinel
node, then the list is circularly linked via the sentinel node. It can be conceptualized as two singly linked lists
formed from the same data items, but in opposite sequential orders.

i) Create a doubly linked list of elements


class DoublyLinkedList

// Node class

class Node {

int data;

Node prev;

Node next;

Node(int data) {

[Link] = data;

[Link] = null;
[Link] = null;

private Node head;

// Insert at end

public void insert(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode;

return;

Node temp = head;

while ([Link] != null) {

temp = [Link];
}

[Link] = newNode;

[Link] = temp;

// Display forward

public void displayForward() {

[Link]("Doubly Linked List (Forward): ");

Node temp = head;

while (temp != null) {


[Link]([Link] + " ");

temp = [Link];

}
[Link]();

// Display backward

public void displayBackward() {

[Link]("Doubly Linked List (Backward): ");

Node temp = head;

// Go to last node

if (temp == null) return;

while ([Link] != null) {

temp = [Link];

// Print in reverse
while (temp != null) {
[Link]([Link] + " ");

temp = [Link];

[Link]();

public static void main(String[] args) {

DoublyLinkedList list = new DoublyLinkedList();

// Insert elements
[Link](10);

[Link](20);

[Link](30);
[Link](40);

// Display

[Link]();

[Link]();

Output:
Doubly Linked List (Forward): 10 20 30 40

Doubly Linked List (Backward): 40 30 20 10

ii) Delete a given element from the above list.

Program:
class DoublyLinkedList {

// Node class

class Node {

int data;
Node prev;

Node next;

Node(int data) {

[Link] = data;

[Link] = null;

[Link] = null;

private Node head;

// Insert at end

public void insert(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode;
return;
}

Node temp = head;

while ([Link] != null) {

temp = [Link];

[Link] = newNode;

[Link] = temp;

}
// Delete a node with given value

public void delete(int key) {


if (head == null) {

[Link]("List is empty!");

return;

Node temp = head;

// Case 1: First node has the key

if ([Link] == key) {

head = [Link];

if (head != null) [Link] = null;

[Link]("Deleted: " + key);

return;

// Search for the node to delete


while (temp != null && [Link] != key) {

temp = [Link];

// If key not found

if (temp == null) {

[Link]("Element " + key + " not found!");

return;

}
// Unlinking the node

if ([Link] != null) [Link] = [Link];

if ([Link] != null) [Link] = [Link];

[Link]("Deleted: " + key);

// Display forward

public void displayForward() {

[Link]("Doubly Linked List (Forward): ");

Node temp = head;

while (temp != null) {

[Link]([Link] + " ");

temp = [Link];

[Link]();

public static void main(String[] args) {


DoublyLinkedList list = new DoublyLinkedList();

// Insert elements

[Link](10);

[Link](20);

[Link](30);

[Link](40);

// Display initial list

[Link]();
// Delete element

[Link](30);

// Display after deletion

[Link]();

Output:
Doubly Linked List (Forward): 10 20 30 40

Deleted: 30

Doubly Linked List (Forward): 10 20 40

iii) Display the contents of the list after deletion

class DoublyLinkedList {

// Node class for doubly linked list

class Node {

int data;

Node prev;

Node next;
Node(int data) {

[Link] = data;

[Link] = null;
[Link] = null;

private Node head;

// Insert at end

public void insert(int data) {

Node newNode = new Node(data);

if (head == null) {

head = newNode;

return;

Node temp = head;


while ([Link] != null) {

temp = [Link];

[Link] = newNode;

[Link] = temp;

// Delete a node with the given value

public void delete(int key) {


if (head == null) {

[Link]("List is empty!");

return;
}

Node temp = head;

// Case 1: First node has the key

if ([Link] == key) {

head = [Link];

if (head != null) [Link] = null;

[Link]("Deleted: " + key);

return;

// Search for the node to delete

while (temp != null && [Link] != key) {

temp = [Link];
}

// If key not found

if (temp == null) {

[Link]("Element " + key + " not found!");

return;

// Unlinking the node

if ([Link] != null) [Link] = [Link];

if ([Link] != null) [Link] = [Link];


[Link]("Deleted: " + key);

// Display the list

public void display() {

if (head == null) {

[Link]("List is empty!");

return;

[Link]("Current List: ");

Node temp = head;

while (temp != null) {

[Link]([Link] + " ");

temp = [Link];

[Link]();
}

public static void main(String[] args) {

DoublyLinkedList list = new DoublyLinkedList();

// Insert elements

[Link](10);

[Link](20);

[Link](30);

[Link](40);
// Display initial list

[Link]("Before Deletion:");

[Link]();

// Delete element

[Link](30);

// Display list after deletion

[Link]("After Deletion:");

[Link]();

Output:
Before Deletion:

Current List: 10 20 30 40
Deleted: 30
After Deletion:

Current List: 10 20 40

VIVA QUESTIONS:
1. What is a Linked list? Linked list is an ordered set of data elements, each containing a link to its successor
(and typically its predecessor).

2. Can you represent a Linked list graphically? The fundamental data structure for the linked record involves 3
segments: the data itself and also the link to another element. Together (data + link) this particular structure is
normally called the Node.

3. How many pointers are required to implement a simple Linked list? You can find generally
3 pointers engaged:

 A head pointer, pointing to the start of the record.

 A tail pointer, pointing on the last node of the list. The key property in the last node is that its subsequent
pointer points to nothing at all (NULL).

 A pointer in every node, pointing to the next node element.

4. How many types of Linked lists are there? Singly linked list, doubly linked list, multiply linked list, Circular
Linked list.

5. How to delete a node from linked list?

 The following are the steps to delete node from the list at the specified position. Set the head to point to the
node that head is pointing to.

 Traverse to the desired position or till the list ends; whichever comes first

 You have to point the previous node to the next node.

6. How to reverse a singly linked list?

 First, set a pointer (*current) to point to the first node i.e. current=head.  Move ahead until current!=null
(till the end)

 set another pointer (*next) to point to the next node i.e. next=current->next

 store reference of *next in a temporary variable (*result) i.e. current->next=result

 swap the result value with current i.e. result=current  And now swap the current value with next. i.e.
current=next

 return result and repeat from step 2  A linked list can also be reversed using recursion which eliminates the
use of a temporary variable.

7. Compare Linked lists and Dynamic Arrays A dynamic array is a data structure that allocates all elements
contiguously in memory, and keeps a count of the present number of elements. If the area reserved for the
dynamic array is exceeded, it‟s reallocated and traced, a costly operation. Linked lists have many benefits over
dynamic arrays. Insertion or deletion of an element at a specific point of a list, is a constant-time operation,
whereas insertion in a dynamic array at random locations would require moving half the elements on the
average, and all the elements in the worst case. Whereas one can delete an element from an array in constant
time by somehow marking its slot as vacant, this causes fragmentation that impedes the performance of
iteration.

8. What is a Circular Linked list?

In the last node of a singly linear list, the link field often contains a null reference. A less common convention is
to make the last node to point to the first node of the list; in this case the list is said to be „circular‟ or
„circularly linked‟.
PROGRAM -7 :
Traffic Light Simulation

Aim: Write a java program to simulate a traffic light. The program lets the user select one
of the three lights: red, yellow or green. On selecting a button, an appropriate message with
”Stop” or “Ready” or “ Go” should appear above the buttons selected color.

THEORY: The AWT supports a rich assortment of graphics [Link] graphics are drawn relative
to a [Link] can the main windowof an applet, a child window of an applet,or a stand alone
application window. The origin of each window is at the top-left corner and is 0,0cordinates are
specified in [Link] output to a window takes place through a graphics context.

Program:

//run in cmd as “javac [Link]”

//after run in cmd as “java TrafficLightSimulator”

import [Link].*;

import [Link].*;

import [Link].*;

public class TrafficLightSimulator extends JFrame implements ActionListener {

private JLabel messageLabel;

private JButton redButton, yellowButton, greenButton;

public TrafficLightSimulator() {
// Set up the frame

setTitle("Traffic Light Simulator");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

// Label to display messages

messageLabel = new JLabel("", [Link]);

[Link](new Font("Arial", [Link], 18));

add(messageLabel, [Link]);

// Panel to hold the buttons

JPanel buttonPanel = new JPanel();

[Link](new FlowLayout());

// Create buttons

redButton = new JButton("Red");

yellowButton = new JButton("Yellow");

greenButton = new JButton("Green");

// Add action listeners

[Link](this);

[Link](this);

[Link](this);
// Add buttons to panel

[Link](redButton);

[Link](yellowButton);

[Link](greenButton);

// Add panel to frame

add(buttonPanel, [Link]);

// Set visible

setVisible(true);

// Handle button clicks

public void actionPerformed(ActionEvent e) {

if ([Link]() == redButton) {

[Link]("Stop");

[Link]([Link]);

} else if ([Link]() == yellowButton) {

[Link]("Ready");

[Link]([Link]);

} else if ([Link]() == greenButton) {

[Link]("Go");

[Link]([Link]());
}

public static void main(String[] args) {

new TrafficLightSimulator();

OutPut:

VIVA QUESTIONS:

1. What is GUI?
GUI stands for Graphical User Interface.
- GUI allows uses to click, drag, select graphical objects such as icons, images, buttons etc.
- GUI suppresses entering text using a command line.
- Examples of GUI operating systems are Windows, Mac, Linux.
- GUI is user friendly and increases the speed of work by the end users.
- A novice can understand the functionalities of certain application through GUI.
2. What is the difference between HashSet and TreeSet?

HashSet maintains no order whereas TreeSet maintains ascending order.

3) What is the difference between Set and Map?

Set contains values only whereas Map contains key and values both.

4) What is the difference between HashSet and HashMap?

HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be
iterated but HashMap need to convert into Set to be iterated.

5) What is the difference between HashMap and TreeMap?

HashMap maintains no order but TreeMap maintains ascending order.

6) What is the difference between Collection and Collections?

Collection is an interface whereas Collections is a class. Collection interface provides normal


functionality of data structure to List, Set and Queue. But, Collections class is to sort and
synchronize collection elements.

7) What is the advantage of generic collection?

If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

8) What is hash-collision in Hashtable and how it is handled in Java?

Two different keys with the same hash value is known as hash-collision. Two different entries will
be kept in a single hash bucket to avoid the collision.

9) What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs.


10) What is the default size of load factor in hashing based collection?

The default size of load factor is 0.75. The default capacity is computed as initial capacity * load
factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

PROGRAM -8 :

Abstract Class

Aim: Write a java program to create an abstract class named shape that contains twointegers and
an empty method named printArea() Provide three classes named Rectangle,, Triangle and Circle
such that each one of the classes extends the class shape. Each one of the class contains only the
method printArea() that print the area of the given shape.
THEORY: To create an abstract class that shows the hiding of elements in a class. At the same
time inheritance property is used to extend the class shape into different geometrical figures. This
represents the reusability of code for a programmer.

Program:

abstract class Shape {


int a, b;

// Constructor to initialize dimensions


Shape(int a, int b) {
this.a = a;
this.b = b;
}

// Abstract method to be implemented by subclasses


abstract void printArea();
}

// Rectangle class
class Rectangle extends Shape {
Rectangle(int length, int breadth) {
super(length, breadth);
}

void printArea() {
int area = a * b;
[Link]("Area of Rectangle: " + area);
}
}

// Triangle class
class Triangle extends Shape {
Triangle(int base, int height) {
super(base, height);
}

void printArea() {
double area = 0.5 * a * b;
[Link]("Area of Triangle: " + area);
}
}

// Circle class
class Circle extends Shape {
Circle(int radius) {
super(radius, 0); // 'b' is unused
}

void printArea() {
double area = [Link] * a * a;
[Link]("Area of Circle: " + area);
}
}

// Main class to test the shapes


public class ShapeTest {
public static void main(String[] args) {
Shape rectangle = new Rectangle(10, 5);
Shape triangle = new Triangle(8, 6);
Shape circle = new Circle(7);

[Link]();
[Link]();
[Link]();
}
}

OutPut:

Area of Rectangle: 50
Area of Triangle: 24.0
Area of Circle: 153.93804002589985

VIVA QUESTIONS:

1. What is abstraction?

Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Abstraction lets you focus on what the object does instead of how it does it.

2. What is the difference between abstraction and encapsulation?

Abstraction hides the implementation details whereas encapsulation wraps code and data into a
single unit.

3. What is abstract class?

A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.

4. Can there be any abstract method without abstract class?

No, if there is any abstract method in a class, that class must be abstract.

5. Can you use abstract and final both with a method?


No, because abstract method needs to be overridden whereas you can't override final method.

6. Is it possible to instantiate the abstract class?

No, abstract class can never be instantiated.

7. What is interface?

Interface is a blueprint of a class that have static constants and abstract [Link] can be used to
achieve fully abstraction and multiple inheritance.

8. Can you declare an interface method static?

No, because methods of an interface is abstract by default, and static and abstract keywords can't
be used together.

9. Can an Interface be final?

No, because its implementation is provided by another class.

10. What is marker interface?

An interface that have no data member and method is known as a marker [Link] example
Serializable, Cloneable etc.

PROGRAM -9 :

Display Table using Grid Layout


Aim: Suppose that table named [Link] is stored in a text file. The first line in the fileis the header,
and the remaining lines correspond to rows in the table. The elements are separated by commas.
Write a java program to display the table using in Grid Layout.

THEORY: To create an table and display it using JTable components


Program:
//create one txt file in your notepad and saved in folder where you are saving java programs
// that file can like

Name, Age, City


Alice, 23, New York
Bob, 30, London
Carol, 25, Paris

// after saved above file now you can write a program and execute it

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class DisplayTableGrid {


public static void main(String[] args) {
[Link](() -> {
new DisplayTableGrid().createAndShowGUI("[Link]");
});
}

public void createAndShowGUI(String filename) {


JFrame frame = new JFrame("Table Display");
[Link](JFrame.EXIT_ON_CLOSE);

[Link]<String[]> rows = readTableFromFile(filename);


if ([Link]()) {
[Link](frame, "File is empty or not found!");
return;
}

int rowCount = [Link]();


int colCount = [Link](0).length;

[Link](new GridLayout(rowCount, colCount, 5, 5));


// Add labels for each cell
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
JLabel label = new JLabel([Link](i)[j], [Link]);
[Link]([Link]([Link]));

// Make header bold


if (i == 0) {
[Link]([Link]().deriveFont([Link]));
[Link](Color.LIGHT_GRAY);
[Link](true);
}
[Link](label);
}
}

[Link]();
[Link](null);
[Link](true);
}

private [Link]<String[]> readTableFromFile(String filename) {


[Link]<String[]> table = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = [Link]()) != null) {
[Link]([Link]("\\s*,\\s*"));
}
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
}
return table;
}
}
OutPut:

VIVA QUESTIONS:
1. polymorphism is a feature that allows
2. polymorphism is expressed by the phrases one interface methods.
3. Method override is the basis .
4. Java implements using dynamic method dispatch.
5. A super class reference variable can refer to a object.
6. The type of object being referred to determines which version of an method.
7. Override methods allows java to support _________ 63
8. Method override occurs only when the names and the type signature of the two
methods are
9. When a method in the subclass has the same name and type as the method in the super class
then the method in the subclass is said to the method in the super class.
10. Difference between overloading and overriding is

PROGRAM -10 :

Mouse Events

Aim: Write a java program that handles all mouse events and shows the event
name at thecenter of the window when mouse event is fired(Use Adapter classes).
THEORY: To handle mouse events you must implement the MouseListener and
the [Link] two interfaces contain methods that
receive and process the various types of mouse events.
Program:

import [Link].*;
import [Link].*;
import [Link].*;

public class MouseEventDemo extends JFrame {

private String eventText = "Perform a mouse action!";

public MouseEventDemo() {
setTitle("Mouse Event Demo (Adapter Classes)");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Custom panel to display text in center


DrawingPanel panel = new DrawingPanel();
add(panel);

// Use adapter class to handle mouse events


[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
eventText = "Mouse Clicked";
[Link]();
}

@Override
public void mousePressed(MouseEvent e) {
eventText = "Mouse Pressed";
[Link]();
}

@Override
public void mouseReleased(MouseEvent e) {
eventText = "Mouse Released";
[Link]();
}
@Override
public void mouseEntered(MouseEvent e) {
eventText = "Mouse Entered";
[Link]();
}

@Override
public void mouseExited(MouseEvent e) {
eventText = "Mouse Exited";
[Link]();
}
});

// Mouse motion adapter for drag and move


[Link](new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
eventText = "Mouse Dragged";
[Link]();
}

@Override
public void mouseMoved(MouseEvent e) {
eventText = "Mouse Moved";
[Link]();
}
});

setVisible(true);
}

// Inner class for custom drawing


class DrawingPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
[Link](g);
[Link](new Font("Arial", [Link], 20));
FontMetrics fm = [Link]();
int x = (getWidth() - [Link](eventText)) / 2;
int y = getHeight() / 2;
[Link](eventText, x, y);
}
}

public static void main(String[] args) {


[Link](MouseEventDemo::new);
}
}

OutPut:

VIVA QUESTIONS:
1. MOUSE_CLICKED events occurs when
2. MOUSE_DRAGGED events occurs when
3. events occur when mouse enters a component.
4. events occur when the mouse exists a component
5. MOUSE_MOVED event occurs when
6. MOUSE_PRESSED even occurs when
7. The events occur when mouse was released.
8. The event occurs when mouse wheel is moved.
9. An event source is
10. A is an object that describes the state change in a source

PROGRAM -11 :

Using File and Hash Table

Aim: Write a java program that loads names and phone numbers from a text file
where thedata is organized as one line per record and each field in a record are
separated by tab(\t).It takes a name or phone number as input and prints the
corresponding other value from the hash table(use hash tables).

THEORY: Text file will contain names and phone numbers which are separated by
a tab. This information has to be recorded in to hash table.

Program:
// first create one data file saviving like “[Link]”

Alice 9876543210
Bob 9123456780
Carol 9988776655

import [Link].*;
import [Link].*;
public class PhoneDirectory {
public static void main(String[] args) {
// Two hash tables: one for name → phone, another for phone → name
Hashtable<String, String> nameToPhone = new Hashtable<>();
Hashtable<String, String> phoneToName = new Hashtable<>();
String filename = "[Link]"; // Your input file (tab-separated)
// Load data from file
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = [Link]()) != null) {
// Split line by tab character
String[] parts = [Link]("\\t");
if ([Link] == 2) {
String name = parts[0].trim();
String phone = parts[1].trim();
[Link](name, phone);
[Link](phone, name);
}
}
} catch (IOException e) {
[Link]("Error reading file: " + [Link]());
return;
}
// Input from user
Scanner sc = new Scanner([Link]);
[Link]("Enter a name or phone number to search: ");
String input = [Link]().trim();
// Check both hash tables
if ([Link](input)) {
[Link]("Phone number of " + input + " is: " + [Link](input));
} else if ([Link](input)) {
[Link]("Name corresponding to phone number " + input + " is: " +
[Link](input));
} else {
[Link]("No record found for: " + input);
}
[Link]();
}
}

OutPut:

Enter a name or phone number to search: 9123456780


Name corresponding to phone number 9123456780 is: Bob
Enter a name or phone number to search: 7055493239
No record found for: 7055493239
VIVA QUESTIONS:
1. is a package in which Hashtable class is available
2. split is a method used for
3. capacity of hashtable can be determined by
4. method is used to insert record in to hash table
5. method is used to know the number of entries in hash
table [Link] to hashtable is
7. is used to remove all entries of hash table
8. Hash table can be enumerated using
9. Scanner class is present in
package [Link] Reader is available in
package

PROGRAM -12 :
Producer-Consumer Problem Using Inter-thread Communication

Aim: Write a Java program that correctly implements the producer – consumer
problem using the concept of interthread communication.
THEORY: Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.

Program:
class SharedBuffer {
private int data;
private boolean available = false;

synchronized void produce(int value) {


while (available) try { wait(); } catch (Exception e) {}
data = value;
available = true;
[Link]("Produced: " + value);
notify();
}

synchronized void consume() {


while (!available) try { wait(); } catch (Exception e) {}
[Link]("Consumed: " + data);
available = false;
notify();
}
}

class Producer extends Thread {


SharedBuffer b;
Producer(SharedBuffer b) { this.b = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](i);
try { [Link](500); } catch (Exception e) {}
}
}
}

class Consumer extends Thread {


SharedBuffer b;
Consumer(SharedBuffer b) { this.b = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]();
try { [Link](800); } catch (Exception e) {}
}
}
}

public class ProducerConsumerDemo {


public static void main(String[] args) {
SharedBuffer b = new SharedBuffer();
new Producer(b).start();
new Consumer(b).start();
}
}

OutPut:
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Produced: 5
Consumed: 5
VIVA QUESTIONS
1) What is Thread in Java?
The thread is an independent path of execution. It's way to take advantage of multiple CPU
available in a machine. By employing multiple threads you can speed up CPU bound task. For
example, if one thread takes 100 milliseconds to do a job, you can use 10 thread to reduce that
task into 10 milliseconds. Java provides excellent support for multithreading at the language
level, and it's also one of the strong selling points.

2) What is the difference between Thread and Process in Java?


The thread is a subset of Process, in other words, one process can contain multiple threads. Two
process runs on different memory space, but all threads share same memory space. Don't confuse
this with stack memory, which is different for the different thread and used to store local data to
that thread. For more detail see the answer.

3) How do you implement Thread in Java?


At the language level, there are two ways to implement Thread in Java. An instance
of [Link] represent a thread but it needs a task to execute, which is an instance of
interface [Link]. Since Thread class itself implement Runnable, you can override
run() method either by extending Thread class or just implementing Runnable interface. For
detailed answer and discussion see this article.

4) When to use Runnable vs Thread in Java?


2) This is a follow-up of previous multi-threading interview question. As we know we can
implement thread either by extending Thread class or implementing Runnable interface, the
question arise, which one is better and when to use one? This question will be easy to answer if
you know that Java programming language doesn't support multiple inheritances of class, but it
allows you to implement multiple interfaces. Which means, it's better to implement Runnable
then extends Thread if you also want to extend another class e.g. Canvas or CommandListener.
For more points and discussion you can also refer this post.

6) What is the difference between start() and run() method of Thread class?
One of trick Java question from early days, but still good enough to differentiate between shallow
understanding of Java threading model start() method is used to start newly created thread,

while start() internally calls run() method, there is difference calling run() method directly. When
you invoke run() as normal method, its called in the same thread, no new thread is started, which
is the case when you call start() method. Read this answer for much more detailed discussion.
PROGRAM -13 :

Using File and Directories


Aim: a Java program to list all the files in a directory including the files

present in all its subdirectories.

THEORY: The listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) method of the FileUtils
class of the ApacheSW Commons IOSlibrary returns a Collection of files in a specified directory passed in as
its first parameter. If the third parameter (dirFilter) is null, only the files in the specified directory are returned.
If [Link] is passed in, all of the files within the specified directory are returned, including
all subdirectories

Program:

import [Link];

public class ListFilesRecursively {


public static void main(String[] args) {
// You can change this path or take it from user input
String directoryPath = "C:\\Users\\Lokes\\OneDrive\\Desktop\\java";

File directory = new File(directoryPath);

if ([Link]() && [Link]()) {


[Link]("Listing files in: " + [Link]());
listFiles(directory);
} else {
[Link]("Invalid directory path!");
}
}

// Recursive method to list files and subdirectories


public static void listFiles(File dir) {
File[] files = [Link]();

if (files != null) {
for (File file : files) {
if ([Link]()) {
[Link]("[DIR] " + [Link]());
listFiles(file); // Recursive call for subdirectory
} else {
[Link](" " + [Link]());
}
}
}
}
}

OutPut:
//These are the files which I gave the path

Listing files in: C:\Users\Lokes\OneDrive\Desktop\java


C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\IntegerDivisionGUI$[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]
C:\Users\Lokes\OneDrive\Desktop\java\[Link]

VIVA QUESTIONS:

1. What is a IO stream?
It is a stream of data that flows from source to destination. Good example is file copying. Two
streams are involved – input stream and output stream. An input stream reads from the file and
stores the data in the process (generally in a temporary variable). The output stream reads from
the process and writes to the destination file.
2. What is the necessity of two types of streams – byte streams and character
streams? Byte streams were introduced with JDK 1.0 and operate on the files containing
ASCII characters. We know Java supports other language characters also known as Unicode
characters. To read the files containing Unicode characters, the designers introduced character
streams with JDK 1.1. As ASCII is a subset of Unicode, for the files of English characters, we
can go with either byte streams or character streams.
3. What are the super most classes of all streams?
All the byte stream classes can be divided into two categories (input stream classes and output
stream classes) and all character streams classes into two (reader classes and writer classes).
There are four abstract classes from which all these streams are derived. The super most class of
all byte stream classes is [Link] and for all output stream classes,
[Link]. Similarly for all reader classes is [Link] and for all writer
classes is [Link].
4. What are FileInputStream and FileOutputStream?
These two are general purpose classes used by the programmer very often to copy file to file. These
classes work well with files containing less data of a few thousand bytes as by performance these are
very poor.
For larger data, it is preferred to use BufferedInputStream (or BufferedReader) and
BufferedOutputStream (or BufferedWriter).
5. Which you feel better to use – byte streams or character streams?
I feel personally to go with character streams as they are the latest. Many features exist in
character streams that do not in byte streams like a) using BufferedReader in place of
BufferedInputStreams and DataInputStream (one stream for two) and b) using newLine() method
to go for next line and for this effect we must go for extra coding in byte streams etc.
6. What [Link]()?
"println()" is a method of PrintStream class. "out" is a static object of PrintStream class defined
in "System" class. System is a class from [Link] package used to interact with the underlying
operating system by the programmer.
7. What are filter streams?
Filter streams are a category of IO streams whose responsibility is to add extra functionality
(advantage) to the existing streams like giving line numbers in the destination file that do not exist
int the source file
or increasing performance of copying etc.
8. Name the filter streams available?
There are four filter streams in [Link] package – two in byte streams side and two in character
streams side. They are FilterInputStream, FilterOutputStream, FilterReader and
FilterWriter. These classes are abstract classes and you cannot create of objects of these classes.
9. Name the filter stream classes on reading side of byte stream?
There are four classes – LineNumberInputStream (the extra functionality is it adds line numbers
in the destination file), DataInputStream (contains special methods like readInt(), readDouble()
and readLine() etc that can read an int, a double and a string at a time), BufferedInputStream
(gives buffering effect that increases the performance to the peak) and PushbackInputStream
(pushes the required character back to the system).
10. What is the functionality of SequenceInputStream?
It is very useful to copy multiple source files into one destination file with very less code
Additional programs:
1)Fibonacci Series Using Recursion (Java)
import [Link];

public class FibonacciRecursion {

// Recursive method to return nth Fibonacci number

public static int fib(int n) {

if (n <= 1) {

return n; // Base cases: fib(0)=0, fib(1)=1

}
return fib(n - 1) + fib(n - 2); // Recursive call

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter the number of terms: ");


int n = [Link]();

[Link]("Fibonacci Series using Recursion:");

for (int i = 0; i < n; i++) {

[Link](fib(i) + " ");

[Link]();

}
Enter the number of terms: 7
Fibonacci Series using Recursion:

0112358

2)What Happens When an Exception Occurs?


When a Java program encounters an unexpected error (like dividing by zero, array out of
bounds, file not found, etc.), it throws an exception.

.a) If the Exception is Handled (try-catch)

The program does NOT terminate. It continues running normally.

public class Example1 {


public static void main(String[] args) {
try {
int a = 10 / 0; // This causes exception
} catch (ArithmeticException e) {
[Link]("Exception caught: " + e);
}
[Link]("Program continues...");
}
}

Output:

Exception caught: [Link]: / by zero


Program continues...

b)The program terminates immediately at the line where the exception occurs.

public class Example2 {


public static void main(String[] args) {
int a = 10 / 0; // No try-catch
[Link]("This line will not be executed");
}
}

Output:

Exception in thread "main" [Link]: / by zero


at [Link]([Link])

❌ Program stops right there — no further statements run.

You might also like