Ii-I Java Lab Manual R22
Ii-I Java Lab Manual R22
OBJECT ORIENTED
PROGRAMMING THROUGH JAVA
LAB MANUAL
Prepared By
Mrs. Geetha
Bhavani
Assistant Professor
Department of CSE
1. Vision & Mission of the Department
To achieve value oriented and quality education with excellent standards on par with evolving technologies
and produce technocrats of global standards with capabilities of facing futuristic challenges.
M1: To enrich advanced knowledge among students for reinforcing the domain knowledge and develop
capabilities and skills to solve complex engineering problems.
M2: To impart value based professional education for a challenging career in Computer Science and
Engineering.
M3: To transform the graduates for contributing to the socio-economic development and welfare of the
society through value based education
PEO2: To inculcate the capabilities to analyze, design and develop innovative solutions of computer
support systems for benefits of the society, by diligence and teamwork.
PO1: Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals
and an engineering specialization to the solution of complex engineering problems
PO2: Problem Analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences and
Engineering sciences.
PO3: Design/Development of Solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health safety, and the cultural, societal, and environmental considerations.
PO4: Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5: Modern Tool Usage: Create, select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6: The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7: Environment and Sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO9: Individual and Team Work: Function effectively as an individual and as a member or leader in
diverse teams and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as being able to comprehend and write effective reports and
design documentation, make effective presentations and give and receive clear instructions.
PO11: Project Management and Finance: Demonstrate knowledge and understanding of the engineering
management principles and apply these to one's own work, as a member and leader in a team to manage
projects and in multidisciplinary environments.
PO12: Life-Long Learning: Recognize the need for and have the preparation and ability to engage in
independent and lifelong learning in the broadest context of technological change.
PSO1: Software Development: Ability to grasp the software development life cycle of software systems
and possess competent skill and knowledge of software design process.
PSO2: Industrial Skills Ability: Ability to interpret fundamental concepts and methodology of computer
systems so that students can understand the functionality of hardware and software aspects of computer
systems.
PSO3: Ethical and Social Responsibility: Communicate effectively in both verbal and written form, will
have knowledge of professional and ethical responsibilities and will show the understanding of impact of
engineering solutions on the society and also will be aware of contemporary issues.
4. Course Objectives:
To write programs using abstract classes.
To write programs for solving real world problems using java collection frame work.
To write multithreaded programs.
To write GUI programs using swing controls in Java. To introduce java compiler and eclipse
platform
5. Course Outcomes:
Able to write programs for solving real world problems using java collection frame
work.
Able to write programs using abstract classes.
Able to write multithreaded programs.
Able to write GUI programs using swing controls in Java
OBJECT ORIENTED PROGRAMMING THROUGH
JAVA
List of Experiments
INDEX
S. No. List of Experiments
1 Use Eclipse or Netbean platform and acquaint with the various menus. Create a test
project, and 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.
2 Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field to
display the result. Handle any possible exceptions like divided by zero.
3 Develop an applet that displays a simple message.
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
4 Write a program that creates a user interface to perform integer divisions. The user
enters 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 a
NumberFormatException. If Num2 were Zero, the program would throw an
ArithmeticException. Display the exception in a message dialog box.
5 Write a Java program that implements a multi-thread application that has three
threads. First thread generates 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
6 Write a java program for the following: i)create a doubly linked list of elements
ii)Delete a given elements from above list iii)Display the contents of list after
deletion
7 Write a Java Program that simulates a Traffic Light. The program lets the use select
one of three lights :red, yellow Green with radiobuttons.On selecting radio button,
an appropriate message with “stop” or “Ready” or “GO” should appear above the
button in selected color.Intially, there is no message shown
8 Write a java program to create an abstract class named Shape that contains two
integers 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 classes contains only the method printArea() that prints the
area of the given shape
9 Suppose that a table named Table.txt is stored in a text file. The first line in the file
is 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 Labels in
Grid Layout
10 Write a Java program that handles all mouse events and shows the event name at
the center of the window when a mouse event is fired (Use Adapter classes)
11 Write a Java program that loads names and phone numbers from a text file where
the data is organized as one line per record and each field in a record are separated
by a tab (\t). It takes a name or phone number as input and prints the corresponding
other value from the hash table (hint: use hash tables)
Steps:
Environment Variables
PATH:
CLASSPATH:
This environment variable will help the jvm to find the runtime environment of java
i.e. all predefined classes and interfaces can be located using this variable. The
location for runtime environment is JRE folder.
1) Use Eclipse or Net bean platform and acquaint with the various menus. Create a
test project, 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.
Aim: To create and test java projects in Eclipse and Netbean platform
Initializing Eclipse : When you develop Java applications in Eclipse, it stores all
the created files in a directory called "workspace". When Eclipse is run for the first
time, it will ask you where you want the workspace to be placed:
You can just use the default location or specify your preferred location. To
avoid getting asked this question every time you start Eclipse, check "Use this
as the default and do not ask again" option and press "OK" button. Once
Eclipse finishes its startup process, you
Will see the following welcome window:
Click the "Workbench" icon on the right, which will lead you to the main Eclipse window:
Creating a Project
Now that you've got Eclipse up and running, it's time to create your first Java
project. To do this, you'll want to go File -> New -> Java Project. After doing so,
you'll see a window like the following:
Type your project name (say, cs144project1) in the "Project name" field and click
Finish. Then the name of your newly created project will appear on the left side of
the Eclipse window (this part of the window is called "Package explorer pane"):
As you create more projects in Eclipse, other project names will appear in the
Package explorer pane and you will be able to switch between your projects by
clicking the name of a project.
Adding a New File to a Project : Now that you've created your first project, you now
want to create a new Java file (with .java extension) and add it into your project. To
create a new Java file, right click on the name of your project (cs144project1) in the
Package explorer pane and select New -> Class as follows:
This command will show you a window that looks like the following:
In the "Name: " section provide the name of the file (or the class) you want to
create, HelloWorld, and click "Finish" button.
Congratulations! Now you have created your first Java code in eclipse. As you
can see from the Package explore pane, your project now includes
HelloWorld.java file. The "Editor pane" to the right of the Package explorer
pane shows the actual content of the HelloWorld.java file, which simply
declares HelloWorld as a public class. You can edit the content of the Java
code inside the Editor pane.
Now let us learn how to code, compile and run a Java program in Eclipse.
First copy and paste the following method into the HelloWorld class
definition:
Now that your code has been saved and compiled, you can run your
program by selecting Run -> Run, or by pressing Ctrl-F11 (Option-F11 on
Now you have learned the very basic functionality of Eclipse. Eclipse
supports many more functionalities than what you just learned,
including integrated debugging and automatic code completion and
method lookup, etc. Please read online Eclipse manual to learn more
about Eclipse.
Netbeans
1. NetBeans IDE with the File | New Project menu item selected.
2. In the New Project wizard, expand the Java category and select Java
Application as shown in the following figure:
1. NetBeans IDE, New Project wizard, Choose Project page.
2. In the Name and Location page of the wizard, do the following (as shown in the
figure below):
o In the Project Name field, type Hello World App.
o In the Create Main Class field, type helloworldapp.HelloWorldApp.
If you don't see JDK 8 (which might appear as 1.8 or 1.8.0) in the list of
installed platforms, click Add Platform, navigate to your JDK 8 install
directory, and click Finish. You should now see this newly added platform:
To set this JDK as the default for all projects, you can run the IDE with the --
jdkhome switch on the command line, or by entering the path to the JDK in
the netbeans_j2sdkhome property of
your INSTALLATION_DIRECTORY/etc/netbeans.conf file.
To specify this JDK for the current project only, select Hello World App in the Projects
pane, choose File | Project Properties (Hello World App), click Libraries, then select JDK 1.8
in the Java Platform pulldown menu. You should see a screen similar to the following:
When you created this project, you left the Create Main Class checkbox
selected in the New Project wizard. The IDE has therefore created a skeleton
class for you. You can add the "Hello World!" message to the skeleton code by
replacing the line:
/**
* The HelloWorldApp class implements an applicationthat
* simply prints "Hello World!" to standard output.
*/
These four lines are a code comment and do not affect how the program runs.
Later sections of this tutorial explain the use and format of codecomments.
Note: Type all code, commands, and file names exactly as shown. Both the
compiler (javac) and launcher (java) arecase-sensitive, so you must capitalize
consistently.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworldapp;
/**
* The HelloWorldApp class implements an applicationthat
* simply prints "Hello World!" to standard output.
*/
public class HelloWorldApp {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println("Hello World!"); // Display the
string.
}
}
Compile the Source File into a .class File
To compile your source file, choose Run | Build Project (Hello World App) from the IDE's
main menu.
The Output window opens and displays output similar to what you see in the
following figure:
If the build output concludes with the statement BUILD FAILED, you probably
have a syntax error in your code. Errors are reported in the Output window as
hyperlinked text. You double-click such a hyperlink to navigate to the source of
an error. You can then fix the error and once again choose Run | Build
Project.
When you build the project, the bytecode file HelloWorldApp.class is generated.
You can see where the new file is generated by opening the Files window and
expanding
the Hello World App/build/classes/helloworldapp node as shown in the following
figure.
Now that you have built the project, you can run your program.
From the IDE's menu bar, choose Run | Run Main Project. The
The program prints "Hello World!" to the Output window (along with other
output from the build script).
Congratulations! Your program works!
The next few pages of the tutorial will explain the code in this simple
application. After that, he lessons go deeper into core language features and
provide many more examples.
Although the rest of the tutorial does not give specific instructions about using
the NetBeans IDE, you can easily use the IDE to write and run the sample code.
The following are some tips on using the IDE and explanations of some IDE
behavior that you are likely to see:
Once you have created a project in the IDE, you can add files to the
project using the New File wizard. Choose File | New File, and then
select a template in the wizard, such as the Empty Java File template.
You can compile and run an individual file (as opposed to a whole project)
using the IDE's Compile File (F9) and Run File(Shift-F6) commands. If
you use the Run Main Project command, the IDE will run the file that
the IDE associates as the main class of the main project. Therefore, if
you create an additional class in your HelloWorldApp project and then try
to run that file with the Run Main Project command, the IDE will run
the HelloWorldApp file instead.
You might want to create separate IDE projects for sample applications
that include more than one source file.
As you are typing in the IDE, a code completion box might periodically
appear. You can either ignore the code completion box and keep typing, or
you can select one of the suggested expressions. If you would prefer not to
have the code completion box automatically appear, you can turn off
the feature. Choose Tools | Options | Editor, click the Code
Completion tab and clear the Auto Popup Completion Window
checkbox.
If you want to rename the node for a source file in the Projects window,
choose Refactor from IDE's main menu. The IDE prompts you
with the Rename dialog box to lead you through the options of renaming
the class and the updating of code that refers to that class. Make the
changes and click Refactor to apply the changes. This sequence of
clicks might seem unnecessary if you have just a single class in your
project, but it is veryuseful when your changes affect other parts of your
code in larger projects.
Program:
Output:
C:\Users\vmtw\Desktop\javaprog>javac TestPrime.java
C:\Users\vmtw\Desktop\javaprog>java TestPrime
C:\Users\vmtw\Desktop\javaprog>java TestPrime
AIM : java program that works as a simple calculator.use a Grid layout to arrange
buttons for the digits and for the + - * %operations. Add a text field to display the
result.
Program:
/* Program to create a Simple Calculator */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
Theory: Applets are designed to bring the web alive. they function to add animation
sound and eventually complete multi media into HTML documents.java is also part
of the future of interfacing with virtual-reality environments implemented via
VRML.At present ,java is limited only by the capabilities of the internet itself.applets
are java programs that are specialized for use over the Web.
Program:
import java.applet.Applet;
import java.awt.*;
/*
<html>
<body>
</applet>
</body>
</html>
*/
g.setColor(Color.blue);
g.setFont(font);
Output:
Aim : Develop an applet which receives an integer in one text field, and computes
its factorial Value and returns it in another text field.
Theory: Applets are designed to bring the web alive.they function to add animation
sound and eventually complete multi media into HTML documents.java is also part of
the future of interfacing with virtual-reality environments implemented via VRML.At
present ,java is limited only by the capabilities of the internet itself.applets are java
programs that are specialized for use over the Web. The Applet life cycle
The init()Method: The init()method is where your applet does much of its setup,such
as defined its layout,parsing parameters,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:
/*
<html>
<body>
</applet>
</body>
</html>
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
Button b1;
setSize(400, 200);
COMPUTER SCIENCE &
ENGINEERING
FlowLayout g = new FlowLayout();
setLayout(g);
l1.setForeground(Color.BLUE);
add(l1);
tf1.setText("0");
add(tf1);
b1 = new Button("Compute");
b1.addActionListener(this);
add(b1);
l3 = new Label();
add(l3);
l2.setForeground(Color.BLUE);
add(l2);
add(tf2);
ae)
long n = Integer.parseInt(tf1.getText());
long f = 1;
while (n != 0)
f = f * n;
n--;
tf2.setText(String.valueOf(f));
Output:
Aim : Program to create a user interface to perform integer divisions. The user enters
two numbers in the textfields, 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 a NumberFormatException. If Num2 were
Zero, the program would throw an ArithmeticException. 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,0 cordinates are specified in pixels. All output to a window takes
place through a graphics context.
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
JButton b1;
A()
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
l1 = new JLabel("Welcome");
setSize(800, 400);
add(l1);
add(l2);
add(tf2);
l3 = new JLabel("Result");
add(l3);
add(tf3);
b1 = new JButton("Divide");
add(b1);
b1.addActionListener(this);
setVisible(true);
try
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
if(b==0)
float c = (float) a / b;
tf3.setText(String.valueOf(c));
catch(NumberFormatException ex)
JOptionPane.showMessageDialog(this, ex.getMessage());
catch(ArithmeticException ex)
JOptionPane.showMessageDialog(this, ex.getMessage());
COMPUTER SCIENCE &
ENGINEERING
}
A a = new A();
Output:
Aim : Creating a Java program that implements a multi-thread application that has three threads.
First thread generates 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 ajava program,only the single thread that is blocked pauses.All other threads continue to
run.
Program:
import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Thread Name:Even Thread and " + x + "is even Number and
Square of "+ x + " is: " + x * x);
}
}
class odd implements Runnable
{
public int x;
public odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Thread Name:ODD Thread and " + x + " is odd number and
Cube of " + x + " is: " + x * x * x);
}
C:\Users\vmtw\Desktop\javaprog>javac MThread1.java
C:\Users\vmtw\Desktop\javaprog>java MThread1
Main Thread and Generated Number is 47
Thread Name:ODD Thread and 47 is odd number and Cube of 47 is: 103823
Aim : create a program in which doubly linked list operations can be shown in detail.
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.
Program:
import java.io.*;
class node
{
public int x;
public node next;
public node prev;
}
class DoubleLinkedList
{
public node first;
public node last;
DoubleLinkedList()
{
first=new node();
first.next=null;
first.prev=null; last=first;
}
void add (int v)
{
node temp=new node();
temp.x=v;
temp.next=null;
last.next=temp;
temp.prev=last; last=temp;
}
void insert(int p,int v)
{
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
if(ptr.next==null)
add(v);
else
{
temp=new node();
temp.x=v;
temp.next=ptr.next;
ptr.next.prev=temp;
ptr.next=temp;
temp.prev=ptr;
}
}
Output:
C:\Users\vmtw\Desktop\javaprog>javac DListTest.java
C:\Users\vmtw\Desktop\javaprog>java DListTest
Enter elements to create
5
Add more?(y,n):y
2
Add more?(y,n):y
1
Add more?(y,n):y
3
Add more?(y,n):y
4
Add more?(y,n):n
Select an option:
3
Aim: write a java program that simulates trafficlight the program let user select one
of three lights ,thread yellowor green .when a radio button is select the light is turn
ed one light can be on at atime. No lights is on when the program starts.
Theory: The AWT supports a rich assortment of graphics methods.All graphics are
drawn relative to a window.this 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,0 cordinates are specified in pixels.All output to a window takes place
through a graphics context.
Program:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ItemListener
{
public JLabel l1, l2;
public JRadioButton r1, r2, r3;
public ButtonGroup bg;
public JPanel p, p1;
public A()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 1));
setSize(800, 400);
p = new JPanel(new FlowLayout());
p1 = new JPanel(new FlowLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 60);
l1.setFont(f);
add(l1);
p.add(l1);
add(p);
l2 = new JLabel("Select Lights");
p1.add(l2);
JRadioButton r1 = new JRadioButton("Red Light");
r1.setBackground(Color.red);
p1.add(r1);
r1.addItemListener(this);
JRadioButton r2 = new JRadioButton("Yellow Light");
r2.setBackground(Color.YELLOW);
p1.add(r2);
r2.addItemListener(this);
JRadioButton r3 = new JRadioButton("Green Light");
r3.setBackground(Color.GREEN);
p1.add(r3);
r3.addItemListener(this);
Aim: Write a java program to create an abstract class that illustrates different
geometrical figures.
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:
Output:
C:\Users\vmtw\Desktop\javaprog>javac Abstex.java
C:\Users\vmtw\Desktop\javaprog>java Abstex
Area of Circle is 12
Aim: Write a java program to display the table using Grid Layout component
Program:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class A extends JFrame
{
public A()
{
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(0, 3);
setLayout(g);
try {
FileInputStream fin = new FileInputStream("grid.txt");
Scanner sc = new Scanner(fin).useDelimiter(",");
String[] arrayList;
String a;
while (sc.hasNextLine())
{
a = sc.nextLine();
arrayList = a.split(",");
for (String i : arrayList)
{
add(new JLabel(i));
}
Output:
10. Write a Java Program that handles all mouse events and show event name at the cen-
ter of the window when the mouse event is fired.(Use Adapter Classes)
Program:
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class A extends JFrame implements MouseListener
{
JLabel l1;
public A()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new GridBagLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
l1.setAlignmentX(Component.CENTER_ALIGNMENT);
l1.setAlignmentY(Component.CENTER_ALIGNMENT);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
}
public class Mevents
{
public static void main(String[] args)
Output:
Aim: Write a java program which can read text file into hash table and print the hash
values based on the hash key input.
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:
import java.util.*;
import java.io.*;
public class Hashtbl
{
public static void main(String[] args)
{
try
{
FileInputStream fs = new
FileInputStream("grid.txt");
Scanner sc = new
Scanner(fs).useDelimiter(",");
Hashtable<String, String> ht = new
Hashtable<String, String>();
String[] arrayList;
String a;
System.out.println("Welcome TO VMTW
Eng College");
System.out.println("HASH TABLE IS");
System.out.println(" ");
System.out.println("KEY : VALUE");
while (sc.hasNext())
{
a = sc.nextLine();
arrayList = a.split(",");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" +
arrayList[1]);
}
System.out.println("Welcome TO VMTW
Eng College");
System.out.println("----MENU ");
System.out.println("----1.Search by Name
");
System.out.println("----2.Search by Mobile
");
System.out.println("----3.Exit ");
String opt = ""; String name, mobile;
Scanner s = new Scanner(System.in);
while (opt != "3") {
System.out.println("Enter Your Option
1,2,3"); opt = s.next();
C:\Users\vmtw\Desktop\javaprog>javac Hashtbl.java
C:\Users\vmtw\Desktop\javaprog>java Hashtbl
HASH TABLE IS
KEY : VALUE
RAJU:9848222067
DRCSK:9849715531
KRISHNA:9848222068
Program:
class Q
{
int n;
boolean valueSet=false; synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
C:\Users\vmtw\Desktop\javaprog>javac ProdCons.java
C:\Users\vmtw\Desktop\javaprog>java ProdCons
Press Control-c to stop
Put:0
Got:0
Put:1
Got:1
Put:2
Got:2
Put:3
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Put:9
Got:9
Put:10
Got:10
13. Write a Java program to list all the files in a directory including the files present in all its
subdirectories.
Theory : Java provides a standard way of reading from and writing to files.
Traditionally thejava.io package was used, but in modern Java
applications you use the java.nio.fileAPI. Java will read all input as a stream of
bytes. The InputStream class is the superclass of all classes representing an input
stream of bytes.
Program:
import java.io.*;
import java.lang.*;
import java.io.File;
public class ListFilesUtil
{
public void listFilesAndFolders(String directoryName)
{
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList){
System.out.println(file.getName());
}
}
public void listFiles(String directoryName)
{
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList)
{
if(file.isFile())
{
System.out.println(file.getName());
}
}
}
public void listFolders(String directoryName)
{
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList)
{
if(file.isDirectory())
COMPUTER SCIENCE &
ENGINEERING
{
System.out.println(file.getName());
}
}
}
public void listFilesAndFilesSubDirectories(String directoryName)
{
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList)
{
if(file.isFile())
{
System.out.println(file.getAbsolutePath());
}
else if(file.isDirectory())
{
listFilesAndFilesSubDirectories(file.getAbsolutePath());
}
}
}
public static void main(String[] args)
{
ListFilesUtil listFilesUtil=new ListFilesUtil();
final String directoryWindows="C://Users/vmtw/Desktop";
System.out.println("Files in the given Path ie., Desktop\n");
listFilesUtil.listFiles(directoryWindows);
System.out.println("\nFolders in the given Path ie.,Desktop\n");
listFilesUtil.listFolders(directoryWindows);
}
}
Output:
C:\Users\vmtw\Desktop\javaprog>javac ListFilesUtil.java
C:\Users\vmtw\Desktop\javaprog>java ListFilesUtil
6.5.2.xlsx
desktop.ini
Person 1 - Chrome.lnk
screenshot related to licencse expiry.jpg
Theory : Quicksort is a Divide and Conquer algorithm. It picks an element as pivot and
partitions the given array around the picked pivot. There are many different versions of
quicksort that pick pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.
Program :
Output:
C:\Users\vmtw\Desktop\javaprog>javac MyQuickSort.java
C:\Users\vmtw\Desktop\javaprog>java MyQuickSort
1 2 12 20 24 45 53 56 56 75 99
Theory : Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.
Program:
import java.util.Scanner;
class BubbleSort {
public static void main(String []args)
{ int num, i, j, temp;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of integers to sort:");
num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter " + num + " integers: ");
for (i = 0; i < num; i++)
array[i] = input.nextInt();
for (i = 0; i < ( num - 1 ); i++)
{
for (j = 0; j < num - i - 1; j++)
{ if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < num; i++)
System.out.println(array[i]);
}
}
Output:
C:\Users\vmtw\Desktop\javaprog>javac BubbleSort.java
C:\Users\vmtw\Desktop\javaprog>java BubbleSort
Enter the number of integers to sort:
5
Enter 5 integers: 5 1 4 2 3
Sorted list of integers:
5
4
3
2
66
1
67