siddhartha · 4/2/2017  · welcome to siddhartha engineering college enter valid number 7 7 is...

42
SIDDHARTHA Institute of Engineering and Technology Department of Computer Science &Engineering JAVA Programming Lab Manual [Subject Code: A40585] For the Academic year 2015-16 II B Tech II Semester

Upload: others

Post on 23-Aug-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

SIDDHARTHA

Institute of Engineering and Technology

Department of Computer Science &Engineering

JAVA Programming Lab Manual

[Subject Code: A40585]

For the Academic year 2015-16

II B Tech II Semester

Page 2: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

List of Experiments

1. Use eclipse or Netbean platform and acquaint with the various menus, create a test

project, add a test class and run it see how you can use auto suggestions, auto fill. Try

code formatter and code refactoring like renaming variables, methods and classes. Try

debug step by step with a small program of about 10 to 15 lines which contains at least

one if else condition and a for loop.

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 divide by zero.

3. a. Develop an applet that displays a simple message

b. Develop an Applet that receives an integer in one text field & compute its factorial

value & returns it in another text filed when the button “Compute” is clicked

4. Write a program that creates a user interface to perform integer divisions. The user enters

two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is

displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were

not an integer, the program would throw a NumberFormatException. If Num2 were Zero,

the program would throw an Arithmetic Exception Display the exception in a message

dialog box

5. Write a java program that implements a multi-thread application that has three threads.

First thread generates random integer every 1 second and if the value is even, second

thread computes the square of the number and prints. If the value is odd, the third thread

will print the value of cube of the number.

6. Write a java program that connects to a database using JDBC and does add, deletes,

modify and retrieve operations

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 a selected

color. Initially there is no message shown.

8. Write a java program to create an abstract class named Shape that contains two integers

and an empty method named printArea(). Provide three classes named Rectangle,

Triangle and Circle such that each one of the classes extends the class Shape. Each one of

the classes contain only the method printArea( ) that prints the area of the given shape.

Page 3: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

9. Suppose that a table named Table.txt is stored in a text file. The first line in the file header

and the remaining lines correspond to row in the table. The elements are separated by

commas. Write a Java program to display the table using labels in grid layout.

10. Write a Java program that handles all mouse events and shows the event name at the

center of the window when a mouse event is fired. (Use adapter classes).

11. Write a java program that loads names and phone numbers from a text file where the data

is organized as one line per record and each field in a record are separated by a tab (\t).it

takes a name or phone number as input and prints the corresponding other value from the

hash table(hint: use hash tables)

12. Implement the above program with database instead of a text file.

13. Write a java program that takes tab separated data (one record per line) from a text file

and inserts them into a database

14. Write a java program that prints the meta-data of a given table.

Page 4: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

1. Use eclipse or Net bean platform and acquaint with the various menus, create a test

project, add a test class and run it see how you can use auto suggestions, auto fill. Try code

formatter and code refactoring like renaming variables, methods and classes. Try debug

step by step with a small program of about 10 to 15 lines which contains at least one if else

condition and a for loop.

Aim: Implement sample java program using eclipse or Netbeans & use its code formatter

code refactoring (renaming variable) & debug step by step.

Program: import java.util.*;

public class Testp

{

public static void main(String[] args) {

System.out.println("Welcome to Siddhartha Engineering College");

Scanner sc = new Scanner(System.in);

System.out.println("Enter valid Number");

int n = sc.nextInt();

int c = 0;

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

if (n % i == 0) {

c++;

}

}

if (c == 2)

{

System.out.println(n + "is Prime Number");

}

else

{

System.out.println(n + "is not Prime Number");

}

}

}

Output:

E:\java>javac Testp.java

E:\java>java Testp

Welcome to Siddhartha Engineering College

Enter valid Number

7

7 is Prime Number

Page 5: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

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 divide by zero.

Aim: Implement simple calculator using grid layout.

ALGORITHM: Input: Press the values and operation in the calculator

Output: Displays the values in the text field

1 Start

2 take applet

3 add new Labels

4 call action performed method.

5 Check the type of operation.

6 Compute the Result.

7 Display the Result.

8 Stop

Program: import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

class A extends JFrame implements ActionListener

{

public JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16;

public JTextField tf1;

public JPanel p;

public String v = "";

public String v1 = "0";

public String op = "";

public A() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);

p = new JPanel(new FlowLayout());

tf1 = new JTextField(10);

p.add(tf1);

add(p);

setLayout(new GridLayout(0, 3));

b1 = new JButton("1");

b1.addActionListener(this);

add(b1);

b2 = new JButton("2");

b2.addActionListener(this);

add(b2);

b3 = new JButton("3");

b3.addActionListener(this);

add(b3);

b4 = new JButton("4");

b4.addActionListener(this);

Page 6: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

add(b4);

b5 = new JButton("5");

b5.addActionListener(this);

add(b5);

b6 = new JButton("6");

b6.addActionListener(this);

add(b6);

b7 = new JButton("7");

b7.addActionListener(this);

add(b7);

b8 = new JButton("8");

b8.addActionListener(this);

add(b8);

b9 = new JButton("9");

b9.addActionListener(this);

add(b9);

b10 = new JButton("0");

b10.addActionListener(this);

add(b10);

b11 = new JButton("+");

b11.addActionListener(this);

add(b11);

b12 = new JButton("-");

b12.addActionListener(this);

add(b12);

b13 = new JButton("*");

b13.addActionListener(this);

add(b13);

b14 = new JButton("/");

b14.addActionListener(this);

add(b14);

b16 = new JButton("%");

b16.addActionListener(this);

add(b16);

b15 = new JButton("=");

b15.addActionListener(this);

add(b15);

setVisible(true);

}

public void actionPerformed(ActionEvent ae)

{

String b = ae.getActionCommand();

switch (b)

{

case "1":

Page 7: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

{

v = v + "1";

tf1.setText(v);

}

break;

case "2": {

v = v + "2";

tf1.setText(v);

}

break;

case "3": {

v = v + "3";

tf1.setText(v);

}

break;

case "4": {

v = v + "4";

tf1.setText(v);

}

break;

case "5": {

v = v + "5";

tf1.setText(v);

}

break;

case "6": {

v = v + "6";

tf1.setText(v);

}

break;

case "7": {

v = v + "7";

tf1.setText(v);

}

break;

case "8": {

v = v + "8";

tf1.setText(v);

}

break;

case "9": {

v = v + "9";

tf1.setText(v);

}

break;

Page 8: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

case "0": {

v = v + "0";

tf1.setText(v);

}

break;

case "+": {

op = "+";

v1 = tf1.getText();

v = "";

}

break;

case "-": {

op = "-";

v1 = tf1.getText();

v = "";

}

break;

case "*": {

op = "*";

v1 = tf1.getText();

v = "";

}

break;

case "/": {

op = "/";

v1 = tf1.getText();

v = "";

}

break;

case "%": {

op = "%";

v1 = tf1.getText();

v = "";

}

break;

case "=": {

switch (op) {

case "+": {

v = tf1.getText();

if (v.equals("")) {

v = "0";

}

long i = Long.parseLong(v1) + Long.parseLong(v);

tf1.setText(String.valueOf(i));

v="";

Page 9: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

}

break;

case "-": {

v = tf1.getText();

if (v.equals("")) {

v = "0";

}

long i = Long.parseLong(v1) - Long.parseLong(v);

tf1.setText(String.valueOf(i));

v="";

}

break;

case "*": {

v = tf1.getText();

if (v.equals("")) {

v = "0";

}

long i = Long.parseLong(v1) * Long.parseLong(v);

tf1.setText(String.valueOf(i));

v="";

}

break;

case "/": {

try {

v = tf1.getText();

if (v.equals("")) {

v = "0";

}

long i = Long.parseLong(v1) / Long.parseLong(v);

tf1.setText(String.valueOf(i));

v="";

} catch (Exception ex) {

JOptionPane.showMessageDialog(this, ex.getMessage());

}

}

break;

case "%": {

try {

v = tf1.getText();

if (v.equals("")) {

v = "0";

}

long i = Long.parseLong(v1) % Long.parseLong(v);

tf1.setText(String.valueOf(i));

v="";

Page 10: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

} catch (Exception ex) {

JOptionPane.showMessageDialog(this, ex.getMessage());

}

}

break;

}

}

break;

}

}

}

public class Calc

{

public static void main(String[] args)

{

A a = new A();

}

}

Output:

Page 11: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

3. a) Develop an applet that displays a simple message.

Aim: Implement Applet to display a simple message.

Algorithm: Input: Enter the Message

Output: Displays the message in applet

Step1: start

Step 2: Create one class with Simple Applet

Step3: compute the data

Step 4: Display the Data

Step 5: Stop

PROGRAM:

import java.applet.Applet;

import java.awt.*;

public class Sms extends Applet {

public void init() {

}

public void paint(Graphics g) {

g.setColor(Color.blue);

Font font = new Font("verdana", Font.BOLD, 15);

g.setFont(font);

g.drawString("Welcome To Siddhartha Eng College", 50, 50);

}

}

/*

<applet code=Sms.class height=300 width=400>

</applet>

*/

output:

Page 12: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

3.b) Develop an Applet that receives an integer in one text field & compute its factorial value &

returns it in another text filed when the button “Compute” is clicked.

Aim: Implement an Applet program that calculates the factorial of a given number.

Algorithm:

Input: Value of „T1‟

Output: Compute the factorial value

Step1: Start.

Step2: Import java.awt pack, and relevant packages.

Step3: Import java.lang.string,awt. event,applet.Applet packages.

Step4: Create Class that extends Applet implements Action Listener

Step5: Create Buttons and Text Fields.

Step6: Create the Data. To set variables in the fields.

Step7: Compute the data.

Step8: Print the Data.(display)

Step9: Stop.

PROGRAM

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);

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);

Page 13: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

}

public void actionPerformed(ActionEvent ae)

{

long n = Integer.parseInt(tf1.getText());

long f = 1;

while (n != 0)

{

f = f * n;

n--;

}

tf2.setText(String.valueOf(f));

}

}

/*

<applet code=Fact.class height=300 width=400>

</applet>

*/

Output:

Page 14: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

4. Write a program that creates a user interface to perform integer divisions. The user enters two

numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the

Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program

would throw a NumberFormatException. If Num2 were Zero, the program would throw an

Arithmetic Exception Display the exception in a message dialog box.

Aim: Implement a user interface to perform integer division and handle Arithmetic Exception.

Algorithm:

Input: Values of Text field T1, T2

Output: Displays the result in Text field T3

Step1: Start.

Step2: Import java.awt package

Step3: Import java.lang.string,awt. event,applet.Applet packages.

Step4: Create Class

Step5: Create Buttons and Text Fields.

Step6: Create the Data.

Step7: Perform the division.

Step8: Print the Data.

Step9: Stop.

PROGRAM:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

class A extends JFrame implements ActionListener {

JLabel l1, l2, l3;

JTextField tf1, tf2, tf3;

JButton b1;

A() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());

l1 = new JLabel("Welcome");

setSize(800, 400);

l1 = new JLabel("Enter Number1");

add(l1);

tf1 = new JTextField(10);

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);

Page 15: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

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)

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 JavaApplication {

public static void main(String[] args) {

A a = new A();

}

}

Output:

Page 16: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

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.

Aim: Implement multithreading concept using a simple application.

Algorithm:

Input: Enter the threads

Output: Displays multiple threads

Step1: Start.

Step2: Import the packages.

Step3: Create multiple threads class.

Step4: Create Multiple thread Implements Runnable{ }.

Step5: Initialize the threads.

Step6: Creating entry point for the thread.

Step7: Use exceptions.

Step8: Create multiple thread demo, Create main() Start threads.

Step9: Display the threads (Three threads)

Step10: Stop .

PROGRAM

import java.util.*;

class even implements Runnable

{

public int x;

public even(int x)

{

this.x = x;

}

public void run()

{

System.out.println("Thread Name:Even Thread and " + x + "is even Number and

Square of " + x + " is: " + x * x);

}

}

class odd implements Runnable

{

public int x;

public odd(int x)

{

this.x = x;

}

public void run()

{

Page 17: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

System.out.println("Thread Name:ODD Thread and " + x + " is odd number and Cube

of " + x + " is: " + x * x * x);

}

}

class A extends Thread

{

public String tname;

public Random r;

public Thread t1, t2;

public A(String s)

{

tname = s;

}

public void run() {

int num = 0;

r = new Random();

try {

for (int i = 0; i < 50; i++) {

num = r.nextInt(100);

System.out.println("Main Thread and Generated Number is " + num);

if (num % 2 == 0) {

t1 = new Thread(new even(num));

t1.start();

} else {

t2 = new Thread(new odd(num));

t2.start();

}

Thread.sleep(1000);

System.out.println("--------------------------------------");

}

} catch (Exception ex) {

System.out.println(ex.getMessage());

}

}

}

public class Mthread {

public static void main(String[] args) {

A a = new A("One");

a.start();

}

}

Page 18: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

Output:

Page 19: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

6).Write a java program that connects to a database using JDBC and does add, deletes, modify and

retrieve operations

Aim: Implement the Database connectivity program using JDBC to perform add, delete and modify.

Algorithm:

Input: Enter the connection detail.

Output: Perform add, delete, modify and retrieve operation.

1: Start.

2: Import the packages.

3: Make the connection.

4: Create another class for making operations.

5: Another class for retrieve the operation.

6: Display the output.

9: Stop.

PROGRAM

import java.sql.*;

import javax.sql.*;

import java.util.*;

class CRUD

{

public static void main(String[] args)

{

Connection cn;

Statement st;

ResultSet rs;

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

con = DriverManager. getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","system");

st = cn.createStatement();

System.out.println("------MENU------");

System.out.println("1.Insert");

System.out.println("2.EDIT");

System.out.println("3.Delete");

System.out.println("4.Display");

System.out.println("5.Exit");

System.out.println("----------------");

String opt = "";

String htno = "", sname = "", mobile = "", sql = "";

Scanner sc = new Scanner(System.in);

while (opt != "5") {

System.out.println("Enter Your Option");

opt = sc.next();

switch (opt) {

case "1": {

System.out.println("Enter Htno");

Page 20: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

htno = sc.next();

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

sname = sc.next();

System.out.println("Enter Mobile");

mobile = sc.next();

sql = "insert into stu values(" + "'" + htno + "'" + "," + "'" + sname + "'" + "," + "'" + mobile + "'" + ")";

if (st.executeUpdate(sql) > 0) {

System.out.println("Record Inserted");

}

}

break;

case "2": {

System.out.println("Enter Htno to Update");

htno = sc.next();

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

sname = sc.next();

System.out.println("Enter Mobile");

mobile = sc.next();

sql = "update stu set sname=" + "'" + sname + "'" + "," + "mobile=" + "'" + mobile + "'" + " where

htno='" + htno + "'";

if (st.executeUpdate(sql) > 0) {

System.out.println("Record Updated");

} else {

System.out.println("Operation Failed");

}

}

break;

case "3": {

System.out.println("Enter Htno to delete");

htno = sc.next();

sql = "delete from stu where Htno=" + "'" + htno + "'";

if (st.executeUpdate(sql) > 0) {

System.out.println("Record deleted");

} else {

System.out.println("Operation Failed");

}

}

break;

case "4": {

sql = "select * from stu";

rs = st.executeQuery(sql);

System.out.println("Htno\tSname\tMobile");

while (rs.next()) {

System.out.println(rs.getString("Htno") + "\t" + rs.getString("SName") + "\t" +

rs.getString("mobile"));

Page 21: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

}

rs.close();

}

break;

case "5": {

opt = "5";

System.out.println("Thank You");

st.close();

cn.close();

}

break;

default: {

System.out.println("Choose Option between 1 and 5 only");

}

}

}

}

catch (Exception ex) {

System.out.println(ex.getMessage());

}

}

}

Page 22: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

Output:

Page 23: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

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 a selected color. Initially there is no

message shown.

Aim: Implement traffic light using AWT layouts.

Algorithm:

Input: Create the traffic light GUI

Output: Perform the traffic light operation

Step1: Start.

Step2: Import all relevant packages.

Step3: Create a Class that Extends ItemListener.

Step4: Create Check boxes.

Step5: Create init() process to initialize checkboxes.

Step6: Create a panel and Set the Layout for Grid().

Step7: Initialize the boxes and add the data ( colours).

Step8: Call method paint to colour using Graphics

Step9: Set the colour and draw.

Step10: Display.

Step11: Stop

PROGRAM

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

class A extends JFrame implements ItemListener {

public JLabel l1, l2;

public JRadioButton r1, r2, r3;

public ButtonGroup bg;

public JPanel p, p1;

public A() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridLayout(2, 1));

setSize(800, 400);

p = new JPanel(new FlowLayout());

p1 = new JPanel(new FlowLayout());

l1 = new JLabel();

Font f = new Font("Verdana", Font.BOLD, 60);

l1.setFont(f);

add(l1);

p.add(l1);

add(p);

l2 = new JLabel("Select Lights");

p1.add(l2);

JRadioButton r1 = new JRadioButton("Red Light");

Page 24: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

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(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 class Tlights {

public static void main(String[] args) {

A a = new A();

}

}

Page 25: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

Output:

Page 26: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

8) Write a java program to create an abstract class named Shape that contains two integers and an

empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle such

that each one of the classes extends the class Shape. Each one of the classes contain only the

method printArea( ) that prints the area of the given shape.

Aim: Implement abstract class using the concept of inheritance.

Algorithm:

Input: Creates GUI

Output: number of sides a triangle, trapezoid and Hexagon

1: Start.

2: Create one abstract Class Shape with method numberofSides().

3: Create classes triangle, trapezoid and Hexagon which will extend Shape.

4: Implement the method “numberofSides()” in each class.

5: Create class cointating main().

6: Display each class method.

7: Stop the Program.

PROGRAM

abstract class Shape {

public int x, y;

public abstract void printArea();

}

class Rectangle extends Shape {

public void printArea() {

System.out.println("Area of Rectangle is " + x * y);

}

}

class Triangle extends Shape {

public void printArea() {

System.out.println("Area of Triangle is " + (x * y) / 2);

}

}

class Circle extends Shape {

public void printArea() {

System.out.println("Area of Circle is " + (22 * x * x) / 7);

}

}

public class Abstex {

public static void main(String[] args) {

// TODO code application logic here

Rectangle r = new Rectangle();

r.x = 10;

r.y = 20;

r.printArea();

System.out.println("-------------------------------------");

Page 27: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

Triangle t = new Triangle();

t.x = 30;

t.y = 35;

t.printArea();

System.out.println("-------------------------------------");

Circle c = new Circle();

c.x = 2;

c.printArea();

System.out.println("-------------------------------------");

}

}

Output:

Page 28: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

9) Suppose that a table named Table.txt is stored in a text file. The first line in the file header and the

remaining lines correspond to row in the table. The elements are separated by commas. Write a Java

program to display the table using labels in grid layout.

Aim: Display the content of a text file using tables in grid layout.

Algorithm:

Input: Enter the text file

Output: Displays the text file information in Table

1: Start.

2: Import all relevant packages

3: Create a Class which extends JFrame class.

4: Create init process for initialization

5: Create and initialize column headings

6: Initialize the data

7: create the table

8: Add the table to a scroll pane

9: add the scroll pane to the content pane

10: Display the table contents

11: Stop

PROGRAM:

import java.io.*;

import java.util.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

class A extends JFrame {

public A() {

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

GridLayout g = new GridLayout(0, 3);

setLayout(g);

try {

FileInputStream fin = new FileInputStream("E:\\emp.txt");

Scanner sc = new Scanner(fin).useDelimiter(",");

String[] arrayList;

String a;

while (sc.hasNextLine()) {

a = sc.nextLine();

arrayList = a.split(",");

for (String i : arrayList) {

add(new JLabel(i));

}

}

} catch (Exception ex) {

Page 29: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

}

setDefaultLookAndFeelDecorated(true);

pack();

setVisible(true);

}

}

public class Tbl {

public static void main(String[] args) {

A a = new A();

}

}

Output:

Page 30: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

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

Aim: Implement all mouse events using adapter classes.

ALGORITHM:

Input: Mouse Operation

Output: Displays the all mouse functions

1. Start the program.

2. Import the packages of applet, awt, awt.event.

3. Create a class, methods.

4. Mouse moments, mouse Clicked, mouse Pressed, mouse Released, mouse Entered, mouse Exited,

mouse Dragged events args.

5. Write g.drawString() application of Graphical User Interface.

6. While rotating mouse event args.

7. The mouse event arguments execution.

8. Printing in the separated Applet viewer window.

9. Stop the program.

PROGRAM:

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

/*<applet code="MouseDemo" width=300 height=300>

</applet>*/

public class MouseDemo extends Applet implements MouseListener,MouseMotionListener

{

int mx=0;

int my=0;

String msg="";

public void init()

{

addMouseListener(this);

addMouseMotionListener(this);

}

public void mouseClicked(MouseEvent me)

{

mx=20;

my=40;

msg="Mouse Clicked";

repaint();

}

public void mousePressed(MouseEvent me)

{

mx=30;

my=60;

Page 31: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

msg="Mouse Pressed";

repaint();

}

public void mouseReleased(MouseEvent me)

{

mx=30;

my=60;

msg="Mouse Released";

repaint();

}

public void mouseEntered(MouseEvent me)

{

mx=40;

my=80;

msg="Mouse Entered";

repaint();

}

public void mouseExited(MouseEvent me)

{

mx=40;

my=80;

msg="Mouse Exited";

repaint();

}

public void mouseDragged(MouseEvent me)

{

mx=me.getX();

my=me.getY();

showStatus("Currently mouse dragged"+mx+" "+my);

repaint();

}

public void mouseMoved(MouseEvent me)

{

mx=me.getX();

my=me.getY();

showStatus("Currently mouse is at"+mx+" "+my);

repaint();

}

public void paint(Graphics g)

{

g.drawString("Handling Mouse Events",30,20);

g.drawString(msg,60,40);

}}

Page 32: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

Output:

Page 33: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

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)

Aim: Implement a program to display the content of a text file using hash tables.

ALGORITHM:

Input: Enter the text file

Output: Displays all the data using hash table

1. Start the program.

2. Import the packages of Io.BufferdReader, io.File, io.FileNotFoundException, io.FileReader,

IOException, util.HashTable, utilIterator, util.Set.

3. Create classes, methods.

4. Create Hash Table and store the data in Hash table from file.

5. Use Iterator interface to search the value.

6. After getting the input value print the other value from Hash Table.

7. Print the output.

8. Stop the Program.

Program:

import java.util.*;

import java.io.*;

public class Hashtbl {

public static void main(String[] args) {

try {

FileInputStream fs = new FileInputStream("E:\\ph.txt");

Scanner sc = new Scanner(fs).useDelimiter("\\s+");

Hashtable<String, String> ht = new Hashtable<String, String>();

String[] arrayList;

String a;

System.out.println("HASH TABLE IS");

System.out.println("--------------------------");

System.out.println("KEY : VALUE");

while (sc.hasNext()) {

a = sc.nextLine();

arrayList = a.split("\\s+");

ht.put(arrayList[0], arrayList[1]);

System.out.println(arrayList[0] + ":" + arrayList[1]);

}

System.out.println("----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);

Page 34: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

while (opt != "3") {

System.out.println("Enter Your Option 1,2,3");

opt = s.next();

switch (opt) {

case "1": {

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

name = s.next();

if (ht.containsKey(name)) {

System.out.println("Mobile is " + ht.get(name));

} else {

System.out.println("Not Found");

}

}

break;

case "2": {

System.out.println("Enter mobile");

mobile = s.next();

if (ht.containsValue(mobile)) {

for (@SuppressWarnings("rawtypes") Map.Entry e : ht.entrySet()) {

if (mobile.equals(e.getValue())) {

System.out.println("Name is " + e.getKey());

}

}

} else {

System.out.println("Not Found");

}

}

break;

case "3": {

opt = "3";

System.out.println("Menu Successfully Exited");

}

break;

default:

System.out.println("Choose Option betwen 1 and Three");

break;

}

}

} catch (Exception ex) {

System.out.println(ex.getMessage());

}

}

}

Page 35: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

Output:

Page 36: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

12).Implement the above program with database instead of a text file.

Aim: Implement the program to display the content of database using hash table.

ALGORITHM: Input: Enter data in database using java program.

Output: Displays the data from database using java program.

1. Start the program.

2. Import the packages of Io.BufferdReader, io.File, io.FileNotFoundException, io.FileReader,

IOException, util.HashTable, utilIterator, util.Set.

3. Create classes, methods.

4. Create Hash Table and store the data in Hash table from file.

5. Use Iterator interface to search the value.

6. After getting the input value print the other value from Hash Table.

7. Print the output.

8. Stop the Program.

Program: import java.sql.*;

import java.util.*;

public class Hashtbl2 {

public static void main(String[] args) {

Connection cn;

Statement st;

ResultSet rs;

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

cn = DriverManager. getConnection("jdbc:oracle:thin:@localhost:1521:XE" ,"system","system");

st = cn.createStatement();

rs = st.executeQuery("select * from phone");

Hashtable<String, String> ht = new Hashtable<String, String>();

System.out.println("HASH TABLE IS");

System.out.println("--------------------------");

System.out.println("KEY : VALUE");

while (rs.next()) {

ht.put(rs.getString("Name"), rs.getString("Mobile"));

System.out.println(rs.getString("Name") + ":" + rs.getString("Mobile"));

}

rs.close();

st.close();

cn.close();

System.out.println("Welcome TO Siddhartha Eng College");

System.out.println("----MENU------");

System.out.println("----1.Search by Name------");

System.out.println("----2.Search by Mobile------");

System.out.println("----3.Exit------");

String opt = "";

String name, mobile;

Scanner s = new Scanner(System.in);

while (opt != "3") {

System.out.println("Enter Your Option 1,2,3");

opt = s.next();

Page 37: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

switch (opt) {

case "1": {

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

name = s.next();

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)) {

for (Map.Entry e : ht.entrySet()) {

if (mobile.equals(e.getValue())) {

System.out.println("Name is " + e.getKey());

}

}

} else {

System.out.println("Not Found");

}

}

break;

case "3": {

opt = "3";

System.out.println("Menu Successfully Exited");

}

break;

default:

System.out.println("Choose Option betwen 1 and Three");

break;

}

}

} catch (Exception ex) {

System.out.println(ex.getMessage());

}

}

}

Program Output:

Page 38: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid
Page 39: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

13).Write a java program that takes tab separated data (one record per line) from a text file

and inserts them into a database.

Aim: Implement a program to read data from text file and insert in the database.

ALGORITHM: Input: Enter data in database using java program.

Output: Displays the data from database using java program.

1. Start the program.

2. Import the packages of BufferedReader,File,FileNotFoundException, FileReader,Exception,

Connection,PreparedStatement,ResultSet,SQLException,Statement,Hashtable,util.Iterator.

3. Create classes, methods.

4. Create Hash Table and store the data in Hash table from file.

5. Use ConnectionUtil class and writeDatatoDatabase method.

6. After getting the input value print the other value from Hash Table.

7. Print the output.

8. Stop the Program.

Program: import java.sql.*;

import java.io.*;

import java.util.*;

public class Tbltodb {

public static void main(String[] args) {

Connection cn;

Statement st;

try

{

Class.forName("oracle.jdbc.driver.OracleDriver");

cn = DriverManager. getConnection("jdbc:oracle:thin:@localhost:1521:XE" ,"system","system");

st=cn.createStatement();

String sql="";

FileInputStream fin=new FileInputStream("E:\\emp1.txt");

Scanner sc=new Scanner(fin);

String[] arrayList;

String a="";

int i=0;

while(sc.hasNext())

{

a=sc.nextLine();

arrayList =a.split("\\s+");

sql="insert into emp1 values("+"'"+arrayList[0]+"','"+arrayList[1]+"','"+arrayList[2]+"')";

st.execute(sql);

i++;

System.out.println(arrayList[0]+":"+arrayList[1]+":"+arrayList[2]);

}

System.out.println(i+" Records are inserted");

st.close();

cn.close();

}

catch(Exception ex)

{

System.out.println(ex.getMessage());

}

Page 40: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

}

}

Output:

Page 41: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

14).Write a java program that prints the meta-data of a given table.

Aim: Implement a program to display metadata of a given table.

ALGORITHM: Input: Enter the text file

Output: Displays all the data using hash table 1. Start the program. 2. Import the packages of sql.Connection, sql.ResultSetMetaData, sql.SQLException, sql.Statement; 3. Create classes, methods. 4. Create connection object and ResultSet object. 5. Use printMetaData method to extract the metadata of table. 6. Print the output. 7. Stop the Program.

Program: import java.sql.*;

import java.util.*;

public class Tblmdata {

public static void main(String[] args) {

Connection cn;

Statement st;

ResultSet rs, rs1;

ResultSetMetaData rsmd;

try {

Scanner sc = new Scanner(System.in);

System.out.println("Enter Database Name");

String dbname = sc.next();

System.out.println("Enter Password");

String pass = sc.next();

Class.forName("oracle.jdbc.driver.OracleDriver");

cn = DriverManager. getConnection("jdbc:oracle:thin:@localhost:1521:XE" ,"system","system");

st = cn.createStatement();

DatabaseMetaData dm = cn.getMetaData();

rs = dm.getTables(cn.getCatalog(), "%", "%", null);

String s = "";

String sql = "select * from ", sql1 = "";

System.out.println("-----------Database is " + dbname);

System.out.println("-------------------------");

System.out.println("Tables are");

System.out.println("-------------------------");

while (rs.next()) {

sql1 = "";

System.out.println("-------Table Name: " + rs.getString(3) + "---------");

sql1 = sql + rs.getString(3);

rs1 = st.executeQuery(sql1);

rsmd = rs1.getMetaData();

System.out.println("Columns are ");

System.out.println("Column Name\tColumn Type\tSize");

for (int i = 1; i <= rsmd.getColumnCount(); i++) {

System.out.println(rsmd.getColumnLabel(i) + "\t" + rsmd.getColumnTypeName(i) + "\t" +

rsmd.getColumnDisplaySize(i));

Page 42: SIDDHARTHA · 4/2/2017  · Welcome to Siddhartha Engineering College Enter valid Number 7 7 is Prime Number . 2. Write a Java program that works as a simple calculator. Use a grid

}

System.out.println("----------------------------------");

}

rs.close();

cn.close();

} catch (Exception ex) {

System.out.println(ex.getMessage());

}

}

}

Output: