0% found this document useful (0 votes)
4 views

Java Programming Manual

Uploaded by

Vinnu vinayak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Programming Manual

Uploaded by

Vinnu vinayak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

OBJECTIVES:

● To teach the students basics of JAVA programs and its execution

● To teach the students the differences between C++ and JAVA programming

● To make the students learn concepts like packages and interfaces

● To make the students understand life cycle of the applets and its functionality

● To make the students understand the usage util package

● To teach the student, to develop java programs using interfaces

Recommended System/Software Requirements:

● Intel based desktop PC with minimum of 2.6GHZ or faster processor with at least 256

MB RAM and 40 GB free disk space.

● Operating system: Flavor of any WINDOWS

● Software: jdk1.7

● Linux and MySQL

● Eclipse or Netbean

1
Installation of Java software: Steps:

1. Download JDK7.0 from www.java.sun.com/downloads


2. Install JDK by double clicking on setup file
3. Follow the installation wizard.
4. Upon successful installation the default location where java is installed is C:\Program Files\
Java directory.
5. To compile a java class we have to use javac (java compiler)
6. To execute java program we have to use jvm (java virtual machine).
7. To use javac and jvm we have to configure environment variables.

Environment Variables PATH:

⮚ This environment variable is to locate the compiler.

⮚ Right click MYCOMPUTER and find a properties tab, Click on Properties

Tab and find Advanced Tab, Click on it to see environment variables.

⮚ In this create a new environment variable called PATH and copy the

Location of java compiler as value to it. Default location: $PATH = C:\


Program Files\Java\Jdk1.6.0\bin; 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

2
location for runtime environment is JRE folder. $CLASSPATH= C:\
Program Files\Java\jre\bin;

INDEX

S.No Week Name of the Experiment Page.No


No

1 1 Use Eclipse or Netbeans platform and acquaint with the Various 5


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 2 Write a Java program that works as a simple calculator. Use a 22


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 3 Develop an applet that displays a simple message 28

4 4 Develop an applet that receives an integer in one text field, and 29


computes its factorial Value and returns it in another text field,
when the button named “Compute” is clicked

5 5 Write a program that creates a user interface to perform integer 31


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

3
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.

6 6 Write a Java program that implements a multi-thread application 34


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.

7 7 Write a Java program for the following: 37

i) Create a doubly linked list of elements.

ii) Delete a given element from the above list.

iii) Display the contents of the list after deletion.

8 8 Write a Java program that simulates a traffic light. The program 40


lets the user select one of three lights: red, yellow, appropriate
message with “Stop” or “Ready” or “Go” should appear above
the buttons in selected color. Initiall there is no message shown.

9 8 Write a java program to create an abstract class named Shape that 44


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

10 10 Suppose that a table named Table.txt is stored in a text file. The 47


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

11 11 Write a Java program that handles all mouse events and shows 50
the event name at the center of the window when mouse event is
fired (Use Adapter classes)

12 12 Write a Java program that loads names and phone numbers from 54
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)
4
13 13 Write a Java program that correctly implements the producer – 58
consumer problem using the concept of interthread
communication.

14 14 Write a Java program to list all the files in a directory including 62


the files present in all its subdirectories.

15 15 Write a Java program that implements Quick sort algorithm for 64


sorting a list of names in ascending order

16 16 Write a Java program that implements Bubble sort algorithm for 66


sorting in descending order and also shows the number of
interchanges occurred for the given set of integers.

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,

5
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.

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:

6
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:

7
8
Type your project name (say, UNIT) 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:

9
This command will show you a window that looks like the following:

10
In the "Name: " section provide the name of the file (or the class) you want to create,
HelloWorld, and click "Finish" button.

11
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.

Saving, compiling, and running Java code

12
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:
public static void main(String[] args) {

System.out.println("Hello world!");}

Now save the file by selecting File->Save, or pressing Ctrl-S (Option-S on Mac). When you
save a Java file, Eclipse will automatically compile the file also, so that you don't need to
compile it later when you want to run it.
13
. 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

14
Quitting Eclipse

You can exit eclipse by using any of the following alternatives:


15
 Hit the X in the upper right corner
 Select File -> Exit
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.

16
Netbeans
Create an IDE Project

To create an IDE project:

1. Launch the NetBeans IDE.

o On Microsoft Windows systems, you can use the NetBeans IDE item in
the Start menu.

o On Solaris OS and Linux systems, you execute the IDE launcher script by

navigating to the IDE's bin directory and typing ./netbeans.

o On Mac OS X systems, click the NetBeans IDE application icon.

2. In the NetBeans IDE, choose File | New Project....

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:
3. NetBeans IDE, New Project wizard, Choose Project page.

4. In the Name and Location page of the wizard, do the following (as shown in the
figure below):
● In the Project Name field, type Hello World App.
In the Create Main Class field, type helloworldapp.HelloWorldApp.

17
1. NetBeans IDE, New Project wizard, Name and Location page.

2. Click Finish.

The project is created and opened in the IDE. You should see the following components:

 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.

 NetBeans IDE with the HelloWorldApp project open.

Add JDK 8 to the Platform List (if necessary)

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:

18
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:

The Java Platform Manager

19
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:

The IDE is now configured for JDK 8.

Add Code to the Generated Source File

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:

// TODO code application logic here


System.out.println("Hello World!"); // Display the string.
Optionally, you can replace these four lines of generated code:
//**
*
20
* @author
*/
/**
* The HelloWorldApp class implements an application that

* 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 code comments.

Be Careful When You Type

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.

HelloWorldApp is not the same as helloworldapp.

Save your changes by choosing File | Save.

The file should look something like the following:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.

*/
package helloworldapp;

/**
* The HelloWorldApp class implements an application that

* 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

21
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:

Output window showing results of building the HelloWorld project.

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.

22
Files window, showing the generated .class file.
Now that you have built the project, you can run your program.
Run the Program
From the IDE's menu bar, choose Run | Run Main Project.
The next figure shows what you should now see.

23
The program prints "Hello World!" to the Output window (along with other output from the
build script).
Congratulations! Your program works!
Continuing the Tutorial with the NetBeans IDE
The next few pages of the tutorial will explain the code in this simple application. After
that, the 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

24
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 very useful when your changes affect other parts of
your code of larger projects.

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.

import java.awt.*;
import java.awt.event.*;
public class cal2 implements ActionListener
{
int c,n;
String s1,s2,s3,s4,s5;
Frame f;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;
Panel p;
TextField tf;
GridLayout g;
cal2()
{
f = new Frame("My calculator");
b1 = new Button("0");
b1.addActionListener(this);
b2 = new Button("1");
b2.addActionListener(this);
b3 = new Button("2");
b3.addActionListener(this);

25
b4 = new Button("3");
b4.addActionListener(this);
b5 = new Button("4");

b5.addActionListener(this);
b6 = new Button("5");
b6.addActionListener(this);
b7 = new Button("6");
b7.addActionListener(this);
b8 = new Button("7");
b8.addActionListener(this);
b9 = new Button("8");
b9.addActionListener(this);
b10 = new Button("9");
b10.addActionListener(this);
b11 = new Button("+");
b11.addActionListener(this);
b12 = new Button("-");
b12.addActionListener(this);
b13 = new Button("*");
b13.addActionListener(this);
b14 = new Button("/");
b14.addActionListener(this);
b15 = new Button("%");
b15.addActionListener(this);
b16 = new Button("=");
b16.addActionListener(this);
b17 = new Button("C");
b17.addActionListener(this);
tf = new TextField(20);
f.setLayout(new GridLayout(4,5));

26
f.add(tf); f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5); f.add(b6); f.add(b7); f.add(b8);
f.add(b9); f.add(b10); f.add(b11); f.add(b12); f.add(b13); f.add(b14); f.add(b15); f.add(b16);
f.add(b17);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
s3 = tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 = tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 = tf.getText();
s4 = "2";
s5 = s3+s4;

tf.setText(s5);
}if(e.getSource()==b4)
{
s3 = tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b5)
{
s3 = tf.getText();
s4 = "4";
s5 = s3+s4;
tf.setText(s5);

27
}
if(e.getSource()==b6)
{
s3 = tf.getText();
s4 = "5";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b7)
{
s3 = tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8)
{
s3 = tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9)
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b10)

{
s3 = tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11)
{
s1 = tf.getText();
tf.setText("");
c=1;
}
if(e.getSource()==b12)
{

28
s1 = tf.getText();
tf.setText("");
c=2;
}
if(e.getSource()==b13)
{
s1 = tf.getText();
tf.setText("");
c=3;
}
if(e.getSource()==b14)
{
s1 = tf.getText();
tf.setText("");
c=4;
}
if(e.getSource()==b15)
{
s1 = tf.getText();
tf.setText("");
c=5;

}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n = Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==2)
{
n = Integer.parseInt(s1)-Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}else
if(c==3)
{
n = Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
if(c==4)
{
try
{

29
int p=Integer.parseInt(s2);
if(p!=0)
{
n = Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
tf.setText("infinite");

}
catch(Exception i){}
}
if(c==5)
{
n = Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
}
if(e.getSource()==b17)
{
tf.setText("");
}
}
public static void main(String[] abc)
{
new cal2();
}
}

Output:

30
3. A) Develop an applet in Java that displays a simple message.
b) Develop an applet in Java 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.
Introduction:

Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:

● It works at client side so less response time.

● Secured

● It can be executed by browsers running under many platforms, including Linux,


Windows, Mac Os etc.

31
Drawback of Applet
● Plug-in is required at client browser to execute applet.

Program:
a)
import java.awt.*;
import java.applet.*;
public class appl extends Applet
{
public void paint(Graphics g)
{
g.drawString("kits",100,100);
}
}

B) import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class factorial extends Applet implements ActionListener{
TextField t1,t2;

32
Button b1;
public void init(){
t1=new TextField(20);
t2=new TextField(20);
b1=new Button("compute");
setLayout(new FlowLayout(FlowLayout.CENTER,20,30));
add(t1);
add(b1);
add(t2);
b1.addActionListener(this);}
/*public void paint(Graphics g){
//setBackground(Color.pink);
g.drawString("Program on factorial",10,10);
}*/
public void start()
{}
public void actionPerformed(ActionEvent ae){
int a,b,i,fact=1;
if(ae.getActionCommand().equals("compute"));
a=Integer.parseInt(t1.getText());
for(i=1;i<=a;i++){
fact=fact*i;}
t2.setText(String.valueOf(fact));}}

Output:

33
4. Write a Java 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 Num 2 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 Number Format Exception. If Num2 were Zero, the
program would throw an Arithmetic Exception. Display the exception in a message dialog
box.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

34
class Aa extends JFrame implements ActionListener
{
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3; JButton b1;
Aa()
{
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);
add(tf1);
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(this);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
try {
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
if(b==0)

35
throw new ArithmeticException(" Divide by Zero Error");
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());
}
}
}
public class labdevi
{
public static void main(String[] args) {
Aa a = new Aa();
}
}

Output:

36
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.
Introduction:
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.

37
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occurs in a single
thread.
Program:
import java.util.Random;

class even extends Thread


{ int num;
even(int num)
{
this.num=num;
}
public void run()
{
System.out.println("the number"+num+" is even"+"squre is"+num*num);
}
}
class odd extends Thread
{
int num;
odd(int num)
{
this.num=num;
}
public void run()
{
System.out.println("the number"+num+" is odd"+"cube is"+num*num*num);
}
}

public class labmultithread {


public static void main(String args[])
{

38
int num = 0;
Random r = new Random();
try
{
for (int i = 0; i < 1; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
if (num % 2 == 0)
{
even e=new even(num);
e.start();
}
else{
odd e1=new odd(num);
e1.start();

}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}}

Output:

Main Thread and Generated Number is 1


New Thread 1 is ODD and Cube of 1 is: 1
--------------------------------------
Main Thread and Generated Number is 68
New Thread 68 is EVEN and Square of 68 is: 4624
--------------------------------------
Main Thread and Generated Number is 44
New Thread 44 is EVEN and Square of 44 is: 1936
--------------------------------------
Main Thread and Generated Number is 73
New Thread 73 is ODD and Cube of 73 is: 389017

39
6. Write a Java program for the following:
i) Create a doubly linked list of elements.
ii) Delete a given element from the above list.
iii) Display the contents of the list after deletion.

Introduction:

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

40
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.

Here is the pictorial view of doubly linked list:

The two node links allow traversal of the list in either direction. While adding or removing a
node in a doubly-linked list requires changing more links than the same operations on a singly
linked list, the operations are simpler and potentially more efficient, because there is no need to
keep track of the previous node during traversal or no need to traverse the list to find the
previous node, so that its link can be modified.

Program:
import java.util.*;
public class LinkedList3 {
public static void main(String [] args)
{
LinkedList<String> ll=new LinkedList<String>();
ll.add("A");
ll.add("B");
ll.add("C");
ll.add("D");
ll.add("E");
ll.add("F");
ll.add("H");
ll.add("I");
ll.add("J");

41
ll.add("K");
System.out.println("Initial list of elements: "+ll);
ll.remove("C");
System.out.println("After invoking remove(object) method: "+ll);
ll.remove(0);
System.out.println("After invoking remove(index) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("A");
ll2.add("kits");
ll.addAll(ll2);
System.out.println("Updated list : "+ll);
ll.removeAll(ll2);
System.out.println("After invoking removeAll() method: "+ll);
ll.removeFirst();
System.out.println("After invoking removeFirst() method: "+ll);
ll.removeLast();
System.out.println("After invoking removeLast() method: "+ll);
ll.removeFirstOccurrence("H");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
ll.removeLastOccurrence("J");
System.out.println("After invoking removeLastOccurrence() method: "+ll);

ll.clear();
System.out.println("After invoking clear() method: "+ll);
}
}

Output:
Initial list of elements: [A, B, C, D, E, F, H, I, J, K]
After invoking remove(object) method: [A, B, D, E, F, H, I, J, K]
After invoking remove(index) method: [B, D, E, F, H, I, J, K]

42
Updated list : [B, D, E, F, H, I, J, K, A, kits]
After invoking removeAll() method: [B, D, E, F, H, I, J, K]
After invoking removeFirst() method: [D, E, F, H, I, J, K]
After invoking removeLast() method: [D, E, F, H, I, J]
After invoking removeFirstOccurrence() method: [D, E, F, I, J]
After invoking removeLastOccurrence() method: [D, E, F, I]
After invoking clear() method: []

7. Write a Java program that simulates a traffic light. The program lets the user select one
of three lights: red, yellow, or green with radio buttons. On selecting a button, an
appropriate message with “Stop” or “Ready” or “Go” should appear above the buttons in
selected color. Initially, there is no message shown.

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class not extends JFrame implements ItemListener

43
{
public JLabel l1, l2;
public JRadioButton r1, r2, r3;
public ButtonGroup bg;
public JPanel p, p1;
public not()
{
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);
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);

44
add(p1);
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
bg.add(r3);
setVisible(true);
}
public void itemStateChanged(ItemEvent i)
{
JRadioButton jb = (JRadioButton) i.getSource();
switch (jb.getText()) {
case "Red Light": {
l1.setText("STOP");
l1.setForeground(Color.red);
}
break;
case "Yellow Light":
{
l1.setText("Ready");
l1.setForeground(Color.YELLOW);
}
break;
case "Green Light":
{
l1.setText("GO");
l1.setForeground(Color.GREEN);
}
break;
}
}
public static void main(String[] args)

45
{
new not();
}
}
Output :

46
8. Write a Java program to create an abstract class named Shape that contains two
integers and an empty method named print Area (). 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 print Area () that prints the area of the
given shape.

Introduction:
Abstract class
If a class contain any abstract method then the class is declared as abstract class. An abstract
class is never instantiated. It is used to provide abstraction. Although it does not provide 100%
abstraction because it can also have concrete method.
Syntax :
abstract class class_name { }

47
Abstract method
Method that are declared without any body within an abstract class are called abstract method.
The method body will be defined by its subclass. Abstract method can never be final and static.
Any class that extends an abstract class must implement all the abstract methods declared by the
super class.
Syntax :
abstract return_type function_name (); // No definition

When to use Abstract Methods & Abstract Class?


Abstract methods are usually declared where two or more subclasses are expected to do a similar
thing in different ways through different implementations. These subclasses extend the same
Abstract class and provide different implementations for the abstract methods.

Abstract classes are used to define generic types of behaviors at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of the
abstract class.

Program:
abstract class shape1
{
int a=5,b=2;
abstract void printarea();
}
class rectangle extends shape1
{
void printarea()
{
int ans=a*b;
System.out.println(ans);
}
}
class triangle extends shape1
{

48
void printarea()
{
double ans=0.5*a*b;
System.out.println(ans);
}
}
class circle extends shape1
{
double pi=3.145;
void printarea()
{
double ans=pi*a*a;
System.out.println(ans);
}
}
class abs
{
public static void main(String args[])
{
rectangle p=new rectangle();
triangle q=new triangle();
circle r=new circle();
p.printarea();
q.printarea();
r.printarea();
}
}
Output:
10
5.0
78.625

49
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.

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class gg extends Frame
{

50
public gg()
{
setSize(600, 600);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fin = new FileInputStream("D:\\student.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 Label(i));
}
}
} catch (Exception ex) {
}
pack();
setVisible(true);
}
}
public class TableData
{
public static void main(String[] args)
{
gg a = new gg();

51
}
}
Input: create a text file with the name studet.txt as
student.txt

OUTPUT: Java Program displays the details of student.txt file, in the Frame using Label in
Grid Layout

52
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).

Introduction:
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);

53
5. public abstract void mouseReleased(MouseEvent e);

Program:

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class ds extends JFrame implements MouseListener
{
JLabel l1;
public ds()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new FlowLayout());
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)

54
{
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 mouseeventslab
{
public static void main(String[] args) {
ds a = new ds();
}
}

Output:

55
56
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).
import java.util.*;
import java.io.*;
public class labfiles
{
public static void main(String[] args)throws IOException {

57
FileReader fs = new FileReader("F:\\test.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\t");
Hashtable ht = new Hashtable();
String[] arrayList;
String a;
System.out.println("welcome to files program \n");
System.out.println("Student Phone numbers are");
while (sc.hasNext())
{
a = sc.nextLine();
arrayList = a.split("\\t");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
System.out.println("welcome to files program \n");
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();

58
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
} else {
System.out.println("Not Found");
}
break;
case "2":
System.out.println("Enter mobile");
mobile = s.next();

if(ht.containsValue(mobile))
{
Set ss=ht.entrySet();
Iterator itr=ss.iterator();
while(itr.hasNext())
{
Map.Entry mp=(Map.Entry)itr.next();
if(mobile.equals(mp.getValue()))
{
System.out.println("Name is :"+ mp.getKey());}
}
}
else
{
System.out.println("Not Found");
}
break;
case "3":
opt = "3";
System.out.println("Menu Successfully Exited");

59
break;
default:
System.out.println("Choose Option betwen 1 and Three");
break;
}
}
}
}

Output:

welcome to files program

Student Phone numbers are


tina:9966554744
John:9160600571
ABC:8008085263
welcome to files program

MENU
1.Search by Name
2.Search by Mobile
3.Exit
Enter Your Option (1,2,3):
1
Enter Name
tina
Mobile is 9966554744
Enter Your Option (1,2,3):
2
Enter mobile
9160600571
Name is :john
Enter Your Option (1,2,3):
3
Menu Successfully Exited

60
12. Write a Java program that correctly implements the producer – consumer problem
using the concept of interthread communication.

public class InterThreadCommEx


{
public static void main(String[] args)
{
Item item = new Item();
Producer producer = new Producer(item);
Consumer consumer = new Consumer(item);

61
producer.start();
consumer.start();
}
}
class Item
{
private int value;
boolean valueSet = false;
public synchronized void setItem(int i) throws InterruptedException
{
if (valueSet)
{
wait();
}
value = i;
System.out.print("Producer seting item: " + i);
notify();
valueSet = true;
}
public synchronized int getItem() throws InterruptedException
{
if (!valueSet) {
wait();
}
System.out.println(" -> Consumer geting item: " + value);
notify();
valueSet = false;
return value;
}
}
class Producer extends Thread

62
{
private Item item;
int i;
public Producer(Item item)
{
this.item = item;
}
public void run()
{
while (true)
{
try
{
sleep(1000);
item.setItem(++i);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Consumer extends Thread
{
private Item item;
public Consumer(Item item)
{
this.item = item;
}
public void run()

63
{
while (true)
{
try
{
sleep(500);
int temp = item.getItem();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
Output:
Producer seting item: 1 -> Consumer geting item: 1
Producer seting item: 2 -> Consumer geting item: 2
Producer seting item: 3 -> Consumer geting item: 3
Producer seting item: 4 -> Consumer geting item: 4
Producer seting item: 5 -> Consumer geting item: 5
Producer seting item: 6 -> Consumer geting item: 6
Producer seting item: 7 -> Consumer geting item: 7
Producer seting item: 8 -> Consumer geting item: 8
Producer seting item: 9 -> Consumer geting item: 9
Producer seting item: 10 -> Consumer geting item: 10
Producer seting item: 11 -> Consumer geting item: 11
Producer seting item: 12 -> Consumer geting item: 12

64
13. Write a Java program to list all the files in a directory including the files present in all
its subdirectories.

import java.io.File;
import java.io.IOException;
public class RecursiveFileDisplay
{
public static void main(String[] args)
{
File currentDir = new File("."); // current directory

65
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir)
{
try
{
File[] files = dir.listFiles();
for (File file : files)
{
if (file.isDirectory())
{
System.out.println("directory:" + file.getCanonicalPath());
displayDirectoryContents(file);
}
else
{
System.out.println(" file:" + file.getCanonicalPath());
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Output:
file:C:\Users\dell\2017-2018\unit1\.classpath
file:C:\Users\dell\2017-2018\unit1\.project
directory:C:\Users\dell\2017-2018\unit1\.settings

66
file:C:\Users\dell\2017-2018\unit1\.settings\org.eclipse.jdt.core.prefs
directory:C:\Users\dell\2017-2018\unit1\bin
directory:C:\Users\dell\2017-2018\unit1\bin\unit1
file:C:\Users\dell\2017-2018\unit1\bin\unit1\A.class
file:C:\Users\dell\2017-2018\unit1\bin\unit1\arr.class
file:C:\Users\dell\2017-2018\unit1\bin\unit1\array3.class
file:C:\Users\dell\2017-2018\unit1\bin\unit1\arrayminmax.class
file:C:\Users\dell\2017-2018\unit1\bin\unit1\arraysum.class
file:C:\Users\dell\2017-2018\unit1\bin\unit1\arrsam.class

14. Write a Java program that implements Quick sort algorithm for sorting a list of names
in ascending order

public class MyQuickSort


{
int array[];
int length;

public void sort(int[] inputArr)


{
if (inputArr == null || inputArr.length == 0)
{
return;
}
this.array = inputArr;

67
length = inputArr.length;
quickSort(0, length - 1);
}

private void quickSort(int lowerIndex, int higherIndex)


{
int i = lowerIndex;
int j = higherIndex;
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
while (i <= j)
{
while (array[i] < pivot)
{
i++;
}
while (array[j] > pivot)
{
j--;
}
if (i <= j)
{
exchangeNumbers(i, j);

i++;
j--;
}
}

if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
private void exchangeNumbers(int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}

public static void main(String a[])


{

68
MyQuickSort sorter = new MyQuickSort();
int[] input = {24,2,45,20,56,75,2,56,99,53,12};
sorter.sort(input);
for(int i:input)
{
System.out.print(i);
System.out.print(" ");
}
}
}

Output:

2 2 12 20 24 45 53 56 56 75 99

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.
import java.util.Scanner;
public class Descending_Order
{
public static void main(String[] args)
{
int n, temp,k=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];

69
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
k++;
}
}
System.out.print("Descending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.println(a[n - 1]);
System.out.print("No of iterations :" + k);
}
}
Output:
Enter no. of elements you want in array:5
Enter all the elements:
4
1

70
2
8
7
Descending Order:8,7,4,2,1
No of iterations :7

71

You might also like