Multithreading Using Priorities Class Mythread1 Extends Thread (

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

1.

Multithreading Using Priorities


]

class MyThread1 extends Thread{


MyThread1(String s){
super(s);
start();
}

public void run(){


for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MAX_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}
}

class MyThread2 extends Thread{


MyThread2(String s){
super(s);
start();

public void run(){


for(int i=0;i<3;i++){
Thread cur=Thread.currentThread();
cur.setPriority(Thread.MIN_PRIORITY);
int p=cur.getPriority();
System.out.println("Thread Name :"+Thread.currentThread().getName());
System.out.println("Thread Priority :"+cur);
}
}

public class ThreadPriority{


public static void main(String args[]){
MyThread2 m2=new MyThread2("My Thread 2");
MyThread1 m1=new MyThread1("My Thread 1");

}
}
Output:

Thread Name :My Thread 2


Thread Priority :Thread[My Thread 2,1,main]
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 1,10,main]
Thread Priority :Thread[My Thread 2,1,main]
Thread Name :My Thread 1
Thread Name :My Thread 2
Thread Priority :Thread[My Thread 1,10,main]
Thread Priority :Thread[My Thread 2,1,main]
Thread Name :My Thread 1
Thread Priority :Thread[My Thread 1,10,main]
2. File & String Manipulations
import java.io.*;
importjava.util.*;

classWordCount {

public static void main(String[]args) {


Scanner in = new Scanner(System.in); // scanner object.
int words=0,lines=0,chars=0;
String temp;

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


File inputFile = new File(in.nextLine()); // reading file
Scanner wordScanner = new Scanner(inputFile);
Scanner lineScanner = new Scanner(inputFile);
wordScanner.useDelimiter("[^A-Za-z]+"); //

while(wordScanner.hasNext())
{
Temp = wordScanner.next(); // return next word if presents.
words++;
chars = chars + temp.length();
}
while(lineScanner.hasNextLine())// return boolean if line presents.
{
lineScanner.nextLine(); // return next line if presents.
lines++;
}
System.out.println("\nTotal Words = "+words+"\nTotal line =
"+lines+ "\nTotal characters = "+chars);
}catch(IOException e)
{
System.out.println(e);
}
}
}
Output:

Enter Your File Name :


WordCount.java

Total Words = 110


Total line = 32
Total characters = 609
3. Write an Applet Program to use various Controls and perform Font Animation.

importjava.awt.Font;
importjava.awt.FontMetrics;
importjava.awt.Graphics;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.awt.Color;

importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.Timer;

public class FontSizeAnimation extends JPanel implements ActionListener {


Timer timer;
int x = 1;

publicFontSizeAnimation() {
timer = new Timer(20, this);
timer.setInitialDelay(500);
timer.start();
}

public void paint(Graphics g) {


super.paintComponent(g);
Font font = new Font("Dialog", Font.PLAIN, x);
g.setFont(font);
FontMetricsfm = g.getFontMetrics();
String s = "I MSC";

int w = (int) getSize().getWidth();


int h = (int) getSize().getHeight();

intstringWidth = fm.stringWidth(s);
g.setColor(Color.blue);
g.drawString(s, (w - stringWidth) / 2, h / 2);
}

public static void main(String[] args) {


JFrame frame = new JFrame("FontSizeAnimation");
frame.add(new FontSizeAnimation());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent e) {


x += 1;
repaint();
}
}
Output:
4. Create a menu with submenu, popup menu, short cut keys, check box items
and separator.
Import javax.swing.*;
import java.awt.event.*;
public class SwingMenu{
public static void main(String[] args) {
SwingMenu s = new SwingMenu();
}

Public SwingMenu(){
JFrame frame = new JFrame("Creating a JMenuBar, JMenu, JMenuItem,
separator Component and Popup Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenu Barmenubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
filemenu.add(new JSeparator());
JMenu editmenu = new JMenu("Edit");
editmenu.add(new JSeparator());
JMenuItem fileItem1 = new JMenuItem("New");

fileItem1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{JOptionPane.showMessageDialog(null, "new", "You Have Clicked New",
JOptionPane.PLAIN_MESSAGE);}
});
JMenuItem fileItem2 = new JMenuItem("Open");
JMenuItem fileItem3 = new JMenuItem("Close");
fileItem3.add(new JSeparator());

JMenuItem fileItem4 = new JMenuItem("Save");


JMenuItem editItem1 = new JMenuItem("Cut");
JMenuItem editItem2 = new JMenuItem("Copy");
editItem2.add(new JSeparator());

JMenuItem editItem3 = new JMenuItem("Paste");


JMenuItem editItem4 = new JMenuItem("Insert");

Final JPopupMenu Pmenu;


JMenuItem menuItem;
Pmenu = new JPopupMenu();
menuItem = new JMenuItem("Cut");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Copy");
Pmenu.add(menuItem);
menuItem = new JMenuItem("Paste");
Pmenu.add(menuItem);
menuItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){}
});
frame.addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent Me)
{
if(Me.isPopupTrigger())
{
Pmenu.show(Me.getComponent(), Me.getX(), Me.getY());
}
}
});

filemenu.add(fileItem1);
filemenu.add(fileItem2);
filemenu.add(fileItem3);
filemenu.add(fileItem4);
editmenu.add(editItem1);
editmenu.add(editItem2);
editmenu.add(editItem3);
editmenu.add(editItem4);
menubar.add(filemenu);
menubar.add(editmenu);
frame.setJMenuBar(menubar);
frame.setSize(400,400);
frame.setVisible(true);
}
}
Output:
5. Implement calculator using Java AWT controls.
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
importjavax.swing.*;

public class CalculatorApplet extends Applet implements ActionListener


{
privateJButtonkeysArray[];
privateJPanelkeyPad;
privateJTextFieldlcdField;
private double result;
privateboolean first;
privatebooleanfoundKey;
staticbooleanclearText;
privateintprevOperator;

public void init()


{
lcdField = new JTextField(20);
keyPad = new JPanel ();
keysArray = new JButton[17];
result = 0.0;
prevOperator = 0;
first = true;
clearText = true;

//Set frame layout manager setLayout(new BorderLayout());

lcdField.setEditable(false);

//Create buttons
for (int i = 0; i <=9; i++)
keysArray[i] = new JButton(String.valueOf(i));
keysArray[10] = new JButton("/");
keysArray[11] = new JButton("*");
keysArray[12] = new JButton("-");
keysArray[13] = new JButton("+");
keysArray[14] = new JButton("=");
keysArray[15] = new JButton(".");
keysArray[16] = new JButton("CLR");

//Set panel layout manager


keyPad.setLayout(new GridLayout (4,4));

//Add button to keyPad panel


for (int i = 7; i <=10; i++) //adds Button 7,8,9, and divide to Panel
keyPad.add(keysArray[i]);

for (int i = 4; i <=6; i++) //adds buttons 4,5,6 to Panel


keyPad.add(keysArray[i]);
keyPad.add(keysArray[11]); //adds multiply button to Panel
for (int i = 1; i <= 3;i++) //adds buttons 1,2 and 3 to Panel
keyPad.add(keysArray[i]);
keyPad.add(keysArray[12]);//adds minus button to Panel
keyPad.add(keysArray[0]); //adds 0 key to Panel

for (int i = 15; i >=13; i--)


keyPad.add(keysArray[i]); //adds decimal point, equal, and addition keys Panel

add(lcdField, BorderLayout.NORTH); //adds text field to top of Frame


add(keyPad, BorderLayout.CENTER); //adds Panel to center of Frame
add(keysArray[16], BorderLayout.EAST); //adds Clear key to right side of applet

for(int i = 0; i <keysArray.length; i++)


keysArray[i].addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
foundKey = false;
//Search for the key pressed
for (int i = 0; i <keysArray.length&& !foundKey; i++)
if(e.getSource() == keysArray[i]) //key match found
{
foundKey = true;
switch(i)
{
case 0: case 1: case 2: case 3: case 4: //number buttons
case 5: case 6: case 7: case 8: case 9: //0-9
case 15:
if (clearText)
{
lcdField.setText("");
clearText = false;
}
lcdField.setText(lcdField.getText() +
keysArray[i].getText());
break;
case 10:// divide button
case 11:// multiply button
case 12:// minus button
case 13:// plus button
case 14:// equal button
clearText = true;
if (first) // First operand
{
if(lcdField.getText().length()==0)
result = 0.0;
else
result = Double.valueOf(lcdField.getText()).doubleValue();
first = false;
prevOperator = i; //save previous operator
}
else //second operand already enter, so calculator total
{
switch(prevOperator)
{
case 10: //divide Button
result /= Double.valueOf(lcdField.getText()).
doubleValue();
break;
case 11: //multiply Button
result *= Double.valueOf(lcdField.getText()).
doubleValue();
break;
case 12: //minus button
result -= Double.valueOf(lcdField.getText()).
doubleValue();
break;
case 13: //plus button
result += Double.valueOf(lcdField.getText()).
doubleValue();
break;
}
lcdField.setText(Double.toString(result));
if (i==14)//equal button
first = true;
else
prevOperator = i; //save previous opetator
}
break;

case 16://Clear button


clearText = true;
first = true;
lcdField.setText("");
result = 0.0;
prevOperator = 0;
break;
}
}
}
}

Calc.html:
<html>
<body>
<applet code="CalculatorApplet.class" width="350" height="350">
Java applet that draws calculator.
</applet>
</body>
</html>

Output:
6. Create a Student mark statement using JDBC control and display the
information using Table.
importjava.util.Scanner;
importjava.sql.*;

public class Student{


public String name;
public String id;
public double marks[]={0,0,0,0,0};
public double avg;
public String result;

public static void main(String[] args)


{
int choice=0;
int i;
Connection conn = null;
System.out.println("Student marksheet processing\n");
Student stud=new Student();;
Scanner nameread=new Scanner(System.in);
Scanner idread=new Scanner(System.in);
Scanner choiceread=new Scanner(System.in);
Scanner readmarks=new Scanner(System.in);
double a;

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:std");
}
catch(Exception e)
{
e.printStackTrace();
}

System.out.println("Enter the number of Students:");


choice=choiceread.nextInt();

for(i=0;i<choice;i++)
{
System.out.println("Enter your name:");
stud.name=nameread.nextLine();
System.out.println("Enter your id:");
stud.id=nameread.nextLine();
stud.avg=0;
stud.result = "Pass";
for(int j=0;j<5;j++)
{
System.out.println("Enter the "+(j+1)+" subject marks:");
stud.marks[j]=readmarks.nextDouble();
stud.avg += stud.marks[j];
if (stud.marks[j] < 50)
stud.result = "Fail";
}
stud.avg = stud.avg/5;
System.out.println("Name of student:"+stud.name+"\n"+"ID of student:"
+stud.id+"\n"+"Percentage obtained:"+stud.avg+" Result: "+stud.result);
try
{
Statement stmt=conn.createStatement();
String query = "insert into std
(id,name,mark1,mark2,mark3,mark4,mark5,avg,result) " +
"values('"+stud.id+"','"+stud.name+"',"+stud.marks[0]+
","+stud.marks[1]+","+stud.marks[2]+","+stud.marks[3]+","+
stud.marks[4]+","+stud.avg+",'"+stud.result+"')";
System.out.println(query);
stmt.executeUpdate(query);
}
catch(Exception e)
{
e.printStackTrace();
}
}
System.out.println("\nStudents List"+"\n");
System.out.println("ID"+"\t"+"Name"+"\t"+"Mark1"+"\t"+"Mark2"+"\t"+"Mark3"+
"\t"+"Mark4"+"\t"+"Mark5"+"\t"+"Avg"+"\t"+"Result"+"\n");

try
{
Statement stmt1=conn.createStatement();
ResultSetrs=stmt1.executeQuery("select * from std");
while(rs.next())
{
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getDouble(3)
+"\t"+rs.getDouble(4)
+"\t"+rs.getDouble(5)+"\t"+rs.getDouble(6)+"\t"+rs.getDouble(7)+"\t"+rs.ge
tDouble(8)+"\t"+rs.getString(9));
}
}
catch(Exception e)
{
e.printStackTrace();
}

}
}

Output:

Student marksheet processing

Enter the number of Students:


1
Enter your name:
Thangam
Enter your id:
S001
Enter the subject1 mark :
80
Enter the subject2 mark :
98
Enter the subject3 mark :
88
Enter the subject4 mark :
87
Enter the subject5 mark :
89

Name of student:Thangam
ID of student:s001
Percentage obtained:88.4
Result: Pass

Students List

ID Name Mark1 Mark2 Mark3 Mark4 Mark5 Avg Result

S002 Siva 78.0 89.0 56.0 56.0 60.0 67.8 Pass


S003 Sai 50.0 45.0 35.0 67.0 56.0 50.6 Fail
S004 shakthi 70.0 80.0 70.0 80.0 75.0 75.0 Pass
S005 Pandi 89.0 78.0 97.0 90.0 88.0 88.4 Pass
S001 Thangam 80.0 98.0 88.0 87.0 89.0 88.4 Pass
7. Program to implement Client/Server technology

//SendConsole.java

import java.net.*;
import java.io.*;
importjava.util.*;

public class SendConsole


{

public static void main(String[] args)


{
String filename,machinename;
System.out.println("\nEnter Filename");
Scanner in = new Scanner(System.in);
filename = in.nextLine();
System.out.println("\nEnter Machinename : ");
machinename = in.nextLine();
try{
intlen;
FileInputStream fin = new FileInputStream(filename);
len = fin.available();
byte[] arr = new byte[len];
System.out.println(filename+" "+len);
for(int i=0;i<len;i++)
{
arr[i] =(byte) fin.read();
}
InetAddressia = InetAddress.getByName(machinename);
System.out.println("is Created");
DatagramSocket ds = new DatagramSocket();
DatagramPacketdp = new DatagramPacket(arr,len,ia,777);
ds.send(dp);
System.out.println("\nPacketSent Successfully");
ds.close();
dp=null;
}
catch(Exception e)
{
System.out.println(e);
}
}
}

//ReceiveConsole.java

import java.net.*;
import java.io.*;
importjava.util.*;

public class ReceiveConsole


{

public static void main(String[] args)


{
String filename,machinename;
System.out.println("\nEnter Filename");
Scanner in = new Scanner(System.in);
filename = in.nextLine();

try
{
intlen=64000;
FileOutputStreamfout = new FileOutputStream(filename);
byte[] arr = new byte[64000];
DatagramSocket ds = new DatagramSocket(777);
DatagramPacketdp = new DatagramPacket(arr,len);
System.out.println("\nSocketCreated");
ds.receive(dp);
System.out.println("Packet Received");
for(int i=0;i<dp.getLength();i++)
{
fout.write((byte)arr[i]);
}
fout.close();
ds.close();
ds=null;
dp=null;
}
catch(Exception e)
{
System.out.println(e);
}
}

}
Output:

E:\AG college\I M.Sc java lab>java SendConsole

Enter Filename
SendConsole.java

Enter Machinename :
localhost
SendConsole.java 997
is created

Packet Sent Successfully

E:\AG college\I M.Sc java lab>java ReceiveConsole

Enter Filename
Temp.java

Socket created
Packet received
8. Write a Java program to create an Employee pay bill calculation using
various swing controls
import java.io.*;
importjava.awt.*;
importjavax.swing.*;
importjava.awt.event.*;
importjava.sql.*;
importjava.util.*;
classEmployeeInformation {
JFrame f;
JPanel p1,p2,p3;
JTabbedPanetp;
ImageIcon btnimg1,btnimg2;
JLabel l1, l2, l3, l4,l5,l6,l7,l8,l9,l10;
JTextField tf1,tf2,tf3,tf4,tf5,tf6,tf7,tf8,tf9,tf10;
JScrollPane sp1;
JButton savebtn,resetbtn,editbtn1,editbtn2,deletebtn ;

EmployeeInformation(){
f=new JFrame("Form");
p1=new JPanel(new GridLayout(5,2));
p2=new JPanel(new GridLayout(5,2));
p3=new JPanel(new GridLayout(2,2));
tp=new JTabbedPane();
l1=new JLabel("Employee ID:");
l2=new JLabel("Employee Name:");
l3=new JLabel("Employee Address:");
l4=new JLabel("Salary:");
l5=new JLabel("Enter Employee ID to delete record:");

l7=new JLabel("Employee ID:");


l8=new JLabel("Employee Name:");
l9=new JLabel("Employee Address:");
l10=new JLabel("Salary:");
tf1=new JTextField(12);
tf2=new JTextField(12);
tf3=new JTextField(12);
tf4=new JTextField(12);
tf5=new JTextField(12);
tf6=new JTextField(12);
tf7=new JTextField(12);
tf8=new JTextField(12);
tf9=new JTextField(12);
tf10=new JTextField(12);
savebtn=new JButton(" Add ");
resetbtn=new JButton(" Reset");
editbtn1=new JButton(" Edit ");
editbtn2=new JButton(" Save");
deletebtn=new JButton("Delete");

p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
p1.add(l3);
p1.add(tf3);
p1.add(l4);
p1.add(tf4);
p1.add(savebtn);
p1.add(resetbtn);
p2.add(l7);
p2.add(tf7);
p2.add(l8);
p2.add(tf8);
p2.add(l9);
p2.add(tf9);
p2.add(l10);
p2.add(tf10);
p2.add(editbtn1);
p2.add(editbtn2);
p3.add(l5);
p3.add(tf5);
p3.add(deletebtn);
resetbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEventae){
tf1.setText("");
tf2.setText("");
tf3.setText("");
tf4.setText("");
}
});
savebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEventae){
String value1=tf1.getText();
String value2=tf2.getText();
String value3=tf3.getText();
String value4=tf4.getText();
Connection con = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:std");PreparedStatement
st=con.prepareStatement("insert into emp(emp_id,emp_name,emp_address,salary)
values(?,?,?,?)");
st.setString(1,value1);
st.setString(2,value2);
st.setString(3,value3);
st.setString(4,value4);
st.executeUpdate();
JOptionPane.showMessageDialog(p1,"Data is successfully inserted into database.");
con.close();
}
catch(Exception e){
System.out.println(e);
JOptionPane.showMessageDialog(p1,"Error in submitting data!");
}
}
});
deletebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEventae){
String value1=tf5.getText();
Connection con = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:std");
PreparedStatementst=con.prepareStatement("DELETE FROM emp WHERE emp_id = ?");
st.setString(1,value1);
st.executeUpdate();
JOptionPane.showMessageDialog(p3,"Record is deleted successfully.");
con.close();
}
catch(Exception exp3)
{
JOptionPane.showMessageDialog(p3,"Error in deleting record.");
System.out.println(exp3);
}
}
});
editbtn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEventae){

String value=tf7.getText();
Connection con = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:std");
PreparedStatementst=con.prepareStatement("select * from emp where emp_id=?");
st.setString(1,value);
ResultSet res=st.executeQuery();
res.next();
tf7.setText(Integer.toString(res.getInt(1)));
tf8.setText(res.getString(2));
tf9.setText(res.getString(3));
tf10.setText(Integer.toString(res.getInt(4)));
con.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(p2,"Can not edit data");
}
}
});
editbtn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEventae){
Connection con = null;
try
{
int x=JOptionPane.showConfirmDialog(p2,"Confirm edit? All data will be replaced");
if(x==0){
try{
String value1=tf7.getText();
String value2=tf8.getText();
String value3=tf9.getText();
String value4=tf10.getText();

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:std");
Statement st=con.createStatement();
st.executeUpdate("update emp set emp_name='"+value2+"',
emp_address='"+value3+"', salary='"+value4+"' where emp_id='"+value1+"'");
JOptionPane.showMessageDialog(p2,"Updated successfully");
con.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(p2,"Error in updating edit fields");
System.out.println(ex);
}
}
}
catch(Exception ex)
{
System.out.println(ex);
JOptionPane.showMessageDialog(p2,"Error");
}
}
});
}
void dis()
{
f.getContentPane().add(tp);
tp.addTab("Add Record",p1);
tp.addTab("Edit Record",p2);
tp.addTab("Delete Record",p3);

f.setSize(350,180);
f.setVisible(true);
f.setResizable(true);
}
public static void main(String z[]){
EmployeeInformation pro=new EmployeeInformation();
pro.dis();
}
}

Output:
CONTENT
S.No Page
Date Name of the Experiment Initial
. No.

1 Multithreading Using Priorities

2 File & String Manipulations

Applet Program using various


3 Controls and perform Font Animation

Create a menu with submenu, popup


4 menu, short cut keys, check box items
and separator

Implement calculator using Java


5 AWT controls

Create a Student mark statement


6 using JDBC control and display the
information using Table

Program to implement Client/Server


7 technology
Java program to create an Employee
8 pay bill calculation using various
swing controls

Signature of the Staff I/C

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy