Java Lab Programmes
Java 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.
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:
VIVA QUESTIONS:
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);
// 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"
};
add(panel, [Link]);
setVisible(true);
}
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]("");
}
}
Output:
Viva questions:
[Link] is object cloning?
This method is used to get the primitive data type of a certain String.
[Link] consists of three classes − Pattern class, Matcher class and PatternSyntaxException class.
If a subclass provides a specific implementation of a method that is already provided by its parent class, it is
known as Method Overriding.
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.
These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double,
Boolean etc.
PROGRAM -3(a)
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>
PROGRAM -3(b)
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:
[Link]
import [Link];
import [Link].*;
import [Link].*;
public class FactorialApplet extends Applet implements ActionListener {
TextField inputField, resultField;
Button computeButton;
OutPut:
VIVA QUESTIONS:
► 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.
All the applets on a given page share the same AppletContext. We obtain this applet context as
follows:
AppletContext ac = getAppletContext();
Forwarding the exception object to the invoking method is known as exception propagation.
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 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:");
if (num2 == 0) {
throw new ArithmeticException("Division by zero");
}
setVisible(true);
}
OutPut:
VIVA QUESTIONS:
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?
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.
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at compile-
time.
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.
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];
while (true) {
if (num % 2 == 0) {
new SquareThread(num).start();
} else {
new CubeThread(num).start();
try {
[Link](e);
}
}
int number;
SquareThread(int num) {
[Link] = num;
int number;
CubeThread(int num) {
[Link] = num;
[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.
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.
// Node class
class Node {
int data;
Node prev;
Node next;
Node(int data) {
[Link] = data;
[Link] = null;
[Link] = null;
// Insert at end
if (head == null) {
head = newNode;
return;
temp = [Link];
}
[Link] = newNode;
[Link] = temp;
// Display forward
temp = [Link];
}
[Link]();
// Display backward
// Go to last node
temp = [Link];
// Print in reverse
while (temp != null) {
[Link]([Link] + " ");
temp = [Link];
[Link]();
// Insert elements
[Link](10);
[Link](20);
[Link](30);
[Link](40);
// Display
[Link]();
[Link]();
Output:
Doubly Linked List (Forward): 10 20 30 40
Program:
class DoublyLinkedList {
// Node class
class Node {
int data;
Node prev;
Node next;
Node(int data) {
[Link] = data;
[Link] = null;
[Link] = null;
// Insert at end
if (head == null) {
head = newNode;
return;
}
temp = [Link];
[Link] = newNode;
[Link] = temp;
}
// Delete a node with given value
[Link]("List is empty!");
return;
if ([Link] == key) {
head = [Link];
return;
temp = [Link];
if (temp == null) {
return;
}
// Unlinking the node
// Display forward
temp = [Link];
[Link]();
// Insert elements
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]();
// Delete element
[Link](30);
[Link]();
Output:
Doubly Linked List (Forward): 10 20 30 40
Deleted: 30
class DoublyLinkedList {
class Node {
int data;
Node prev;
Node next;
Node(int data) {
[Link] = data;
[Link] = null;
[Link] = null;
// Insert at end
if (head == null) {
head = newNode;
return;
temp = [Link];
[Link] = newNode;
[Link] = temp;
[Link]("List is empty!");
return;
}
if ([Link] == key) {
head = [Link];
return;
temp = [Link];
}
if (temp == null) {
return;
if (head == null) {
[Link]("List is empty!");
return;
temp = [Link];
[Link]();
}
// Insert elements
[Link](10);
[Link](20);
[Link](30);
[Link](40);
// Display initial list
[Link]("Before Deletion:");
[Link]();
// Delete element
[Link](30);
[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 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).
4. How many types of Linked lists are there? Singly linked list, doubly linked list, multiply linked list, Circular
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
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
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.
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:
import [Link].*;
import [Link].*;
import [Link].*;
public TrafficLightSimulator() {
// Set up the frame
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(messageLabel, [Link]);
[Link](new FlowLayout());
// Create buttons
[Link](this);
[Link](this);
[Link](this);
// Add buttons to panel
[Link](redButton);
[Link](yellowButton);
[Link](greenButton);
add(buttonPanel, [Link]);
// Set visible
setVisible(true);
if ([Link]() == redButton) {
[Link]("Stop");
[Link]([Link]);
[Link]("Ready");
[Link]([Link]);
[Link]("Go");
[Link]([Link]());
}
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?
Set contains values only whereas Map contains key and values both.
HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be
iterated but HashMap need to convert into Set to be iterated.
If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.
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.
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:
// 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);
}
}
[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.
Abstraction hides the implementation details whereas encapsulation wraps code and data into a
single unit.
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.
No, if there is any abstract method in a class, that class must be abstract.
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.
No, because methods of an interface is abstract by default, and static and abstract keywords can't
be used together.
An interface that have no data member and method is known as a marker [Link] example
Serializable, Cloneable etc.
PROGRAM -9 :
// after saved above file now you can write a program and execute it
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
[Link]();
[Link](null);
[Link](true);
}
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 MouseEventDemo() {
setTitle("Mouse Event Demo (Adapter Classes)");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
@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]();
}
});
@Override
public void mouseMoved(MouseEvent e) {
eventText = "Mouse Moved";
[Link]();
}
});
setVisible(true);
}
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 :
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:
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;
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.
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 :
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];
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
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];
if (n <= 1) {
}
return fib(n - 1) + fib(n - 2); // Recursive call
[Link]();
}
Enter the number of terms: 7
Fibonacci Series using Recursion:
0112358
Output:
b)The program terminates immediately at the line where the exception occurs.
Output: