You are on page 1of 25

EXPERIMENT 14

AIM- WRITE A PROGRAM TO IMPLEMENT EXCEPTION HANDLING USING ALL 5 KEYWORDS (TRY, CATCH, THROW,
THROWS AND FINALLY).

SOURCE CODE:

package First;
class exception {
// Unhandled Exceptions are specified
static void procA() throws IllegalAccessException {

System.out.println("inside procA");
throw new IllegalAccessException("procA throwing an exception which it cant handle on its own using
'throws' clause");

static void procB() {


try {

System.out.println("inside procB");
throw new NullPointerException("Manually thrown Exception using 'throw' clause");
}
catch (NullPointerException e)
{
System.out.println(e+"\nCaught Inside procB");
}
finally {
System.out.println("procB finally statement. Executed after the try and catch clause\n");
}
}
// Return from within a try block.
static void procC() {
try {
System.out.println("inside procC");
return;
} finally {
System.out.println("procC's finally statement. Excecuted after try and before its return statement");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println(e+"\nException caught in procA using 'catch' \n");
}
procB();
procC();
}
}

Chaudhary Sarimurrab 00314807218


OUTPUT:

Chaudhary Sarimurrab 00314807218


EXPERIMENT 15

AIM- WRITE A PROGRAM TO IMPLEMENT PRODUCER CONSUMER PROBLEM IN JAVA USING THREAD
SYNCHRONIZATION.

SOURCE CODE:

import java.util.Scanner;
class Q {
int n;
boolean signal = false;
synchronized int consume() {
while(!signal)
try {
System.out.println("Consumer thread sleeps");

wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consumer thread awakes");
System.out.println("Consumed: " + n);
signal = false;
notify();
return n;
}
synchronized void produce(int n) {
while(signal)
try {
System.out.println("Producer thread sleeps");
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;

System.out.println("Producer thread awakes");


signal = true;
System.out.println("Produced: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
int n;
Producer(Q q,int n) {
this.n=n;
this.q = q;
new Thread(this, "Producer").start();
}
Chaudhary Sarimurrab 00314807218
public void run() {
System.out.println("Producer thread created");
int i = 0;
while(i<n) {
q.produce(++i);
}

System.out.println("Producer thread sleeps");

}
}
class Consumer implements Runnable {
Q q;
int n;
Consumer(Q q,int n) {
this.q = q;
this.n=n;
new Thread(this, "Consumer").start();

}
public void run() {
System.out.println("Consumer thread created");
while(true) {
q.consume();
}

}
}
public class synch {
public static void main(String[] args) {
int n;
System.out.println("Enter the production limit");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
System.out.println("The production limit is "+n);
Q q = new Q();
new Producer(q,n);
new Consumer(q,n);

}
}

Chaudhary Sarimurrab 00314807218


OUTPUT:

Chaudhary Sarimurrab 00314807218


EXPERIMENT 16

AIM- WRITE A PROGRAM TO SHOW DEADLOCKS BETWEEN TWO THREADS IN JAVA

SOURCE CODE:

class A {
synchronized void foo(B b) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("A Interrupted");
}
System.out.println(name + " trying to call B.method()");
b.method();
}
synchronized void method() {
System.out.println("Inside A.method");
}
}
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call A.method()");
a.method();
}
synchronized void method() {
System.out.println("Inside A.method");
}
}
class synch implements Runnable {
A a = new A();
B b = new B();
synch() {
Thread.currentThread().setName("MainThread");
System.out.println(Thread.currentThread().getName()+" invoked");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b);
System.out.println("Back in main thread"); // THIS WILL NEVER OCCUR
}

Chaudhary Sarimurrab 00314807218


public void run() {
System.out.println("New Thread with name "+Thread.currentThread().getName()+" created");
System.out.println(Thread.currentThread().getName()+" invoked");
b.bar(a);
System.out.println("Back in other thread"); // THIS WILL NEVER OCCUR
}
public static void main(String args[]) {
new synch();
}
}

// Program will not terminate ever as a deadlock situation is created

OUTPUT:

Chaudhary Sarimurrab 00314807218


EXPERIMENT 17

AIM- WRITE A PROGRAM TO CONNECT DATABASE WITH JAVA USING JDBC DRIVERS.

SOURCE CODE:

import java.sql.*;
import java.util.Scanner;

public class database {

public static void main(String args[]) throws Exception


{
Scanner sc= new Scanner(System.in);
String url="jdbc:mysql://localhost:3306/ansh?useSSL=false&autoReconnect=true";
String user="root";
String pass="7879";
String fetch_query="select * from students";
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection(url,user,pass);
Statement st= con.createStatement();
ResultSet rs=st.executeQuery(fetch_query);
// rs.next();
System.out.println("INITIAL TABLE\n");
System.out.printf("%15s %15s %15s %15s\n","NAME","ENROLLMENT_NUM","BRANCH","MARKS");

while(rs.next())
{ String name=rs.getString("NAME");
int roll= rs.getInt("ENROLLMENT_NUM");
String branch=rs.getString("BRANCH");
int marks=rs.getInt("MARKS");
System.out.printf("%15s %15d %15s %15d\n",name,roll,branch,marks);

}
System.out.println("Enter the name, enrollment_num,branch and marks of a student to add in table");
String name1=sc.next();
int roll1 =sc.nextInt();
String branch1=sc.next();
int marks1=sc.nextInt();

Chaudhary Sarimurrab 00314807218


String insquery="insert into students values ("+"'"+name1+"'"+","+roll1+","+"'"+branch1+"'"+","+marks1+")";
// System.out.println(insquery);

int count=st.executeUpdate(insquery);
System.out.println(count+" rows affected");
rs=st.executeQuery(fetch_query);
System.out.println("\n\nUPDATED TABLE\n");
System.out.printf("%15s %15s %15s %15s\n","NAME","ENROLLMENT_NUM","BRANCH","MARKS");

while(rs.next())
{ String name=rs.getString("NAME");
int roll= rs.getInt("ENROLLMENT_NUM");
String branch=rs.getString("BRANCH");
int marks=rs.getInt("MARKS");
System.out.printf("%15s %15d %15s %15d\n",name,roll,branch,marks);

}
st.close();
con.close();

}
}

Chaudhary Sarimurrab 00314807218


OUTPUT AND SQL TABLES:

ORIGINAL TABLE IN DATABASE:

Chaudhary Sarimurrab 00314807218


EXPERIMENT 18

AIM- CREATE A SERVLET WHICH USES COOKIES TO STORE THE NUMBER OF TIMES A USER HAS VISITED THE
SERVLET.

SOURCE CODE:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class myServlet extends HttpServlet

static int i=1;

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String k=String.valueOf(i);

Cookie c = new Cookie("visit",k);

response.addCookie(c);

int j=Integer.parseInt(c.getValue());

if(j==1)

out.println("Welcome for the first time on myServlet");

else

out.println("HEY,You visited "+i+" times on myServlet");

i++;

Chaudhary Sarimurrab 00314807218


OUTPUT

Chaudhary Sarimurrab 00314807218


EXPERIMENT 19

AIM- CREATE A SIMPLE TEXT EDITOR LIKE WORDPAD USING SWINGS IN JAVA.

SOURCE CODE:

import javax.swing.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.plaf.metal.*;
class editor extends JFrame implements ActionListener {
JTextArea t;
JFrame f;
editor() throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException,
IllegalAccessException {

f = new JFrame("editor");
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
t = new JTextArea();
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("File");
JMenuItem mi1 = new JMenuItem("New");
JMenuItem mi2 = new JMenuItem("Open");
JMenuItem mi3 = new JMenuItem("Save");
JMenuItem mi9 = new JMenuItem("Print");
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi9.addActionListener(this);
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m1.add(mi9);
JMenu m2 = new JMenu("Edit");
JMenuItem mi4 = new JMenuItem("cut");
JMenuItem mi5 = new JMenuItem("copy");
JMenuItem mi6 = new JMenuItem("paste");
JMenuItem mi7=new JMenuItem("select all");
mi4.addActionListener(this);
mi5.addActionListener(this);
mi6.addActionListener(this);
mi7.addActionListener(this);
m2.add(mi4);
m2.add(mi5);
m2.add(mi6);
m2.add(mi7);
JMenuItem mc = new JMenuItem("close");
mc.addActionListener(this);

Chaudhary Sarimurrab 00314807218


mb.add(m1);
mb.add(m2);
mb.add(mc);
f.setJMenuBar(mb);
f.add(t);
f.setSize(500, 500);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("cut")) {
t.cut();
}
else if (s.equals("copy")) {
t.copy();
}
else if (s.equals("paste")) {
t.paste();
}
else if (s.equals("select all")) {
t.selectAll();
}
else if (s.equals("Save")) {
JFileChooser j = new JFileChooser("d:");
int r = j.showSaveDialog(null);

if (r == JFileChooser.APPROVE_OPTION) {
File fi = new File(j.getSelectedFile().getAbsolutePath());
try {
FileWriter wr = new FileWriter(fi, false);
BufferedWriter w = new BufferedWriter(wr);
w.write(t.getText());
w.flush();
w.close();
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f, evt.getMessage());
}
}
else
JOptionPane.showMessageDialog(f, "the user cancelled the operation");
}
else if (s.equals("Print")) {
try {
t.print();
}
catch (Exception evt) {

Chaudhary Sarimurrab 00314807218


JOptionPane.showMessageDialog(f, evt.getMessage());
}
}
else if (s.equals("Open")) {
JFileChooser j = new JFileChooser("f:");
int r = j.showOpenDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
File fi = new File(j.getSelectedFile().getAbsolutePath());
try {
String s1 = "", sl = "";
FileReader fr = new FileReader(fi);
BufferedReader br = new BufferedReader(fr);
sl = br.readLine();
while ((s1 = br.readLine()) != null) {
sl = sl + "\n" + s1;
}
t.setText(sl);
}
catch (Exception evt) {
JOptionPane.showMessageDialog(f, evt.getMessage());
}
}
else
JOptionPane.showMessageDialog(f, "the user cancelled the operation");
}
else if (s.equals("New")) {
t.setText("");
}
else if (s.equals("close")) {
f.setVisible(false);
}
}
public static void main(String args[]) throws ClassNotFoundException, UnsupportedLookAndFeelException,
InstantiationException, IllegalAccessException {
editor e = new editor();
}
}

Chaudhary Sarimurrab 00314807218


SCREENSHOTS OF EDITOR

Chaudhary Sarimurrab 00314807218


EXPERIMENT 20

AIM- CREATE A SCIENTIFIC CALCULATOR USING SWINGS IN JAVA

SOURCE CODE:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Calculator extends JFrame {
private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN, 20);
private JTextField textfield;
private boolean number = true;
private String equalOp = "=";
private CalculatorOp op = new CalculatorOp();
public Calculator() {
textfield = new JTextField("", 12);
textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);
ActionListener numberListener = new NumberListener();
String buttonOrder = "1234567890 ";
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < buttonOrder.length(); i++) {
String key = buttonOrder.substring(i, i+1);
if (key.equals(" ")) {
buttonPanel.add(new JLabel(""));
} else {
JButton button = new JButton(key);
button.addActionListener(numberListener);
button.setFont(BIGGER_FONT);
buttonPanel.add(button);
}
}
ActionListener operatorListener = new OperatorListener();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 4, 4));
String[] opOrder = {"+", "-", "*", "/","=","C","sin","cos","log"};
for (int i = 0; i < opOrder.length; i++) {
JButton button = new JButton(opOrder[i]);
button.addActionListener(operatorListener);
button.setFont(BIGGER_FONT);
panel.add(button);
}
JPanel pan = new JPanel();
pan.setLayout(new BorderLayout(4, 4));
pan.add(textfield, BorderLayout.NORTH );
pan.add(buttonPanel , BorderLayout.CENTER);
pan.add(panel , BorderLayout.EAST);
Chaudhary Sarimurrab 00314807218
this.setContentPane(pan);
this.pack();
this.setTitle("Calculator");
this.setResizable(false);
}
private void action() {
number = true;
textfield.setText("");
equalOp = "=";
op.setTotal("");
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String displayText = textfield.getText();
if (e.getActionCommand().equals("sin"))
{
textfield.setText("" + Math.sin(Double.valueOf(displayText).doubleValue()));
}else
if (e.getActionCommand().equals("cos"))
{
textfield.setText("" + Math.cos(Double.valueOf(displayText).doubleValue()));
}
else
if (e.getActionCommand().equals("log"))
{
textfield.setText("" + Math.log(Double.valueOf(displayText).doubleValue()));
}
else if (e.getActionCommand().equals("C"))
{
textfield.setText("");
}
else
{
if (number)
{ action();
textfield.setText("");

}
else
{ number = true;
if (equalOp.equals("="))
{
op.setTotal(displayText);
}else
if (equalOp.equals("+"))
{
op.add(displayText);
}

Chaudhary Sarimurrab 00314807218


else if (equalOp.equals("-"))
{
op.subtract(displayText);
}
else if (equalOp.equals("*"))
{
op.multiply(displayText);
}
else if (equalOp.equals("/"))
{
op.divide(displayText);
}
textfield.setText("" + op.getTotalString());
equalOp = e.getActionCommand(); } } } }
class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String digit = event.getActionCommand();
if (number) {
textfield.setText(digit);
number = false;
} else {
textfield.setText(textfield.getText() + digit); } }
}
public class CalculatorOp {
private int total;
public CalculatorOp() {
total = 0; }
public String getTotalString() {
return ""+total; }
public void setTotal(String n) {
total = convertToNumber(n); }
public void add(String n) {
total += convertToNumber(n); }
public void subtract(String n) {
total -= convertToNumber(n); }
public void multiply(String n) {
total *= convertToNumber(n); }
public void divide(String n) {
total /= convertToNumber(n); }
private int convertToNumber(String n) {
return Integer.parseInt(n); } }}
class ACalculator {
public static void main(String[] args) {
JFrame frame = new Calculator();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Chaudhary Sarimurrab 00314807218


SCREENSHOT OF CALCULATOR

Chaudhary Sarimurrab 00314807218


EXPERIMENT 21

AIM- WRITE A PROGRAM TO DEMONSTRATE THE LIFE CYCLE OF APPLETS.

SOURCE CODE:

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
/*<applet code="AppletLifeCycle.class" width="350" height="150"> </applet>*/
public class AppletLifeCycle extends Applet
{
public void init()
{
setBackground(Color.CYAN);
System.out.println("init() called");
}
public void start(){ System.out.println("Start() called"); }
public void paint(Graphics g){ System.out.println("Paint(() called"); }

public void stop() { System.out.println("Stop() Called"); }


public void destroy() { System.out.println("Destroy)() Called"); }
}

OUTPUT:

Chaudhary Sarimurrab 00314807218


EXPERIMENT 22

AIM- WRITE A PROGRAM TO CREATE ANALOG CLOCK USING APPLETS IN JAVA.

SOURCE CODE:

import java.util.*;

import java.text.*;

import java.applet.*;

import java.awt.*;

public class SimpleAnalogClock extends Applet implements Runnable

{ int clkhours = 0, clkminutes = 0, clkseconds = 0;

String clkString = "";

int clkwidth, clkheight;

Thread thr = null;

boolean threadSuspended;

public void init()

{ clkwidth = getSize().width;

clkheight = getSize().height;

setBackground(Color.black);

public void start()

{ if (thr == null)

{ thr = new Thread(this);

thr.setPriority(Thread.MIN_PRIORITY);

threadSuspended = false;

thr.start();

} else

{ if (threadSuspended)

{ threadSuspended = false;

synchronized(this)

{ notify(); } } } }

public void stop()

threadSuspended = true;

Chaudhary Sarimurrab 00314807218


}

public void run()

{ try

{ while (true)

{ Calendar clndr = Calendar.getInstance();

clkhours = clndr.get(Calendar.HOUR_OF_DAY);

if (clkhours > 12) clkhours -= 12;

clkminutes = clndr.get(Calendar.MINUTE);

clkseconds = clndr.get(Calendar.SECOND);

SimpleDateFormat frmatter = new SimpleDateFormat("hh:mm:ss", Locale.getDefault());

Date d = clndr.getTime();

clkString = frmatter.format(d);

if (threadSuspended)

synchronized(this)

while (threadSuspended)

wait();

} } }

repaint();

thr.sleep(1000);

} catch (Exception e)

void drawHand(double angle, int radius, Graphics grp)

angle -= 0.5 * Math.PI;

int a = (int)(radius * Math.cos(angle));

int b = (int)(radius * Math.sin(angle));

grp.drawLine(clkwidth / 2, clkheight / 2, clkwidth / 2 + a, clkheight / 2 + b);

Chaudhary Sarimurrab 00314807218


void drawWedge(double angle, int radius, Graphics grp)

angle -= 0.5 * Math.PI;

int a = (int)(radius * Math.cos(angle));

int b = (int)(radius * Math.sin(angle));

angle += 2 * Math.PI / 3;

int a2 = (int)(5 * Math.cos(angle));

int b2 = (int)(5 * Math.sin(angle));

angle += 2 * Math.PI / 3;

int a3 = (int)(5 * Math.cos(angle));

int b3 = (int)(5 * Math.sin(angle));

grp.drawLine(clkwidth / 2 + a2, clkheight / 2 + b2, clkwidth / 2 + a, clkheight / 2 + b);

grp.drawLine(clkwidth / 2 + a3, clkheight / 2 + b3, clkwidth / 2 + a, clkheight / 2 + b);

grp.drawLine(clkwidth / 2 + a2, clkheight / 2 + b2, clkwidth / 2 + a3, clkheight / 2 + b3);

public void paint(Graphics grp)

grp.setColor(Color.gray);

drawWedge(2 * Math.PI * clkhours / 12, clkwidth / 5, grp);

drawWedge(2 * Math.PI * clkminutes / 60, clkwidth / 3, grp);

drawHand(2 * Math.PI * clkseconds / 60, clkwidth / 2, grp);

grp.setColor(Color.white);

grp.drawString(clkString, 10, clkheight - 10);

grp.drawString("C-Sharpcorner.com", 113, 300);

/*

<applet code="SimpleAnalogClock.class" width="350" height="350">

</applet>

/*

Chaudhary Sarimurrab 00314807218


OUTPUT:

Chaudhary Sarimurrab 00314807218

You might also like