JAVA_LAB_MANUAL
JAVA_LAB_MANUAL
Object Oriented
Programming through Java
R22 REGULATION
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.
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.
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. List of Experiments
No.
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)
12 Write a java program that correctly implements the producer-consumer
problem using the concept of inter thread communication
13 Write a java program to list all the files in a directory including files
14 Write a Java program that implements Quick sort algorithm for sorting a list
of names in ascending order
15 Write a Java program that implements Bubble sort algorithm for sorting in
descending order and also shows the number of interchanges occurred for
the given set of integers.
Installation of Java software:
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. Todo
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 Mac) or by clicking
on the "Run" button near the top of the window. Once your program
finishes running, you will be able to see the output of your program by selecting the
"Console tab" at the bottom of the window.
Quitting Eclipse
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.
The Projects window, which contains a tree view of the components of the project,
including source files, libraries that your code depends on, and so on.
The Source Editor window with a file called HelloWorldApp.java open.
The Navigator window, which you can use to quickly navigate between elements
within the selected class.
It may be necessary to add JDK 8 to the IDE's list of available platforms. To do this, choose
Tools | Java Platforms as shown in the following figure:
Selecting the Java Platform Manager from the Tools Menu
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 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 SUCCESSFUL, congratulations! You
have successfully compiled your program!
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:
import
java.util.*;
public class
Testp {
public static void main(String[] args) {
System.out.println("Welcome to KG REDDY Engineering
College"); System.out.println("--------Prime Number ");
Scanner sc = new
Scanner(System.in);
System.out.println("Enter valid
Number");int n = sc.nextInt();
int c = 0;
for (int i = 1; i <= n;
i++) {if (n % i == 0) {
c++;
}
}
if (c == 2) {
System.out.println(n + "is Prime Number");
} else {
System.out.println(n + "is not Prime Number");
}
}
}
Output:
AIM : java program that works as a simple calculator.use a Grid layout to arrange
buttonsfor 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>
*/
int num1,num2,result;
TextField T1;
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
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);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
COMPUTER SCIENCE & ENGINEERING
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
COMPUTER SCIENCE & ENGINEERING
Operation='/';
T1.setText("");
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
catch(ArithmeticException e) {
result=num2;
JOptionPane.showMessageDialog(this,"Divided by zero");
break;
T1.setText(""+result);
if(str.equals("clear")) {
COMPUTER SCIENCE & ENGINEERING
T1.setText("");
Output:
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.*;
public class Sms extends
Applet {public void init() {
}
public void paint(Graphics g) {
g.setColor(Color.blue);
Font font = new Font("verdana", Font.BOLD, 15);
g.setFont(font);
g.drawString("Welcome To KG REDDY Eng College", 50, 50);
}
}
Applet code:
<html>
<body>
</applet>
</body>
</html>
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
asdefined 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:
import
java.applet.Applet;
import java.awt.*;
import
java.awt.event.*;
TextField tf1,
tf2;Button b1;
public void
init() {
setSize(400,
200);
FlowLayout g = new
FlowLayout();setLayout(g);
l1 = new Label("Enter
Value");
l1.setForeground(Color.B
LUE); add(l1);
COMPUTER SCIENCE & ENGINEERING
tf1 = new
TextField(5);
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);
tf2 = new
TextField(5);
add(tf2);
ae) {long n =
Integer.parseInt(tf1.getText());
long f =
1; while
(n != 0) {f
= f * n;
n--;
tf2.setText(String.valueOf(f));
<html>
<body>
</applet>
</body>
</html>
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 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 java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
import javax.swing.event.*;
JTextField tf1,
tf2, tf3;JButton
b1;
A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
l1 = new JLabel("Welcome");
setSize(800, 400);
l1 = new JLabel("Enter
Number1");add(l1);
tf1 = new
JTextField(10);
l2 = new
JLabel("Enter
Number2");add(l2);
tf2 = new
JTextField(10);
add(tf2);
l3 = new
JLabel("Result");
add(l3);
tf3 = new
JTextField(10);
add(tf3);
b1 = new
JButton("Divide");
add(b1);
b1.addActionListener(t
his); setVisible(true);
ae) {try {
int a =
integer.parseInt(tf1.getText());
int b =
Integer.parseInt(tf2.getText());
if(b==0)
Error");float c = (float) a / b;
tf3.setText(String.valueOf(c));
JOptionPane.showMessageDialog(this,
ex.getMessage());
ex.getMessage());
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);
}
}
class A extends
Thread {public
String tname;
public Random r;
public Thread
t1, t2; public
A(String s) {
tname = s;
}
Output:
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;
DoubleLinke
dList()
first=new
node();
first.next=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;
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=pt
r.next;
ptr.next.prev
COMPUTER SCIENCE & ENGINEERING
=temp;
ptr.next=tem
p;
temp.prev=pt
r;
}
}
void del(int p)
node
ptr=first,temp;
for(int i=1;i<=p-
1;i++)
ptr=ptr.next;
if(ptr.next.next=
=null)
temp=l
ast;
last=las
t.prev;
last.nex
t=null;
else
temp=ptr.next;
ptr.next=ptr.next.next;
ptr.next.prev=ptr;
COMPUTER SCIENCE & ENGINEERING
}
temp=null;
void show()
System.out.println("\nList Elements:Left to
Right");for(node
ptr=first.next;ptr!=null;ptr=ptr.next)
System.out.print("\t"+ptr.x);
System.out.println("\nList Elements:Right to
Left");for(node
ptr=last;ptr.prev!=null;ptr=ptr.prev)
System.out.print("\t"+ptr.x);
Class DListTest
String
con="";int
x,op,p,v;
InputStreamReader isr=new
InputStreamReader(System.in);BufferedReader
br=new BufferedReader(isr);
x=Integer.parseInt(br.readLine());
l1.add(x);
System.out.print("Add
more?(y,n):");
con=br.readLine();
}while(con.equals("y"))
l1.show();
do
{
System.out.println("\n 1.Insert\n 2.Delete \n 3.Display \n 4.Exit");
System.out.println("\nSelect an option:");
op=Integer.parseInt(br.readLine());
if(op==1)
System.out.println("Enter
Positiontoinsert:"); p=
Integer.parseInt(br.readLine());
System.out.println("Enter Value to
insert:"); v=
Integer.parseInt(br.readLine());
l1.insert(p,v);
if(op==2)
System.out.println("Enter
Positiontodelete:"); p=
l1.del(p);
l1.show();
}while(op<4)
}
Output:
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_CL
OSE);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(thi
s);
JRadioButton r2 = new JRadioButton("Yellow Light");
r2.setBackground(Color.YELLOW);
p1.add(r2);
r2.addItemListener(thi
s);
JRadioButton r3 = new JRadioButton("Green Light");
r3.setBackground(Color.GREEN);
p1.add(r3);
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:
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(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(0, 3);
setLay
out(g);
try {
FileInputStream fin = new FileInputStream("D:\\emp.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));
}
}
} catch (Exception ex) {
}
setDefaultLookAndFeelDecorated(tr
ue);pack();
setVisible(true);
}
}
public class Tbl {
public static void main(String[]
args) {A a = new A();
}
Output:
Theory : To handle mouse events you must implement the MouseListener and the
MouseMotionListener interfaces.These two interfaces contain methods that receive and
process the various types of mouse events.
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) {A a = new A();
COMPUTER SCIENCE & ENGINEERING
}
}
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("D:\\ph.txt");
Scanner sc = newScanner(fs).useDelimiter("\\s+");
Hashtable<String, String> ht = new Hashtable<String,
String>();String[] arrayList;
String a;
System.out.println("Welcome TO KG REDDY 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("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
System.out.println("Welcome TO KG REDDY 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();
switch
(opt) {case
"1": {
System.out.println("Enter
Name");name = s.next();
if (ht.containsKey(name)) {
System.out.println("Mobile is " +
ht.get(name));
COMPUTER SCIENCE & ENGINEERING
}
else {
System.out.println("Not Found");
}
}
break;
case "2":
{
System.out.println("Enter
mobile");mobile = s.next();
if (ht.containsValue(mobile))
{ for (Map.Entry e : ht.entrySet())
{if
(mobile.equals(e.getValue())
) {
System.out.println("Name is " + e.getKey());
}
}
} else {
System.out.println("Not Found");
}
}
break;
case "3": {
opt = "3";
System.out.println("Menu Successfully Exited");
}
break;
default:
System.out.println("Choose Option betwen 1 and Three");
break;
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage()
);
}
}
}
Output:
Program:
class Q
{
int n;
boolean
valueSet=false;
synchronized int
get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
class ProdCons
{
public static void main(String[] args)
{
Q q=new
Q(); new
Producer(q);
new
Consumer(q
);
System.out.println("Press Control-c to stop");
}
}
Output:
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;
System.out.println(file.getName());
if(file.isFile())
{
System.out.println(file.getName());
if
(file.isDirectory())
{ System.out.println(file.getName());
if (file.isFile()){ System.out.println(file.getAbsolutePath());
listFilesUtil.listFiles(directoryLinuxMac);
Output:
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 :
public class
MyQuickSort {private
int array[];
return;
this.array = inputArr;
length = inputArr.length;
int j = higherIndex;
lowerIndex)/2];while (i <= j) {
{i++;
{j--;
i++;
j--;
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
array[i] = array[j];
array[j] = temp;
sorter.sort(input);
for(int i:input){
System.out.print(" ");
Output:
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:
65