0% found this document useful (0 votes)
88 views42 pages

CSE II Yr JNTU

The document contains code for several Java programs that solve different problems: 1) A Quadratic equation solver that takes user input for coefficients a, b, c and uses the quadratic formula to find the real roots, printing the results. 2) Fibonacci sequence generators that use iterative and recursive functions to print the nth value. 3) A prime number checker that takes a user input and prints all prime numbers up to that value. 4) A matrix multiplier that takes user input for two matrices and prints the product if multiplication is possible. 5) A program that sums all integers in a string by tokenizing the input. 6) A palindrome checker that takes a string and checks if it is a

Uploaded by

Salma Fatima
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views42 pages

CSE II Yr JNTU

The document contains code for several Java programs that solve different problems: 1) A Quadratic equation solver that takes user input for coefficients a, b, c and uses the quadratic formula to find the real roots, printing the results. 2) Fibonacci sequence generators that use iterative and recursive functions to print the nth value. 3) A prime number checker that takes a user input and prints all prime numbers up to that value. 4) A matrix multiplier that takes user input for two matrices and prints the product if multiplication is possible. 5) A program that sums all integers in a string by tokenizing the input. 6) A palindrome checker that takes a string and checks if it is a

Uploaded by

Salma Fatima
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 42

//Quadratic.

java
/*Write a java program that prints all real solutions to the Quadratic
equation Read in a,b,c and use the Quadratic formula. If the discrminant
is b2 - 4ac is negative then display a message stating that there are
no real solutions*/

import java.lang.*;
import java.io.*;

public class Quadratic {

public static void main(String args[]) throws IOException {


int a, b, c, disc, r1, r2;

InputStreamReader obj = new InputStreamReader(System.in);


BufferedReader br = new BufferedReader(obj);

System.out.println("Enter a");
a = Integer.parseInt(br.readLine());

System.out.println("Enter b");
b = Integer.parseInt(br.readLine());

System.out.println("Enter c");
c = Integer.parseInt(br.readLine());

disc = (b * b) - (4 * a * c);

if (disc > 0) {
System.out.println("Roots are real and unequal");

r1 = ((-b) + (b * b - 4 * a * c)) / (2 * a);


r2 = ((-b) - (b * b - 4 * a * c)) / (2 * a);

System.out.println("Roots are as Follows");


System.out.println(" r1 = " + r1);
System.out.println(" r2 = " + r2);
}

else if (disc == 0) {
System.out.println("Roots are Real and Equal");
r1 = r2 = (-b) / (2 * a);
System.out.println(" r1 = " + r1);
System.out.println(" r2 = " + r2);
}

else {
System.out.println("Roots are imaginary");
}
}
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


OUTPUT
Enter a
2
Enter b
4
Enter c
2
Roots are Real and Equal
r1 = -1
r2 = -1

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//Fibonacci.java
/*Write a java program that uses non recursive function to print
the nth value in the Fibonnacci Sequence*/

public class Fibonacci


{
int a = 0, b = 1, c = 1, i = 0;

public void fibonacci(int n)


{
System.out.println("Fibonacci serries as follows");
System.out.println(" " + a);
System.out.println(" " + b);

while (i <= n - 3)
{
c = a + b;
System.out.println(" " + c);

a = b;
b = c;
i++;
}
}
}

//FibonacciTest.java
import java.io.*;
public class FibonacciTest {
public static void main(String args[]) throws IOException
{
InputStreamReader obj = new InputStreamReader( System.in );
BufferedReader br = new BufferedReader( obj );

System.out.println(" Enter last number ");


int n = Integer.parseInt( br.readLine() );

Fibonacci f = new Fibonacci();


f.fibonacci( n );

}
}

OUTPUT
Enter last number 7

Fibonacci serries as follows


0
1
1
2
3
5
8

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//FibonacciRec.java
/*Write a java program that uses recursive function to print
the nth value in the Fibonnacci Sequence*/

import java.io.*;
public class FibonacciRec {

public int fibonacci( int n )


{
if( n == 1 || n == 2 )
return n;
else
return fibonacci( n - 1 ) + fibonacci( n - 2 );
}

//FibonacciRecTest.java
import java.io.*;

public class FibonacciRecTest


{
public static void main(String args[]) throws IOException
{
InputStreamReader obj = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(obj);

System.out.println("Enter last integer");


int n = Integer.parseInt(br.readLine());

FibonacciRec fibrec = new FibonacciRec();


System.out.println("Fibonacci series using recursion");

for (int i = 1; i <= n; i++)


{
int res = fibrec.fibonacci(i);
System.out.println(" " + res);
}
}
}

OUTPUT
Enter last integer 4

Fibonacci series using recursion


1
2
3
5

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//Prime.java
/*Write a program that prompts the user for an integer and then prints
out all the prime numbers up to that integer*/

import java.io.*;
public class Prime
{
boolean isPrime = false;

public void prime(int n)


{
System.out.println("prime Numbers are as follows");
for (int i = 2; i <= n; i++)
{
isPrime = true;
for (int j = 2; j <= i / 2; j++)
{
if (i % j == 0)
isPrime = false;
}
if (isPrime == true)
System.out.println(" " + i);
}
}
}

//PrimeTest.java

import java.io.*;
public class PrimeTest
{
public static void main(String args[] )throws IOException
{
InputStreamReader obj = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader( obj );

System.out.println("Enter last number");


int n = Integer.parseInt(br.readLine());

Prime p = new Prime();


p.prime(n);
}
}

OUTPUT
Enter last number: 7
Prime Number are as follows
2
3
5
7

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//MatrixMul.java
/*Write a Java Program to multiply two given matrices*/

import java.io.*;
import java.util.Scanner;

public class MatrixMul


{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);

System.out.println("Enter rows and columns of first matrix");


int m = s.nextInt();
int n = s.nextInt();

System.out.println("Enter the col and rows of second matrix");


int p = s.nextInt();
int q = s.nextInt();

int a[][] = new int[m][n];


int b[][] = new int[p][q];
int c[][] = new int[m][q];

if (n == p)
{
System.out.println("Matrix Multiplication is possible");

System.out.println("Enter the values of matrix1");


for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
a[i][j] = s.nextInt();
}

System.out.println("Enter the values of second matrix");


for (int i = 0; i < p; i++)
for (int j = 0; j < q; j++)
{
b[i][j] = s.nextInt();
}

for (int i = 0; i < p; i++)


{
for (int j = 0; j < q; j++)
{
int sum = 0;
for (int k = 0; k < n; k++)
{
sum += a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


System.out.println("Product is");
for (int i = 0; i < m; i++)
{
System.out.println("");
for (int j = 0; j < q; j++)
{
System.out.print(" " + c[i][j]);
}
}
}
else
System.out.println("Matrix Multiplication is not possible");
}
}

OUTPUT
Enter rows and columns of first matrix
2 2
Enter the col and rows of second matrix
2 2
Matrix Multiplication is possible

Enter the values of matrix1


1 0 0 1
Enter the values of second matrix
1 2 3 4

Product is
1 2
3 4

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//SumOfInt.java
//Program for sum of all integers using string tokenizer

import java.io.*;
import java.util.*;
public class SumOfInt {
public static void main(String args[]) throws IOException
{
InputStreamReader obj = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader( obj );
System.out.println("Enter integers");
String input = br.readLine();
StringTokenizer tokens = new StringTokenizer(input);

int sum = 0;
while(tokens.hasMoreTokens())
{
String value = tokens.nextToken();
int value1 = Integer.parseInt(value);
sum += value1;

}
System.out.println("Sum of integers is: "+ sum);
}

OUTPUT
Enter integers
1 2 3 4 5 6
Sum of integers is: 21

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//Palimdrome.java
/*Write a java Program that checks whether the string is palindrome or
not*/

import java.util.*;
public class Palindrome
{
public static void main(String args[])
{
String s1 = new String();
String s2 = new String();
System.out.println("Enter a string");

Scanner sc = new Scanner( System.in);


s1 = sc.nextLine();
StringBuffer sb = new StringBuffer( s1 );

//String reverse function for reversing the string


s2 = sb.reverse().toString();
if( s1.equals( s2 ))
System.out.println(" " + s1 + " is a palindrome");
else
System.out.println(" " + s2 + " is not a palindrome");
}
}

OUTPUT
Enter a string madam
madam is a palindrome

Enter a string java


avaj is not a palindrome

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//Sort.java
/*Write a java Program for sorting a given list of names in ascending
order*/

import java.util.*;

public class Sort


{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int i, j;

System.out.println("Enter the number of strings to be sorted");


int n = sc.nextInt();
String a[] = new String[n + 1];

System.out.println("enter the names");


for (i = 0; i <= n; i++)
{
a[i] = sc.nextLine();
}

System.out.println("\nSorted List is");


for (i = 0; i < a.length; i++)
{
for (j = i; j < a.length; j++)
{
if (a[j].compareTo(a[i]) < 0)
{
String t = a[i];
a[i] = a[j];
a[j] = t;
}
}
System.out.println(a[i]);
}

}
}

OUTPUT

Enter the number of strings to be sorted 3

enter the names


mechanical
civil
electrical

Sorted List is
civil
electrical
mechanical

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//ReadTxt.java
/*Write a Program to make a frequency count of words in a given text*/

import java.util.*;
public class ReadTxt {
public static void main(String args[])
{
String s1 = new String();
System.out.println("Enter a line of text:-");
Scanner sc = new Scanner(System.in);
s1 = sc.nextLine();

int sum = 0;
StringTokenizer st = new StringTokenizer( s1 );

while(st.hasMoreTokens())
{
String value = st.nextToken();
System.out.println(value);
sum++;
}
System.out.println("Frequency counts of words is" + sum);
}

OUTPUT
Enter a line of text:- This is a line with 7 tokens

This
is
a
line
with
7
tokens

Frequency counts of words is7

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//FileInfo.java
/* Write a java program that reads a file name from the user, then
displays information about whether the files exists, is readable, is
Writable, the type of file and the length of the file in bytes*/

import java.io.*;
import javax.swing.*;

public class FileInfo


{
public static void main(String args[])throws IOException
{
InputStreamReader obj = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(obj);

System.out.println("Enter File Name:");


String fileName = br.readLine();
File f = new File( fileName );

if (f.isFile())
{
System.out.println(f + (f.isFile() ? " is " : "isNot")
+ "aFile");

System.out.println(f + (f.exists() ? " does " : "doesNot")


+ "exists");

System.out.println(f + (f.canRead() ? " can " : "cannot")


+ "read");

System.out.println(f + (f.canWrite() ? " can ": "canno")


+ "write");

}
else
System.out.println(f + "is not a File");

}
}

OUTPUT
Enter File Name: C:\\cse\\FibDemo.java

C:\cse\FibDemo.java is aFile
C:\cse\FibDemo.java does exists
C:\cse\FibDemo.java can read
C:\cse\FibDemo.java can write

//LineNumb.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


/*Write a File that reads a file and displays the file on the screen,
with a line number before each line*/

import java.io.*;

public class LineNumb


{
public static void main(String args[]) throws IOException
{
String file = "C:\\cse\\FibonacciRec.java";
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String s;
int i = 1;

while (((s = br.readLine()) != null))


{
System.out.println(i + " " + s);
i++;
}
}
}

OUTPUT
1 /*Write a java program that uses recursive function to print
2 the nth value in the Fibonnacci Sequence*/
3
4 //FibonacciRec
5
6 import java.io.*;
7 public class FibonacciRec {
8
9 public int fibonacci( int n )
10 {
11 if( n == 1 || n == 2 )
12 return n;
13 else
14 return fibonacci( n - 1 ) + fibonacci( n - 2 );
15 }
16
17 }

//DisplayFile.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


/*Write a java program that displays the number of characters, lines and
words in a text file*/

import java.io.*;
import java.util.*;

public class DisplayFile {

public static void main(String args[]) throws IOException {


String s1 = "";
String s2 = "";
int c = 0, i = 0, j = 0, sum = 0;
try {

String fileName = "C:\\cse\\FibonacciRec.java";


FileReader f1 = new FileReader(fileName);
FileReader f2 = new FileReader(fileName);
BufferedReader br1 = new BufferedReader(f1);
BufferedReader br2 = new BufferedReader(f2);

while ((s1 = br1.readLine()) != null) {


i++;
}

while (s2 != null) {

s2 = br2.readLine();
j = s2.length();
sum += j;

StringTokenizer st = new StringTokenizer(s2);

while (st.hasMoreTokens()) {

st.nextToken();
c++;

}
} catch (Exception e){ }

System.out.println("total number of lines " + i);


System.out.println("Total number of words " + c);
System.out.println("Total number of characters " + sum);

}
}

OUTPUT
total number of lines 17
Total number of words 57
Total number of characters 331

// WelcomeApplet.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


// Develop an applet that displays a simple message.

import java.awt.*;
import javax.swing.*;
public class WelcomeApplet extends JApplet {
public void paint(Graphics g)
{
g.drawString("Welcome..This string is displayed at the position
x= 25,y =25",25,25);
}

OUTPUT

//Factorial.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


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

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Factorial extends JApplet implements ActionListener {

JLabel numLabel;
JTextField numField;

JLabel factLabel;
JTextField factField;

JButton compute;
int fact ;

public void init()


{
fact = 1;
Container c = getContentPane();
c.setLayout(new GridLayout(3,2,3,3));

numLabel = new JLabel("num");


numField = new JTextField( 10 );
c.add(numLabel);
c.add(numField);

factLabel = new JLabel("FactorialVal");


factField = new JTextField( 10 );
c.add(factLabel);
c.add(factField);

compute = new JButton("Compute");


c.add(compute);
compute.addActionListener(this);

setSize(100,100);
//setVisible(true);
}

public void actionPerformed(ActionEvent e)


{
String a = numField.getText();
int a1 = Integer.parseInt(a);
System.out.println(a1);

int facto = factorial( a1);

String fact = String.valueOf(facto);


factField.setText(fact);

public int factorial( int n)

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


{
if( n <= 1)
return 1;
else
return n * factorial( n - 1);

}
}

OUTPUT

//MouseTracker.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//Write a Java program for handling mouse events.

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

public class MouseTracker extends JFrame


implements MouseListener, MouseMotionListener {
private JLabel outputLabel;

public MouseTracker()
{
super( "Demonstrating Mouse Events" );

outputLabel = new JLabel();


Container c = getContentPane();
c.add(outputLabel);

// application listens to its own mouse events


addMouseListener( this );
addMouseMotionListener( this );

setSize( 275, 100 );


setVisible(true);
}

// MouseListener event handler


public void mouseClicked( MouseEvent e )
{
int x = e.getX();
int y = e.getY();
outputLabel.setText( "Mouse Clicked at x =" + x + " y = " + y );
}

// MouseListener event handler


public void mousePressed( MouseEvent e )
{
int x = e.getX();
int y = e.getY();
outputLabel.setText( "Mouse Pressed at x =" + x + " y = " + y );
}

// MouseListener event handler


public void mouseReleased( MouseEvent e )
{
int x = e.getX();
int y = e.getY();
outputLabel.setText( "Mouse Released at x =" + x + " y = " + y );
}

// MouseListener event handler


public void mouseEntered( MouseEvent e )
{
outputLabel.setText( "Mouse in window" );
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


// MouseListener event handler
public void mouseExited( MouseEvent e )
{
outputLabel.setText( "Mouse outside window" );
}

// MouseMotionListener event handler


public void mouseDragged( MouseEvent e )
{
int x = e.getX();
int y = e.getY();
outputLabel.setText( "Mouse Dragged at x =" + x + " y = " + y );
}
// MouseMotionListener event handler
public void mouseMoved( MouseEvent e )
{
int x = e.getX();
int y = e.getY();
outputLabel.setText( "Mouse Moved at x =" + x + " y = " + y );
}

public static void main( String args[] )


{
MouseTracker app = new MouseTracker();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);

}
}

//Multi.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//Write a Java program that creates three threads.
//First thread displays “Good Morning” every one second,
//the second thread displays “Hello” every two seconds and
//the third thread displays “Welcome” every three seconds.

public class Multi extends Thread {

static int thread1, thread2, thread3;

public void run()


{
while (true)
{
String name = Thread.currentThread().getName();
//Thread-1 prints GoodMorning every 1000ms
if (name.equals("Thread-1"))
{
thread1++;
System.out.println(name + "-->Good Morning");
try
{
Thread.sleep(1000);
} catch (Exception e)
{
System.out.println("Interrupted");
}
}

//Thread-2 prints "Hello" every 2000ms


if (name.equals("Thread-2"))
{
thread2++;
System.out.println(name + "-->Hello");
try
{
Thread.sleep(2000);
}
catch (Exception e)
{
System.out.println("Interrupted");
}
}

//Thread-3 displays "Welcome" every 3000ms


if (name.equals("Thread-3"))
{
thread3++;
System.out.println(name + "-->Welcome");
try
{
Thread.sleep(3000);
}
catch (Exception e)
{
System.out.println("Interrupted");
}
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


}
}
}

public class MultiTest{

public static void main(String args[]) {


Multi t0 = new Multi();
Multi t1 = new Multi();
Multi t2 = new Multi();

t0.setName("Thread-1");
t1.setName("Thread-2");
t2.setName("Thread-3");

t0.start();
t1.start();
t2.start();
// main thread will sleep for 5000ms
try
{
Thread.currentThread().sleep(5000);
System.out.println("Number of times Thread-1, Thread-2,
Thread-3 has been executed in 5000 milliseconds i.e 5sec");

System.out.println(" Thread-1 = " + thread1 +


" Thread-2 = " + thread2 +
" Thread-3 = " + thread3);

System.exit(0);
}
catch (InterruptedException e)
{
System.out.println("Interrupted");
}
}
}

OUTPUT
Thread-1-->Good Morning
Thread-3-->Welcome
Thread-2-->Hello
Thread-1-->Good Morning
Thread-2-->Hello
Thread-1-->Good Morning
Thread-3-->Welcome
Thread-1-->Good Morning
Thread-2-->Hello
Thread-1-->Good Morning

Number of times Thread-0, Thread-1, Thread-2 has been executed in 5000ms


i.e 5sec
Thread-1 = 5 Thread-2 = 3 Thread-3 = 2

// Producer.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


// Definition of threaded class Producer

public class Producer extends Thread {

public SharedAccess pHold;

public Producer(SharedAccess h) {
super("ProduceInteger");
pHold = h;
}

public void run() {


for (int count = 1; count <= 5; count++)
{

pHold.setSharedInt(count);
System.out.println("Producer" + count);
}
}
}

// Consumer.java
// Definition of threaded class ConsumeInteger

public class Consumer extends Thread {

public SharedAccess cHold;

public Consumer(SharedAccess h)
{
super("Consumer");
cHold = h;
}

public void run()


{
int val;

do
{
val = cHold.getSharedInt();
System.out.println("Consumer:" + val);
} while (val != 5);
}
}

// SharedAccess.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


// Definition of class SharedAccess that
// uses thread synchronization to ensure that both
// threads access sharedInt at the proper times.

public class SharedAccess {

private int sharedInt = -1;


private boolean producerTurn = true; // condition variable

public synchronized void setSharedInt(int val)


{
while (!producerTurn) { // not the producer's turn

try
{
System.out.println("Producer is waiting");
System.out.println("Consumer is consuming the value produced by
producer");
wait();
}
catch (InterruptedException e)
{
System.out.println(“Interrupted”);
}
}

sharedInt = val;
producerTurn = false;
notify(); // tell a waiting thread(consumer) to become ready
}

public synchronized int getSharedInt()


{

while (producerTurn) { // not the consumer's turn


try {
System.out.println("Consumer is waiting for producer
to produce the value");
System.out.println("Producer is Producing");

wait();
}
catch (InterruptedException e) {
System.out.println(“Interrupted”);
}
}

producerTurn = true;
notify(); // tell a waiting thread(producer) to become ready
return sharedInt;
}
}

// ProducerConsumerTest.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


// Show multiple threads modifying shared object.

public class ProducerConsumerTest {


public static void main( String args[] )
{
SharedAccess h =new SharedAccess();
Producer p = new Producer( h );
Consumer c = new Consumer( h );

p.start();
c.start();
}
}

OUTPUT

Producer:1
Producer is waiting
Consumer is consuming the value produced by producer
Consumer:1

Consumer is waiting for producer to produce the value


Producer is Producing
Producer:2
Producer is waiting
Consumer is consuming the value produced by producer
Consumer:2

Consumer is waiting for producer to produce the value


Producer is Producing
Producer3
Producer is waiting
Consumer is consuming the value produced by producer
Consumer:3

Consumer is waiting for producer to produce the value


Producer is Producing
Producer4
Producer is waiting
Consumer is consuming the value produced by producer
Consumer:4

Consumer is waiting for producer to produce the value


Producer is Producing
Producer:5
Producer is waiting
Consumer is consuming the value produced by producer
Consumer:5

//Addition.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//Write a program that creates a user interface to perform addition.
//The user enters two numbers in the textfields, Num1 and Num2.
//The addition of Num1 and Num2 is displayed in the Result field
//when the Additon button is clicked.

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

public class Addition extends JFrame implements ActionListener {


private JLabel numLabel;
private JLabel num2Label;
private JLabel resultLabel;
private JButton addBtn;

private JTextField num1Field;


private JTextField num2Field;
private JTextField resultField;

public Addition()
{
super("Addition");

Container c = getContentPane();
c.setLayout( new FlowLayout());

numLabel = new JLabel("Num1");


c.add(numLabel);
num1Field = new JTextField(10);
c.add(num1Field);

num2Label = new JLabel("Num2");


c.add(num2Label);
num2Field = new JTextField(10);
c.add(num2Field);

resultLabel = new JLabel("Result");


c.add(resultLabel);
resultField = new JTextField(10);
c.add(resultField);

addBtn = new JButton("Addition");


addBtn.addActionListener(this);
c.add(addBtn);

setSize(100,100);
setVisible(true);
}

public void actionPerformed(ActionEvent e)

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


{
String a = num1Field.getText();
int a1 = Integer.parseInt(a);

String b = num2Field.getText();
int b1 = Integer.parseInt(b);

int result = a1 + b1;


String result1 = String.valueOf(result);
resultField.setText(result1);

}
public static void main(String args[])
{
Addition add = new Addition();
add.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);

}
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//SignalLight.java
//Write a java program that simulates a traffic light.
//The program lets the user select one of three lights: red,
yellow,or //green.When a radio button is selected, the light is turned
on, and //only one light can be on at a time No light is on when the
program //starts.

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

public class SignalLight extends JFrame implements ItemListener {

private JRadioButton redLightBtn;


private JRadioButton greenLightBtn;
private JRadioButton yellowLightBtn;
JTextArea out;
ButtonGroup signal;

public SignalLight() {

Container c = getContentPane();
c.setLayout(new FlowLayout());

redLightBtn = new JRadioButton("redLight");


redLightBtn.addItemListener(this);
c.add(redLightBtn);

greenLightBtn = new JRadioButton("greenLight");


greenLightBtn.addItemListener(this);
c.add(greenLightBtn);

yellowLightBtn = new JRadioButton("YellowLight");


yellowLightBtn.addItemListener(this);
c.add(yellowLightBtn);

signal = new ButtonGroup();


signal.add(redLightBtn);
signal.add(greenLightBtn);
signal.add(yellowLightBtn);

setSize(250, 250);
setVisible(true);
}

public void itemStateChanged(ItemEvent e) {


Graphics g = getGraphics();

if (e.getSource() == redLightBtn) {
g.setColor(Color.RED);
g.fillOval(100, 100, 40, 40);
}

if (e.getSource() == greenLightBtn) {
g.setColor(Color.GREEN);

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


g.fillOval(100, 100, 40, 40);
}

if (e.getSource() == yellowLightBtn) {
g.setColor(Color.YELLOW);
g.fillOval(100, 100, 40, 40);
}

public static void main(String args[]) {


SignalLight app = new SignalLight();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);

}
}

OUTPUT

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//LineOvalRect.java
// Write a Java program that allows the user to draw lines,
// rectangles and ovals.

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

public class LineOvalRect extends JApplet{

public void paint(Graphics g)


{
g.setColor(Color.BLUE);
g.drawLine(50,10,150,10);
g.drawRect(50, 50, 100, 50);
g.drawOval(50, 150, 100, 50);
}
}

OUTPUT

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//Shape.java
//Write a java program to create an abstract class named Shape
//that contains an empty method named numberOfSides ( ).
//Provide three classes named Triangle,Pentagon and Hexagon
//such that each one of the classes extends the class Shape.
//Each one of the classes contains only the method numberOfSides( )
//that shows the number of sides in the given geometrical figures.

public abstract class Shape {


public abstract void noOfSides();

//Triangle.java
public class Triangle extends Shape{
public void noOfSides()
{
System.out.println("Triangle has 3 sides");
}
}

//Pentagon.java
public class Pentagon extends Shape{
public void noOfSides()
{
System.out.println("Pentagon has 5 sides");
}
}

//Hexagon.java
public class Hexagon extends Shape {
public void noOfSides()
{
System.out.println("Hexagon has 6 sides");
}
}

//ShapeTest.java
public class ShapeTest {

public static void main(String args[]) {


Shape s;

Triangle t = new Triangle();


t.noOfSides();
s = t;
s.noOfSides();

Pentagon p = new Pentagon();


p.noOfSides();
s = p;
s.noOfSides();

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


Hexagon h = new Hexagon();
h.noOfSides();
s = h;
s.noOfSides();
}
}

OUTPUT

Triangle has 3 sides


Triangle has 3 sides
Pentagon has 5 sides
Pentagon has 5 sides
Hexagon has 6 sides
Hexagon has 6 sides

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//LoginTable.java
//Write a program to create login table using JTable

import javax.swing.*;
import java.awt.*;
public class LoginTable extends JApplet {

public void init() {

// Get content pane


Container c = getContentPane();

// Set layout manager


c.setLayout(new BorderLayout());

// Initialize column headings


final String[] colHeads = { "UserName", "Passsword" };

// Initialize login with username and password


final String Login[][] = { { "Sana" , "1234" },
{ "Adam" , "qwer"},
{ "Sachin", "asdf" }
};

// Create the table


JTable table = new JTable(Login, colHeads);

JScrollPane scroller = new JScrollPane(table);

// Add scroll pane to the content pane


c.add(scroller);
}
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//ComboBoxTest.java
//create a comboBox and listen to its event

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboBoxTest extends JFrame implements ItemListener {
public String courses[] = {"CSE","ECE","EEE"};
public JComboBox courseComBox;

public ComboBoxTest()
{//get ContentPane and set its layout
Container c =getContentPane();
c.setLayout(new FlowLayout());

// set up JComboBox and register its event handler


courseComBox = new JComboBox(courses);
courseComBox.addItemListener(this);

//add the comboBox to container


c.add(courseComBox);
setSize(100,100);
setVisible(true);
}

//handle JComboBox event


public void itemStateChanged(ItemEvent e)
{
int index = courseComBox.getSelectedIndex();
String selected = courses[index];
JOptionPane.showMessageDialog(this,"u have selected "+selected);
}
public static void main(String args[])
{
ComboBoxTest app = new ComboBoxTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);

}
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//CheckBoxTest.java
//Create a CheckBox and listen to its event.

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

public class CheckBoxTest extends JFrame implements ItemListener {

public JCheckBox accept;


public JTextArea output;

public CheckBoxTest() {

super("CheckBoxTest");
//get the container and set its layout
Container c = getContentPane();
c.setLayout(new FlowLayout());

//Initialise the checkbox and register it with the ItemListener


accept = new JCheckBox("I accept the terms and agreement");
accept.addItemListener(this);
c.add(accept);

output = new JTextArea();


output.setEditable(false);
c.add(output);

setSize(300, 200);
setVisible(true);
}

//handle JCheckBox events


public void itemStateChanged(ItemEvent e) {
if (e.getSource() == accept)
{
if (e.getStateChange() == ItemEvent.SELECTED)
output.setText("\nYou have SELECTED I accept the terms and agreement");
else if (e.getStateChange() == ItemEvent.DESELECTED)
output.setText("\nYou have DESELECTED I accept the terms and agreement");

public static void main(String args[]) {


CheckBoxTest app = new CheckBoxTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


}

//ListTest.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


//Create a JList and Listen to its event

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

public class ListTest extends JFrame implements ListSelectionListener {


private JList cityList;
JTextArea output;

private String metroCities[] =


{ "Hyderabad","Bangalore","Chennai","Mumrbai","Pune","Delhi" };

public ListTest()
{
super( "List Test" );

Container c = getContentPane();
c.setLayout( new FlowLayout() );

// create a list with the items in the metroCities array


cityList = new JList( metroCities );
cityList.setVisibleRowCount( 3 );

// do not allow multiple selections


cityList.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION );

// add a JScrollPane containing the JList


// to the content pane
c.add( new JScrollPane( cityList ) );

output = new JTextArea();


c.add(output);

// set up event handler


cityList.addListSelectionListener(this);
setSize( 350, 150 );
setVisible(true);
}

//handling JList events


public void valueChanged( ListSelectionEvent e )
{
int index = cityList.getSelectedIndex();
String city = metroCities[index];
output.setText("You have selected " + city);

public static void main( String args[] )

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


{
ListTest app = new ListTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);

}
}

// KeyDemo.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


// Demonstrating keystroke events.

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

public class KeyDemo extends JFrame implements KeyListener {


private JTextArea output;

public KeyDemo()
{
super( "Demonstrating Keystroke Events" );

Container c = getContentPane();
c.setLayout(new FlowLayout());

output = new JTextArea( 10, 15 );


output.setText( "Press any key on the keyboard..." );
output.setEnabled( false );
c.add(output);

// allow frame to process Key events


addKeyListener( this );

setSize( 350, 100 );


setVisible(true);
}

public void keyPressed( KeyEvent e )


{
String key = e.getKeyText( e.getKeyCode() );
output.append("\nKey Pressed = " + key );

boolean actionKey = e.isActionKey();


if(actionKey == true)
output.append("\n"+ key + " is an action key");
}

public void keyReleased( KeyEvent e )


{
String key = e.getKeyText( e.getKeyCode() );
output.append("\nKey Released = " + key );

public void keyTyped( KeyEvent e )


{
char key = e.getKeyChar();
output.append("\nCharacter Key typed is = " + key );

public static void main( String args[] )

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


{
KeyDemo app = new KeyDemo();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


Adapter classes: Window adapter, mouse adapter, mouse motion adapter, key
adapter classes, anonymous inner class
//listening to key strokes
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class KeyAdapterDemo extends JFrame {

JTextArea output;
JLabel statusBar;

public KeyAdapterDemo() {
super("A simple paint program");

Container c = getContentPane();
c.setLayout(new FlowLayout());

output = new JTextArea(150, 10);


output.setText("press any key on the kryboard") ;
output.setEnabled(false);
c.add(output);

addKeyListener( new KeyAdapter() {


public void keyTyped(KeyEvent e) {
char key = e.getKeyChar();
output.append("\nCharacter key typed is = " + key);

}
});

setSize(300, 150);
setVisible(true);
}

public static void main(String args[]) {


KeyAdapterDemo app = new KeyAdapterDemo();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

//MouseAdapterDemo.java

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


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

public class MouseAdaptersDemo extends JFrame {


public JLabel outputLabel;

public MouseAdaptersDemo()
{
super( "Mouse Events" );

Container c = getContentPane();
c.setLayout(new FlowLayout());

outputLabel = new JLabel();


c.add(outputLabel);

addMouseListener(
new MouseAdapter() {
public void mouseClicked( MouseEvent e )
{
int x = e.getX();
int y = e.getY();
outputLabel.setText("Mouse Clicked at x = " + x + " y = "
+ y );
}
}
);

addMouseMotionListener(
new MouseMotionAdapter() {
public void mouseDragged( MouseEvent e )
{
int x = e.getX();
int y = e.getY();
outputLabel.setText("Mouse Dragged at x = " + x + " y = "
+ y );
}
}
);

setSize( 300, 150 );


setVisible(true);
}

public static void main( String args[] )


{
MouseAdaptersDemo app= new MouseAdaptersDemo();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.


}
);
}
}

Dr.VRK Women’s College Of Engg & Technology, Aziz Nagar, RR Dist.

You might also like