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

Java External

The document describes an experiment to create an abstract class named Shape with two integer fields and an empty printArea() method. It then provides three subclasses (Rectangle, Triangle, Circle) that extend Shape and override the printArea() method to print the area calculation specific to each shape. The program creates objects of each subclass and calls printArea() on each object to output the area.

Uploaded by

Pati NithinReddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Java External

The document describes an experiment to create an abstract class named Shape with two integer fields and an empty printArea() method. It then provides three subclasses (Rectangle, Triangle, Circle) that extend Shape and override the printArea() method to print the area calculation specific to each shape. The program creates objects of each subclass and calls printArea() on each object to output the area.

Uploaded by

Pati NithinReddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

EXPERIMENT-3(A)

OBJECTIVE:
To develop an Applet in java that displays a Simple Message

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name „Sms‟ extends Applet.
3. Declare the Font class object.
4. Set the font.
5. Call the setFont method and drawString method g.setFont(font);
g.drawString(“String", 50, 50);
6.Create the HTML file for applet tag.

PROCEDURE:
To execute a java program we require setting a class path:
1.C:\set path= C:\Program Files\Java\ JDK1.7\bin;.;
2.C:\javac HelloJava.java
3.C:\appletviewer Sms.html

SOURCE CODE:
importjava.applet.Applet;
import java.awt.*;
public class HelloJava 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("Hello Java ", 50, 50);
}
}

Expected Output:

1
2
EXPERIMENT-3(B)
OBJECTIVE:
To 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 button named “Compute” is
clicked

PROGRAM LOGIC:
 Start the program
 Create a class with the name “Fact‟ extends Applet which implements
ActionListener.
 Declare the Label,TextField, Button variables.
 Call init method
 Call the setLayout method, setLayout(g);
 Create the HTML file for applet tag.

PROCEDURE:
1.C:\javac Fact.java
2.C:\appletviewer Fact.html

SOURCE CODE:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Fact extends Applet implements ActionListener
{
Label l1, l2, l3;
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.BLUE);
add(l1);
tf1 = new TextField(5);
3
tf1.setText("0");
add(tf1);
b1 = new Button("Compute");
b1.addActionListener(this);
add(b1);
l3 = new Label();
add(l3);
l2 = new Label("factorial: ");
l2.setForeground(Color.BLUE);
add(l2);
tf2 = new TextField(5);
add(tf2);
}
public void actionPerformed(ActionEventae)
{
long n = Integer.parseInt(tf1.getText());
long f = 1;
while (n != 0)
{ f = f * n;
n--;
} tf2.setText(String.valueOf(f));
}
}
Expected Output:

4
EXPERIMENT-4

OBJECTIVE:
To creates User Interface to perform Integer Divisions. The user enters two numbers in
text fields, Num1 and Num2.The division of Num1 and Num2 is displayed in the result
field when the divide button clicked. If Num1 or Num2 were not integer, the program
would throw a NumberFormatException, If Num2 is Zero, and the program would throw
an Arithmetic Exception. Display the Exception in message box.

PROGRAM LOGIC:

 Start the program


 Create a class with the name “A extends JFrame‟.
 Declare the JLabel,JTextField,JButton variables.
 Declare the default constructor of the class.
 5.Addbuttons,TextField and labels to the Flow Layout.
 6.CallActionPerformed method.

PROCEDURE:

1.C:\javac JavaApplication9.java
2. C:\java JavaApplication9

SOURCE CODE:

importjava.awt.*;
import java.awt.event.*;
import javax.swing.*;
importjavax.swing.event.*;
class A1 extends JFrame implements ActionListener
{
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3;
JButton b1;
A1()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
5
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(ActionEventae)
{
try
{
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
if(b==0)
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)
6
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
}
public class JavaApplication9
{
public static void main(String[] args)
{
A1 a = new A1();
}
}

EXPECTED OUTPUT:

7
Experiment: 5
OBJECTIVE:
Write Java Program that implements a multithread application that has three threads. First
thread generates Random integer for every second and if the value is even, second thread
computes the square of number and prints. If the value is odd, the third thread will print
the value of cube of number.

PROCEDURE:

1.C:\javac JavaApplication5.java
2. C:\java JavaApplication5

SOURCE CODE

import java.util.*;

class even implements Runnable


{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN 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("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x * x);
}
}
8
class A extends Thread
{
public void run()
{
Intnum = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)

{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num));
t1.start();
} else {
Thread t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}}}
public class JavaProgram5
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}

EXPECTED OUTPUT:
9
10
EXPERIMENT-7

OBJECTIVE
To simulate a Traffic Light. The program lets the use select one of three lights :red,
yellow or Green with radio buttons. 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.

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name A implements ItemListener.
3. Create the ButtonGroup ,JRadiobuttons,JPanel.
4. Add to the JFrame
5. Register the components to the Jframe.
6. Close the Jframe.

PROCEDURE:
To execute a java program we require setting a class path:
1.C:\set path= C:\Program Files\Java\ JDK1.7\bin;.;
2.C:\javac TLights.java
3.C:\java TLights

SOURCE CODE:

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

class A extends JFrame implements ItemListener


{
public JLabel l1, l2;
publicJRadioButton r1, r2, r3;
public ButtonGroupbg;
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());

11
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);
add(p1);
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
bg.add(r3);
setVisible(true);
}

public void itemStateChanged(ItemEventi)


{
JRadioButtonjb = (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;
}
}

12
}

public class TLights { public static void main(String[] args) {

A a = new A();
}}

EXPECTED OUTPUT:

13
EXPERIMENT-8
OBJECTIVE:
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 subclass
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 Shape.

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name Shape.
3. Create the Rectangle,Triangle,Circle extends Shape.
4. Create the objects to the individual classes.
5. Call the PrintArea() on individual object.

PROCEDURE:
To execute a java program we require setting a class path: 1.C:\set path= C:\Program
Files\Java\ JDK1.7\bin;.; 2.C:\javac Abstex.java
3.C:\java Abstex

SOURCE CODE:

import java.util.*;
abstract class shape
{
public intx,y;
public abstract void printArea();
}
class Rectangle1 extends shape
{
public void printArea()
{
float area;
area= x * y;
System.out.println("Area of Rectangle is " +area);
}
}
class Triangle extends shape
{
public void printArea()
14
{
float area;
area= (x * y) / 2;
System.out.println("Area of Triangle is " + area);
}
}
class Circle extends shape
{
public void printArea()
{
float area;
area=(22 * x * x) / 7;
System.out.println("Area of Circle is " + area);
}
}
public class Shapes
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter values : ");


int x1=sc.nextInt();
int y1=sc.nextInt();

Rectangle1 r = new Rectangle1();


r.x = x1; r.y = y1;
r.printArea();

Triangle t = new Triangle();


t.x = x1; t.y = y1;
t.printArea();

Circle c = new Circle();


c.x = x1;
c.printArea();
}
}

15
EXPECTED OUTPUT:

16
EXPERIMENT-10

OBJECTIVE:

Write a Java Program that handles all mouse events and show event name at the center of
the window when the mouse event is fired. (Use Adapter Classes)

importjavax.swing.*;
importjava.awt.*;
importjavax.swing.event.*;
importjava.awt.event.*;
class A extends JFrame implements MouseListener
{
JLabel l1;
public A()
{
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_ALIGN
MENT);
l1.setAlignmentY(Component.CENTER_ALIGN
MENT); 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)
{
17
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();
}
}
EXPECTED OUTPUT:

18
EXPERIMENT-12

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

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name Threadexample
3. Display the data.

PROCEDURE:
To execute a java program we require setting a class path:
1. C:\set path= C:\Program Files\Java\ JDK1.7\bin
2. C:\javacThreadexample.java
3. C:\java Threadexample

SOURCE CODE:

import java.util.LinkedList;
public class Threadexample
{
public static void main(String[] args)throws InterruptedException
{
// Object of a class that has both produce() and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
19
e.printStackTrace();
}
}
});

// Create consumer thread


Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}

// This class has a list, producer (adds items to list


// and consumber (removes items).
public static class PC
{
// Create a list shared by producer and consumer
// Size of list is 2.
20
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;

// Function called by producer thread


public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size()==capacity)
wait();
System.out.println("Producer produced-" +value);

// to insert the jobs in the list


list.add(value++);
notify();
Thread.sleep(1000);
}
}
}

// Function called by consumer thread


public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size()==0)
wait();

21
//to retrive the ifrst job in the list
intval = list.removeFirst();
System.out.println("Consumer consumed-" + val);
// Wake up producer thread
notify();
// and sleep
Thread.sleep(1000);
}
}
}
}
}
EXPECTED OUTPUT:

22
EXPERIMENT-14

OBJECTIVE:
Writea Java program that implements Quick sort algorithm for sorting alist of numbers in
ascending order.

SOURCE CODE:

importjava.util.Scanner;
publicclassQuickSort
{

Publicstaticvoid sort(int[] arr)


{
quickSort(arr, 0, arr.length - 1);
}
/** Quick sort function **/
publicstaticvoidquickSort(intarr[], int low, int high)
{
int i = low, j = high;
int temp;
int pivot = arr[(low + high) / 2];

/** partition **/


while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
/** swap **/
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

i++;
j--;
}
}

23
/** recursively sort lower half **/
if (low < j)
quickSort(arr, low, j);
/** recursively sort upper half **/
if (i < high)
quickSort(arr, i, high);
}
/** Main method **/
publicstaticvoid main(String[] args)
{
Scanner scan = newScanner( System.in );
System.out.println("Quick Sort Test\n");
int n, i;
/** Accept number of elements **/
System.out.println("Enter number of integer elements");
n = scan.nextInt();
/** Create array of n elements **/
intarr[] = newint[ n ];
/** Accept elements **/
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
/** Call method sort **/
sort(arr);
/** Print sorted Array **/
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}

EXPECTED OUPUT:
Enter number of integer elements
10
Enter 10 integer elements
877 567 3456 876 467 26 934 9876 1 4567

Elements after sorting


1 26 467 567 876 877 934 3456 4567 9876

24
EXPERIMENT-15

OBJECTIVE:
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.

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name Threadexample
3. Display the data.

PROCEDURE:

To execute a java program we require setting a class path:


1.C:\set path= C:\Program Files\Java\ JDK1.7\bin;.; 2.C:\javacThreadexample.java
3.C:\java Threadexample

SOURCE CODE:
import java.util.Scanner;

class BubbleSort
{
public static void main(String []args)
{
int num, i, j, temp,count=0;
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])
25
{
count++;
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]);
System.out.println(count);
}
}
EXPECTED OUTPUT:

26

You might also like