Sie sind auf Seite 1von 38

1.

Employee Processing – Using Class

import java.io.*;
public class Employee
{
String name;
int age;
String designation;
double salary;
// This is the constructor of the class Employee
public Employee(String empName)
{
name = empName;
}
// Assign the age of the Employee to the variable age.
public void empAge(int empAge)
{
age = empAge;
}
/* Assign the designation to the variable designation.*/
public void empDesignation(String empDesig)
{
designation = empDesig;
}
/* Assign the salary to the variable salary.*/
public void empSalary(double empSalary)
{
salary = empSalary;
}
/* Print the Employee details */
public void printEmployee()
{
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
public static void main(String args[])
{
Employee e=new Employee("Ram");
e.empAge(40);
e.empDesignation("Programmer");
e.empSalary(43005.00);
e.printEmployee();
}
}

2 . Program using ‘this’ keyword

import java.io.*;
public class ThisClass
{
int a,b,c;
public ThisClass(int x,int y)
{
this.a=x;
this.b=y;
}
/* Print the Sum */
public void sum()
{
this.c=this.a+this.b;
System.out.println("Value of A:"+ this.a );
System.out.println("Value of B:" + this.b );
System.out.println("Sum is:" + this.c );
}
public static void main(String args[])
{
ThisClass tc=new ThisClass(5,10);
tc.sum();
}
}

3 . Program for Method Overloading

class Calculator
{
public int add( int a, int b)
{
System.out.println("Int and Int Addition");
return a+b;
}
public float add( float a, float b)
{
System.out.println("Float and Float Addition ");
return a+b;
}
public float add( float a, int b)
{
System.out.println("Float and Int Addition ");
return a+b;
}
public static void main(String args[ ])
{
Calculator c= new Calculator( );
System.out.println(c.add(20,10));
System.out.println(c.add(2.5f,10));
System.out.println(c.add(1.5f,10.5f));
}
}

4. Program for Method Overriding

class A
{
int i, j;
A(int a, int b)
{
i = a; j = b;
}
void show()
{
// display i and j
System.out.println("i and j: " + i + "" + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show()
{
// display k – this overrides show() in A
System.out.println("Over ride”);
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}

5. Program using Single Inheritance

import java.io.*;
class Base
{
int empno;
float sal;
Base(int a,float b)
{
empno=a;
sal=b;
}
void put()
{
System.out.println("Employee Number is:"+empno+"\nSalary : "+sal);
}
}
class Derived extends Base
{
String name;
Derived(int a, float b, String n) /* Sub class Constructor */
{
super(a,b);
name=n;
}
void put()
{
super.put();
System.out.println("Employee Name is :"+name);
}
}
class SingleInher
{
public static void main(String args[])
{
Derived d=new Derived(10,200000.00f,"Kalam");
d.put();
}
}

6. Program for Multiple Inheritance using Interface

class Student
{
String name;
int n;
public Student(String tname, int tn)
{
name=tname;
n=tn;
}
void put()
{
System.out.println("Number Is : "+n+"\nName Is : "+name);
}
}
interface StudInt
{
String college="AVC";
String course="MCA";
}
class Interface1 extends Student implements StudInt
{
long phone;
public Interface1(String tname,int tn,long tphone)
{
super(tname,tn);
phone=tphone;
}
void put()
{
super.put();
System.out.println("Course Is : "+course+"\nCollege Is : "+college+"\nPhone
Is : " + phone);
}
public static void main(String args[])
{
Interface1 s=new Interface1("Raja",100,9842561278);
s.put();
}
}

7. Program for Interthreading

class ItemQueue
{
int n;
boolean flag=false;
synchronized int remove()
{
if(!flag)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught :");
}
System.out.println("Item received : "+n);
flag=false;
notify();
return n;
}
synchronized void insert(int n)
{
if(flag)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught :");
}
this.n=n;
flag=true;
System.out.println("Item placed : "+n);
notify();
}
}
class A implements Runnable
{
ItemQueue q;
A(ItemQueue q)
{
this.q=q;new Thread(this,"Producer Thread").start();
}
public void run()
{
int i=0;
while(true)
{
q.insert(i++);
}
}
}
class B implements Runnable
{
ItemQueue q;
B(ItemQueue q)
{
this.q=q;
new Thread(this,"Consumer Thread").start();
}
public void run()
{
while(true)
{
q.remove();
}
}
}
class ThreadEx
{
public static void main(String args[])
{
System.out.println("Beginning");
ItemQueue q=new ItemQueue();
B b=new B(q);
A a=new A(q);
System.out.println("Enter Control-C to stop !");
}
}
8. Sum of Two values Using User defined Packages

/* onePack.java and stored within the package p1 */


package p1;
import java.io.*;
public class OnePack
{
int x;
public int readX() throws IOException
{
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter A Value : ");
x=Integer.parseInt(d.readLine());
return x;
}
}
/* two.java and stored in jdk1.6\bin */
import p1.OnePack;
import java.io.*;
class Two
{
int y;
Two()
{
y=100;
}
public static void main(String args[]) throws IOException
{
OnePack p=new OnePack();
Two t=new Two();
int c=p.readX() + t.y;
System.out.println("sum is : "+c);
}
}
9. Java Program Using Exceptions Handling Mechanism

import java.io.* ;
import java.lang.Exception ;
public class HandleError
{
public static void main( String[] args )
{
int a = 2 ; int b = 3 ; int c = 5 ; int d = 0 ; int e = 1 ; int f = 3 ;
try
{
System.out.println( a+"/"+b+" = "+div( a, b ) ) ;
System.out.println( c+"/"+d+" = "+div( c, d ) ) ;
}
catch( Exception except )
{
System.out.println( "Caught exception " + except.getMessage() ) ;
}
System.out.println( e+"/"+f+" = "+div( e, f ) ) ;
}
static int div( int a, int b )
{
return (a/b) ;
}
}

10. Calculator Program using Frames


import java.awt.*;
import java.awt.event.*;
import java.awt.Font;
class Calculator implements ActionListener
{
//Declaring Objects
Frame f=new Frame();
Font fo=new Font("Times New Roman",Font.BOLD,16);
Label l=new Label("CALCULATOR PROGRAM USING FRAME");
Label l1=new Label("First Number");
Label l2=new Label("Second Number");
Label l3=new Label("Result");
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();
Button b1=new Button("Add");
Button b2=new Button("Sub");
Button b3=new Button("Mul");
Button b4=new Button("Div");
Button b5=new Button("Clear");
Calculator()
{
//Giving Coordinates
l.setBounds(50,60,400,20);
l1.setBounds(50,100,100,20);
l2.setBounds(50,140,100,20);
l3.setBounds(50,180,100,20);
t1.setBounds(200,100,100,20);
t2.setBounds(200,140,100,20);
t3.setBounds(200,180,100,20);
b1.setBounds(50,250,50,20);
b2.setBounds(110,250,50,20);
b3.setBounds(170,250,50,20);
b4.setBounds(230,250,50,20);
b5.setBounds(290,250,50,20);
//Adding components to the frame
f.add(l);
f.add(l1);
f.add(l2);
f.add(l3);
f.add(t1);
f.add(t2);
f.add(t3);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
f.setLayout(null);
f.setVisible(true);
f.setSize(400,350);
f.setFont(fo);
}
public void actionPerformed(ActionEvent e)
{
double n1=Double.parseDouble(t1.getText());
double n2=Double.parseDouble(t2.getText());
if(e.getSource()==b1)
{
t3.setText(String.valueOf(n1+n2));
}
if(e.getSource()==b2)
{
t3.setText(String.valueOf(n1-n2));
}
if(e.getSource()==b3)
{
t3.setText(String.valueOf(n1*n2));
}
if(e.getSource()==b4)
{
t3.setText(String.valueOf(n1/n2));
}
if(e.getSource()==b5)
{
System.exit(0);
}
}
public static void main(String args[])
{
Calculator c=new Calculator();
}
}

11. Temperature Conversion using Applet

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Font;
public class convApplet extends Applet implements ItemListener,ActionListener
{
Choice c;
TextField d,res;
public void init()
{
setLayout(null);
setBackground(Color.yellow);
Font myf=new Font("Times New Roman",Font.BOLD,20);
setFont(myf);
Label l1=new Label("Enter value : ",Label.LEFT);
d=new TextField(20);
res=new TextField(20);
Label l2=new Label("Result :",Label.LEFT);
c=new Choice();
c.addItem("C to F");
c.addItem("F to C");
l1.setBounds(90,100,150,30);
add(l1);
l2.setBounds(90,150,100,30);
add(l2);
d.setBounds(250,100,100,30);
add(d);
res.setBounds(200,150,60,30);
add(res);
c.setBounds(350,100,100,30);
add(c);
d.addActionListener(this);
res.addActionListener(this);
c.addItemListener(this);
}
public void actionPerformed(ActionEvent ae)
{}
public void itemStateChanged(ItemEvent e)
{
float f=Float.parseFloat(d.getText());
switch(c.getSelectedIndex())
{
case 0:
double s=0;
s=(f*1.8)+32;
res.setText(String.valueOf(s));
showStatus("Celsius value of"+f+"is"+s);
break;
case 1:
double a=0;
a=(f-32)*5/9;
res.setText(String.valueOf(a));
showStatus("Fahrenheit value"+f+"is"+a);
break;
}
repaint();
}
public void paint(Graphics g)
{
g.drawString("Temperature Conversion Program",200,20);
}
}
/*<Html>
<Title> Temperature Conversion </Title>
<applet code="convApplet" width=400 height=450></applet>
</Html>*
12. Draw Graphical Shapes using Applet

import java.awt.*;
import java.applet.*;
public class GraphicsEx extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10, 10,50,50);
g.drawLine( 10,50,50, 10);
g.drawRect(150,160,50,40);
g.drawRect(180,150,50,60);
g.drawOval(20,30,40,40);
g.drawOval( 120,30,60,40);
g.drawArc(30,40,60,50,0,75);
g.drawArc(30, 100,60,50,75, 180);

}
}
/*<applet code=GraphicsEx height=400 width=400>
</applet>*/

13.File Processing

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

class FileOperation
{
public static void main(String args[])throw IOException,FileNotFoundException,NumberFormatException
{
FileInputStream fin;
FileOutputStream fout;
int i,choice,j;
boolean created;
DataInputStream d=new DataInputStream(System.in);
String s1,s,dummy;
File f,f1;
do
{
System.out.println("1. New\t2. Open\t3. Copy\t4. Rename\t5.Delete\t 6.Path \t7.Length");
System.out.println("Enter Your Wish : ");
choice=Integer.parseInt(d.readLine());
switch(choice)
{
case 1:
System.out.println("Enter File Name : ");
s=d.readLine();
f=new File(s);
if(!f.exists())
{
fout=new FileOutputStream(s);
System.out.println("Enter Data : ");
i=0;
while(i!=-1)
{
i=System.in.read();
fout.write(i);
}
fout.close();
System.out.println("File Created !");
}
else
System.out.println("File already Exists");
dummy=d.readLine();
break;
case 2:
System.out.println("Enter File Name to Open : ");
s=d.readLine();
f=new File(s);
if(f.exists())
{
fin=new FileInputStream(s);
do
{
i=fin.read();
if(i!=-1)
System.out.print((char)i);
}
while(i!=-1);
fin.close();
}
else
System.out.println("File Not Exists");
dummy=d.readLine();
break;
case 3:
System.out.println("Enter Source File Name to Open : ");
s=d.readLine();
f=new File(s);
if(f.exists())
{
System.out.println("Enter Target File : ");
s1=d.readLine();
f1=new File(s1);
if(!f1.exists())
{
fin=new FileInputStream(s);
fout=new FileOutputStream(s1);
do
{
i=fin.read();
if(i!=-1)
fout.write(i);
}
while(i!=-1);

fin.close();
fout.close();
}
}
else
System.out.println("Source File Not Found");
dummy=d.readLine();
break;

case 4:
System.out.println("Enter Filename to Rename");
s=d.readLine();
f=new File(s);
System.out.println("Enter New Filename ");
s1=d.readLine();
f1=new File(s1);
f.renameTo(f1);
break;
case 5:
System.out.println("Enter Filename to Delete");
s=d.readLine();
f=new File(s);
f.delete();
System.out.println("File is Deleted !");
break;
case 6:
System.out.println("Enter Filename to Find Path");
s=d.readLine();
f=new File(s);
if(f.exists())
System.out.println("Path : "+f.getAbsolutePath());
else
System.out.println("File Not Found");
break;
case 7:
System.out.println("Enter Filename to Find Length : ");
s=d.readLine();
f=new File(s);
if(f.exists())
System.out.println("Length of : "+f.getName()+" is :
"+f.length()+" Bytes");
else
System.out.println("File Not Found");
break;
case 8: break;
}
}
while(choice!=8);
}
}

14. Arithmetic Operations – Using Remote Method Invocation


/* computeInt.java */
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface computeInt extends Remote


{
int add(int a,int b)throws RemoteException;
int sub(int a,int b)throws RemoteException;
int mul(int a,int b)throws RemoteException;
int div(int a,int b)throws RemoteException;
}

/* comserver.java */
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
public class comserver extends UnicastRemoteObject implements computeInt
{
public comserver()throws RemoteException
{
super();
}
public int add(int a,int b)throws RemoteException
{
return a+b;
}
public int sub(int a,int b)throws RemoteException
{
return a-b;
}
public int mul(int a,int b)throws RemoteException
{
return a*b;
}
public int div(int a,int b)throws RemoteException
{
return a/b;
}
public static void main(String args[])
{
try
{
computeInt c1=new comserver();
String I="CI";
Naming.rebind(I,c1);
System.out.println("Server bound and started");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

/* compuclient.java */
import java.rmi.*;
import java.io.*;
public class compuclient
{
public static void main(String args[]) throws IOException
{
int a,b;
try
{
String I="CI";
computeInt c=(computeInt)Naming.lookup(I);
System.out.println("Ready to continue");
DataInputStream d=new DataInputStream(System.in);

System.out.println("Enter Value for A : ");


a=Integer.parseInt(d.readLine());

System.out.println("Enter Value for B : ");


b=Integer.parseInt(d.readLine());

int i=c.add(a,b);
int j=c.sub(a,b);
int k=c.mul(a,b);
int l=c.div(a,b);

System.out.println("Sum of "+a+" and "+b+" is "+i);


System.out.println("Difference between "+a+" and "+b+" is "+j);
System.out.println("Product of "+a+" and "+b+" is "+k);
System.out.println("Division of "+a+" and "+b+" is "+l);
}
catch(Exception e)
{}
}
}

15. Calculator - Event Handling in Swing

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class calSwing extends JApplet implements ActionListener
{
double a,b,c;
JTextField t1;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;
String s,s1,s2,s3,s4;
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
t1=new JTextField(10);
t1.setBounds(80,200,260,40);
c.add(t1);
b1=new JButton("0"); b2=new JButton("1"); b3=new JButton("2");
b4=new JButton("3"); b5=new JButton("4"); b6=new JButton("5");
b7=new JButton("6"); b8=new JButton("7"); b9=new JButton("8");
b10=new JButton("9"); b11=new JButton("+"); b12=new JButton("-");
b13=new JButton("*"); b14=new JButton("/"); b15=new JButton("=");
b16=new JButton("CLR"); b17=new JButton(".");
b1.setBounds(90,260,40,30); c.add(b1);
b2.setBounds(140,260,40,30); c.add(b2);
b3.setBounds(190,260,40,30); c.add(b3);
b4.setBounds(240,260,40,30); c.add(b4);
b5.setBounds(290,260,40,30); c.add(b5);
b6.setBounds(90,300,40,30); c.add(b6);
b7.setBounds(140,300,40,30); c.add(b7);
b8.setBounds(190,300,40,30); c.add(b8);
b9.setBounds(240,300,40,30); c.add(b9);
b10.setBounds(290,300,40,30); c.add(b10);
b11.setBounds(90,340,40,30); c.add(b11);
b12.setBounds(140,340,40,30); c.add(b12);
b13.setBounds(190,340,40,30); c.add(b13);
b14.setBounds(240,340,40,30); c.add(b14);
b15.setBounds(290,340,40,30); c.add(b15);
b16.setBounds(90,380,70,20); c.add(b16);
b17.setBounds(140,380,70,20); c.add(b17);
b1.addActionListener(this); b2.addActionListener(this);
b3.addActionListener(this); b4.addActionListener(this);
b5.addActionListener(this); b6.addActionListener(this);
b7.addActionListener(this); b8.addActionListener(this);
b9.addActionListener(this); b10.addActionListener(this);
b11.addActionListener(this); b12.addActionListener(this);
b13.addActionListener(this); b14.addActionListener(this);
b15.addActionListener(this); b16.addActionListener(this);
b17.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
s=ae.getActionCommand();
if(s.equals("0") || s.equals("1") || s.equals("2")||s.equals("3") || s.equals("4")
||s.equals("5")||s.equals("6")||s.equals("7")||s.equals("8") ||s.equals("9")
||s.equals("."))
{
s1=t1.getText()+s;
t1.setText(s1);
}
if(s.equals("+"))
{
s2=t1.getText(); t1.setText(""); s3="+";
}
if(s.equals("-"))
{
s2=t1.getText(); t1.setText(""); s3="-";
}
if(s.equals("*"))
{
s2=t1.getText(); t1.setText(""); s3="*";
}
if(s.equals("/"))
{
s2=t1.getText(); t1.setText(""); s3="/";
}
if(s.equals("="))
{
s4=t1.getText(); a=Double.parseDouble(s2);
b=Double.parseDouble(s4);
if(s3.equals("+"))
c=a+b;
if(s3.equals("-"))
c=a-b;
if(s3.equals("*"))
c=a*b;
if(s3.equals("/"))
c=a/b;
t1.setText(String.valueOf(c));
}
if(s.equals("CLR"))
{
t1.setText("");
}
}
}

16. Personal information system using swing

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwgEmp extends JApplet implements ActionListener,ItemListener
{
JTextField jt1,jt2,jt3,jt4,jt5,jt6,jt7;
Choice dd,mm,yy;
JCheckBox c1,c2,c3,c4;
public void init()
{
Container c=getContentPane();
JLabel jl1=new JLabel("Employee processing using Swing");
JLabel jl2=new JLabel("Emp code");
JLabel jl3=new JLabel("Emp Name");
JLabel jl4=new JLabel("DOB");
JLabel jl5=new JLabel("Qualification");
JLabel jl6=new JLabel("Basic Pay");
JLabel jl7=new JLabel("Allowance");
JLabel jl8=new JLabel("Detection");
JLabel jl9=new JLabel("Gross Pay");
JLabel jl10=new JLabel("Net Pay");

c1=new JCheckBox("UG",true);
c2=new JCheckBox("PG",false);
c3=new JCheckBox("Mphil",false);
c4=new JCheckBox("PhD",false);

jt1=new JTextField();
jt2=new JTextField();
jt3=new JTextField();
jt4=new JTextField();
jt5=new JTextField();
jt6=new JTextField();
jt7=new JTextField();

dd=new Choice();
mm=new Choice();
yy=new Choice();

JButton jb=new JButton("Find");


JButton jb1=new JButton("Clear");

dd.addItem("1"); dd.addItem("2"); dd.addItem("3"); dd.addItem("4");


dd.addItem("5"); dd.addItem("6"); dd.addItem("7"); dd.addItem("8");
dd.addItem("9"); dd.addItem("10"); dd.addItem("11"); dd.addItem("12");
dd.addItem("13"); dd.addItem("14"); dd.addItem("15"); dd.addItem("16");
dd.addItem("17"); dd.addItem("18"); dd.addItem("19"); dd.addItem("20");
dd.addItem("21"); dd.addItem("22"); dd.addItem("23"); dd.addItem("24");
dd.addItem("25"); dd.addItem("26"); dd.addItem("27"); dd.addItem("28");
dd.addItem("29");dd.addItem("30");dd.addItem("31");

mm.addItem("Jan");mm.addItem("Fib");mm.addItem("Mar");
mm.addItem("Apr");mm.addItem("May");mm.addItem("Jun");
mm.addItem("Jul ");mm.addItem("Aug");mm.addItem("Sep");
mm.addItem("Oct");mm.addItem("Nov");mm.addItem("Dec");

yy.addItem("1980");yy.addItem("1981");yy.addItem("1982");
yy.addItem("1983");yy.addItem("1984");yy.addItem("1985");
yy.addItem("1986");yy.addItem("1987");yy.addItem("1988");
yy.addItem("1989");yy.addItem("1990");yy.addItem("1991");
yy.addItem("1992");yy.addItem("1993");yy.addItem("1994");

c.add(jl1); c.add(jl2); c.add(jl3); c.add(jl4); c.add(jl5);


c.add(jl6); c.add(jl7); c.add(jl8); c.add(jl9); c.add(jl10);
c.add(jt1); c.add(jt2);
c.add(jt3); c.add(jt4); c.add(jt5); c.add(jt6); c.add(jt7);
c.add(dd); c.add(mm); c.add(yy);
c.add(jb); c.add(jb1); c.add(c1); c.add(c2); c.add(c3);
c.add(c4);

jl1.setBounds(50,50,350,20); jl2.setBounds(50,100,140,20);
jl3.setBounds( 50,130,140,20); jl4.setBounds(50,160,140,20);
jt1.setBounds(130,100,140,20); jt2.setBounds(130,130,170,20);
jl5.setBounds(50,200,120,20);

c1.setBounds(130,200,50,20); c2.setBounds(180,200,50,20);
c3.setBounds(230,200,100,20); c4.setBounds(270,200,100,20);
jl6.setBounds(50,230,80,20); jt3.setBounds(130,230,100,20);
jl7.setBounds(50,270,100,20); jt4.setBounds(130,270,90,20); jl8.setBounds(50,310,90,20);
jt5.setBounds(130,310,100,20); jl9.setBounds(50,350,100,20);
jt6.setBounds(130,350,100,20);
jl10.setBounds(50,390,100,20); jt7.setBounds(130,390,100,20);
jb.setBounds(70,440,80,30); jb1.setBounds(160,440,100,30);
dd.setBounds(130,160,50,30); mm.setBounds(180,160,70,30);
yy.setBounds(250,160,80,30);
jt1.addActionListener(this); jt2.addActionListener(this);
jt3.addActionListener(this); jt4.addActionListener(this);
jt5.addActionListener(this); jt6.addActionListener(this);
jt7.addActionListener(this); jb.addActionListener(this);
jb1.addActionListener(this); c1.addItemListener(this);
c2.addItemListener(this); c3.addItemListener(this);
c4.addItemListener(this);
c.setLayout(null);
}
public void actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
if(s.equals("Find"))
{
float bp=Float.valueOf(jt3.getText()).floatValue();
float all=bp*0.4f;
float dt=bp*0.3f;
float gp=bp+all;
float np=bp-dt+all;
jt4.setText(String.valueOf(all));
jt5.setText(String.valueOf(dt));
jt6.setText(String.valueOf(gp));
jt7.setText(String.valueOf(np));
}
if(s.equals("Clear"))
{
jt1.setText(""); jt2.setText(""); jt3.setText("");
jt4.setText(""); jt5.setText(""); jt6.setText("");
jt7.setText("");
}
}
public void itemStateChanged(ItemEvent ds){}
}

/* <applet code="SwgEmp.class" width=100 height=300></applet> */

17. FTP Using Sockets


// FTP Client.java
import java.net.*;
import java.io.*;
import java.util.*;
class FTPClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket("127.0.0.1",5217);
transferfileClient t=new transferfileClient(soc);
t.displayMenu();
}
}
class transferfileClient
{
Socket ClientSoc;
DataInputStream din; DataOutputStream dout;
BufferedReader br;
transferfileClient(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception ex)
{ }
}
void SendFile() throws Exception
{
String filename;
System.out.print("Enter File Name :");
filename=br.readLine();
File f=new File(filename);
if(!f.exists())
{
System.out.println("File not Exists...");
dout.writeUTF("File not found");
return;
}
dout.writeUTF(filename);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Already Exists")==0)
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="Y")
{
dout.writeUTF("Y");
}
else
{
dout.writeUTF("N");
return;
}
}
System.out.println("Sending File ...");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
} while(ch!=-1);
fin.close();
System.out.println(din.readUTF());
}
void ReceiveFile() throws Exception
{
String fileName;
System.out.print("Enter File Name :");
fileName=br.readLine();
dout.writeUTF(fileName);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Not Found")==0)
{
System.out.println("File not found on Server ...");
return;
}
else if(msgFromServer.compareTo("READY")==0)
{
System.out.println("Receiving File ...");
File f=new File(fileName);
if(f.exists())
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="N")
{
dout.flush();
return;
}
}
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
System.out.println(din.readUTF());
}
}
public void displayMenu() throws Exception
{
while(true)
{
System.out.println("[ MENU ]");
System.out.println("1. Send File");
System.out.println("2. Receive File");
System.out.println("3. Exit");
System.out.print("\nEnter Choice :");
int choice;
choice=Integer.parseInt(br.readLine());
if(choice==1)
{
dout.writeUTF("SEND");
SendFile();
}
else if(choice==2)
{
dout.writeUTF("GET");
ReceiveFile();
}
else
{
dout.writeUTF("DISCONNECT");
System.exit(1);
}
}
}
}
// FTPServer.java
import java.net.*;
import java.io.*;
import java.util.*;
public class FTPServer
{
public static void main(String args[]) throws Exception
{
ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
{
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
}
}
}
class transferfile extends Thread
{
Socket ClientSoc;
DataInputStream din; DataOutputStream dout;
transferfile(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
start();
}
catch(Exception ex) { }
}
void SendFile() throws Exception
{
String filename=din.readUTF();
File f=new File(filename);
if(!f.exists())
{
dout.writeUTF("File Not Found");
return;
}
else
{
dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}while(ch!=-1);
fin.close();
dout.writeUTF("File Receive Successfully");
}
}
void ReceiveFile() throws Exception
{
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
{
return;
}
File f=new File(filename);
String option;
if(f.exists())
{
dout.writeUTF("File Already Exists");
option=din.readUTF();
}
else
{
dout.writeUTF("SendFile");
option="Y";
}
if(option.compareTo("Y")==0)
{
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
dout.writeUTF("File Send Successfully");
}
else
{
return;
}
}

public void run()


{
while(true)
{
try
{
System.out.println("Waiting for Command ...");
String Command=din.readUTF();
if(Command.compareTo("GET")==0)
{
System.out.println("\tGET Command Received ..");
SendFile();
continue;
}
else if(Command.compareTo("SEND")==0)
{
System.out.println("\t SEND Command Received...");
ReceiveFile();
continue;
}
else if(Command.compareTo("DISCONNECT")==0)
{
System.out.println("\tDisconnect Command Received ...");
System.exit(1);
}
}
catch(Exception ex) { }
}
}
}
18. Client Server Program

//Server1.java
import java.io.*;
import java.net.*;
import java.net.Socket;

public class Server1


{
public static void main(String a[])throws Exception
{
int p = 98;
Socket so;
System.out.println("I am Ready");
String q = "hai how r u? I am fine";
ServerSocket ss = new ServerSocket(p);
DataInputStream ds;
PrintStream ot;
while(true)
{
so = ss.accept();
ot = new PrintStream(so.getOutputStream());
ds = new DataInputStream(so.getInputStream());
ot.println(q);
q = ds.readLine();
System.out.println("From Client : "+q);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
q = br.readLine();
if(q.equals("end"))
{
so.close();
System.exit(0);
ot.println(q);
so.close();
}
}
}
}

// Client1.java
import java.io.*;
import java.net.*;
import java.net.Socket;

public class Client1


{
public static void main(String a[])throws Exception
{
String q;
Socket so;
PrintStream ps;
DataInputStream dip;
System.out.println("I am Ready");
while(true)
{
so = new Socket(InetAddress.getLocalHost(),98);
ps = new PrintStream(so.getOutputStream());
dip = new DataInputStream(so.getInputStream());
System.out.println("From Server : "+dip.readLine());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
q = br.readLine();
if(q.equals("end"))
{
ps.println("Over Talk");
so.close();
System.exit(0);
}
ps.println(q);
so.close(); } } }
19. Creation of jar files and using them

1. Command for creating a JAR file named guru.jar that contains all of the .java files in the current directory:
jar cf guru.jar *.java

2. Command for Tabulating the Contents of a JAR File to list the contents of guru.jar:

jar tf guru.jar

3. Command for Extracting Files from a JAR File guru.jar and places those files in the current directory:

jar xf guru.jar

4. Command for Updating an Existing JAR File to add the file statMain.java to guru.jar:

jar -uf guru.jar statMain.java


20. Reading and Writing in File

Writer code:
import java.io.*;
class WriteAFile
{
public static void main (String[] args)
{
try
{
FileWriter writer = new FileWriter("hello.txt");
writer.write ("hello this is your first file!");
writer.close ();

}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
}

Reader Code:
import java.io.*;
class ReadAFile
{
public static void main (String [] args)
{
try
{
File myFile = new File ("hello.txt");
FileReader fileReader = new FileReader (myFile );
BufferedReader reader = new BufferedReader (fileReader);
String line = null;
while ((line = reader.readLine()) != null)
{
System.out.println (line);
}
reader.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

21. Servlet Program Using JDBC Through Jdbc:Odbc Bridge


//LoginForm.html
<html>
<body>
<form method="post" action="http://localhost:8084/servlet/LoginPage">
<table border="0" cellspacing="0" cellpadding="15" width="400" align="center">
<tr>
<td>Login Name:</td>
<td><input type="text" name="LoginId" size="20"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="Password" size="20"></td>
</tr>
</table>
<p> <center>
<input type="submit" value="Login">
<input type="reset" value="Reset">
</center>
</form>
</body>
</html>

//LoginPage.java
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginPage extends HttpServlet
{
Connection con;
public void service(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
ServletOutputStream pw=res.getOutputStream();
try
{
//register the driver to be used in the application
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection
("jdbc:odbc:test","system","mkm");
Statement stmt=con.createStatement();
String login=req.getParameter("LoginId");
String word=req.getParameter("Password");
ResultSet rs=stmt.executeQuery("Select * from login where
uname='"+login+"' and pword='"+word+"'");
res.setContentType("text/html");
if(rs.next()==false)
{
pw.println("<b> Access Denied </b>");

}
else
{
pw.println("<b> Welcome,You have been authendicated </b>");
}
stmt.close();
con.close();
}
catch(Exception x)
{
System.out.println("Some error in try block");
System.out.println(x.getMessage());
}
}
}

//web.xml – Configuration
<servlet>
<servlet-name>LoginPage</servlet-name>
<servlet-class>LoginPage</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> LoginPage </servlet-name>
<url-pattern>/servlet/ LoginPage </url-pattern>
</servlet-mapping>
22. Servlet Program for PNR Status Enquiry

//pnr. html
<html>
<head><script>
function check(f)
{
pnr=f.pnr.value;
if(pnr.length<10)
alert("Invalid PIN Number");
}
</script></head>
<body>
<form method="post" action="http://localhost:8084/servlet/PnrStatus" target=f2>
<b><h3> Enter Your PIN No:
<input type="text" name="pnr" size="20" onblur="check(this.form)"><br>
<input type="submit" value="Get Status">
</form>
</body>
</html>
//PnrStatus.java
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PnrStatus extends HttpServlet
{
String pnr,trainNo,ticketNo,name;
int age;
double amount;
String statusCode;
Connection con;
public void service(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
PrintWriter pw=res.getWriter();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection
"jdbc:odbc:test","system","mkm");
Statement stmt=con.createStatement();
pnr=req.getParameter("pnr");
ResultSet rs=stmt.executeQuery("Select * from train where pnr='"+pnr+"'");
res.setContentType("text/html");
if(rs.next())
{
pnr = rs.getString(1);
trainNo = rs.getString(2);
ticketNo =rs.getString(3);
name = rs.getString(4);
age = rs.getInt(5);
amount = rs.getDouble(6);
statusCode = rs.getString(7);
pw.println("<HTML>");
pw.println("<body>");
pw.println("<center><h3> Train Reservation Status </h3>");
pw.println("<table align=center>");
pw.println("<tr><td> PNR Number: </td><td>"+ pnr +"</td></tr>");
pw.println("<tr><td> Train Number:</td><td>"+ trainNo +"</td></tr>");
pw.println("<tr><td> Ticket Number : </td><td>"+ ticketNo +"</td></tr>");
pw.println("<tr><td> Name: </td><td>"+ name +"</td></tr>");
pw.println("<tr><td> Age: </td><td>"+ age +"</td></tr>");
pw.println("<tr><td> Amount: </td><td>"+ amount +"</td></tr>");
if(statusCode.equals("C"))
{
pw.println("<tr><td> Status : </td><td> Confirmed </td></tr>");
}
if(statusCode.equals("R"))
{
pw.println("<tr><td> Status : </td><td> Reserved </td></tr>");
}
if(statusCode.equals("W"))
{
pw.println("<tr><td> Status : </td><td> Waiting </td></tr>");
}
pw.println("</body></HTML>");
}
else
{
pw.println("<b> PNR number does not exist");
}
stmt.close(); con.close();
}
catch(Exception x)
{ System.out.println(x.getMessage()); }
}
}
//web.xml – Configuration
<servlet>
<servlet-name> PnrStatus </servlet-name>
<servlet-class> PnrStatus </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> PnrStatus </servlet-name>
<url-pattern>/servlet/ PnrStatus </url-pattern>
</servlet-mapping>
23. Student Marks Calculation using Servlet

//student.html
<html>
<head>
<title>Pat-Bill</title>
</head>
<body bgcolor="pink">
<form action="http://localhost:8084/servlet/StudentInfo" method ="Get"><center>
/*Status of Student result */ <br><br>
<b> Enter Student Name </b>
<input type="text" name="sname" size="30"><br><br>
<b> Enter Student ID </b>
<input type="text" name="sid" size="30"><br><br>
<b> Enter the Mark 1 </b>
<input type="text" name="mark1" size="30"><br><br>
<b> Enter the Mark 2 </b>
<input type="text" name="mark2" size="30"><br><br>
<b> Enter the Mark 3 </b>
<input type="text" name="mark3" size="30"><br><br><br>
<input type="submit" name="view" value="VIEW">
</form>
</body>
</html>

//StudentInfo.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class StudentInfo extends HttpServlet
{
public void doGet(HttpServletRequest r, HttpServletResponse s)throws ServletException, IOException
{
String stid ="", stname ="", ma1 ="", ma2="",ma3="";
int m1,m2,m3, tot;
float avg;
String b1="";
s.setContentType("text/html");
PrintWriter t = s.getWriter();
stid = r.getParameter("sid");
stname = r.getParameter("sname");
ma1 = r.getParameter("mark1");
m1= Integer.parseInt(ma1);
ma2 = r.getParameter("mark2");
m2= Integer.parseInt(ma2);
ma3 = r.getParameter("mark3");
m3= Integer.parseInt(ma3);

tot = m1 + m2 + m3;
avg = tot/3;
t.println("<html><head>");
t.println("<title>STUDENT RESULT</title></head>");
t.println("<body bgcolor=pink>");
t.println("<h1><center>STATUS OF STUDENT </center></h1>");
t.println("<br><h2><center>STUDENT DETAILS</center></h1>");
t.println("<h4><center>STUDENT NAME : "+stname+"</center><br>");
t.println("<h4><center>STUDENT ID : "+stid+"</center><br>");
t.println("<h4><center>MARK 1 : "+m1+"</center><br>");
t.println("<h4><center>MARK 2 : "+m2+"</center><br>");
t.println("<h4><center>MARK 3 : "+m3+"</center><br>");
t.println("<h4><center>TOTAL MARK : "+tot+"</center><br>");
t.println("<h4><center>AVERAGE : "+avg+"</center><br>");
t.println("</body></html>");
}
}

//web.xml – Configuration
<servlet>
<servlet-name> StudentInfo </servlet-name>
<servlet-class> StudentInfo </servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> StudentInfo </servlet-name>
<url-pattern>/servlet/ StudentInfo </url-pattern>
</servlet-mapping>
24. Simple Applications Using Netbeans

Procedure:
Step 1: Creating a Project
Open netbeans IDE
1. Choose File > New Project
2. In the categories pane, select the java node. In the Projects pane, choose java Application. Click Next
3. Type Simple Calculator in the Project Name field.
4. Deselect the Create Main Class checkbox. If it is selected.
5. Click Finish.

Step 2: Create a JFrame Container


1. In the Projects window, right-click the Simple Calculator node and
2. Choose New -> Other
3. In the New File dialog box, Choose the Swing GUI Forms category and the JFrame Form file type. Click Next.
4. Enter SimpleCalculatorUI as the class name.
5. Enter my Simplecalculator as the package.
6. Click Finish.

Adding Components into the Front End


Applications front end with a JPanel. Then add three JLabels, three JTextFields and one JButtons.

Step 3: Renaming the Components


In this step we are going to rename the display text of the components that were just added to the JFrame.
1. Double-click jLabel1 and change the text property to Type First Name.
2. Double-click jLabel2 and change the text property to Type Second Name.
3. Double-click jLabel3 and change the text Result.
4. Delete the sample text from jTextField1, you can make the display text editable may have to resize the jTextField1 to its
original size. Repeat this step for jTextField2 and jTextField3.
5. Rename the display text of jButton1 to ADD.

Step 4: Coding
private void addButtonActionPerformed(java.awt.event.ActionEvent evt)
{
int num1, num2, result;
num1 = Integer.parseInt(jTextField1.getText());
num2 = Integer.parseInt(jTextField2.getText());
result = num1 + num2;
jTextField3.setText(String.valueOf(result));
}
private void subActionPerformed(java.awt.event.ActionEvent evt)
{
int num1, num2, result;
num1 = Integer.parseInt(jTextField1.getText());
num2 = Integer.parseInt(jTextField2.getText());
result = num1 - num2;
jTextField3.setText(String.valueOf(result));
}

private void mulActionPerformed(java.awt.event.ActionEvent evt)


{
int num1, num2, result;
num1 = Integer.parseInt(jTextField1.getText());
num2 = Integer.parseInt(jTextField2.getText());
result = num1 * num2;
jTextField3.setText(String.valueOf(result));
}

private void divActionPerformed(java.awt.event.ActionEvent evt)


{
int num1, num2, result;
num1 = Integer.parseInt(jTextField1.getText());
num2 = Integer.parseInt(jTextField2.getText());
result = num1 / num2;
jTextField3.setText(String.valueOf(result));
}
Step 5: Running the Program
To run the program in the IDE
1. Choose Run -> Run Main Project
2. Build main project
3. Run file press shift f6.

Das könnte Ihnen auch gefallen