Q1. Write a program that implements
the Concept of Encapsulation.
class Emp
{
private int empid;
private String name;
public Emp( int x,String y)
{
empid=x;
name=y;
}
public void show()
{
System.out.println("empid="+empid);
System.out.println("name="+name);
}
}
class Encap
{
public static void main(String arg[])
{
int eid=Integer.parseInt(arg[0]);
String ename=arg[1];
Emp e1=new Emp(eid,ename);
e1.show();
}
}
Output:-
Q2. WAP to demonstrate concept of
Polymorphism (Overloading).
class Overloaddemo
{
void test()
{
System.out.println("No
Parameters");
}
//Overload test for one integer parameter
void test(int a)
{
System.out.println("a:"+a);
}
//Overload test for two integer
parameter
void test(int a, int b)
{
System.out.println("a & b:"+a
+" "+b);
}
//overload test for double
parameter
double test(double a)
{
System.out.println("Double a:"+a);
return
a*a;
}
}
class Overload
{
public static void main(String args[])
{
Overloaddemo ob= new Overloaddemo();
double result;
//call all version of test()
ob.test();
ob.test(10);
ob.test(10,20);
result=ob.test(123.25);
System.out.println("Result
of ob.test(123.25):"+result);
}
}
Output:-
Q2(a) Write a Program to demonstrate
concept of Polymorphism (Overriden).
class Funcover
{
public void calc(int x,int y)
{
int z;
z=x*y;
System.out.println("multiplication="+z);
}
}
class Override extends Funcover
{
public void calc(int x,int y)
{
int z;
z=x/y;
System.out.print("division="+z);
}
}
class Overrideex
{
public static void main(String arg[])
{
Funcover f1=new Funcover();
f1.calc(7,6);
Override f2=new Override();
f2.calc(14,2);
}
}
Output:-
Q3 Write a Program the use boolean
data type and print the Prime number Series upto 50.
class Primetest
{
public
static void main(String args[])
{
int num,i;
boolean
prime=true;
for(num=3;num<=50;num++)
{
prime=true;
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
prime=false;
}}
if(prime)
System.out.println(""+num);
}}}
Output:-
Q4 Write a Program for Matrix Multiplication and Transpose using Input/Output Stream.
import java.io.*;
class Mat
{
public static void main(String
args[]) throws Exception
{
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
System.out.println("1. Transpose
of Matrix");
System.out.println("2. Matrix
multiplication");
System.out.println("Any other
choice for exit the prg");
System.out.print("\n\nEnter Your
choice");
int
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("Enter the
order of matrix");
int n,m;
n=Integer.parseInt(br.readLine());
m=Integer.parseInt(br.readLine());
int a[][]=new int[10][10];
System.out.print("enter the
"+m*n+" elements of matrix");
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("Origional Matrix
is::");
show(n,m,a);
System.out.println("After
Transpose Matrix become::");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[j][i]+"
");
}
System.out.println();
}
break;
case 2:
int i,j,s;
int m1,n1,p,q;
int a1[][]=new int[10][10];
int b[][]=new
int[10][10];
int c[][]=new
int[10][10];
System.out.print("Enter no. of Row
of First Matrix->");
m1=Integer.parseInt(br.readLine());
System.out.print("Enter
no. of Column of First Matrix->");
n1=Integer.parseInt(br.readLine());
System.out.print("Enter
no. of Row of Second Matrix->");
p=Integer.parseInt(br.readLine());
System.out.print("Enter
no. of Column of Second Matrix->");
q=Integer.parseInt(br.readLine());
if(n1!=p)
{
System.out.println("\n\nMatrix
Multyply Fail!!---Matrix should be Identical");
break;
}
System.out.println("Enter
First Matrix");
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
System.out.print("Enter
Element at " + (i+1) + " Row and " + (j+1) + " Column
->");
a1[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("Enter
Second Matrix");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
System.out.print("Enter
Element at " + (i+1) + " Row and " + (j+1) + " Column
->");
b[i][j]=Integer.parseInt(br.readLine());
}
}
for(i=0;i<m1;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(s=0;s<n1;s++)
c[i][j]+=a1[i][s]*b[s][j];
}
}
System.out.println("First Array:");
show(m1,n1,a1);
System.out.println("Second
Array:");
show(p,q,b);
System.out.println("Multiplied
Array:");
show(m1,q,c);
break;
default:
}
}
public static void show(int n,int
m,int a[][])
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(a[i][j]+"
");
}
System.out.println();
}
}
}
OUTPUT:-
Q5. Write a Program for Vector class when input
elements as argument and copy
the element into an array.
import java.util.*;
import java.io.*;
class Vectordemo
{
public static void main(String args[])throws Exception
{
Vector v = new Vector();
int n=Integer.parseInt(args[0]);
for(int
i=1;i<=n;i++)
v.addElement(args[i]);
v.insertElementAt(v.elementAt(n-1),0);
v.insertElementAt(v.elementAt(n-1),1);
v.insertElementAt(v.elementAt(n-1),2);
v.removeElementAt(v.size()-1);
v.removeElementAt(v.size()-1);
v.removeElementAt(v.size()-1);
System.out.println("After rearrangement :"+v);
System.out.println("Size of Vector :"+v.size());
Object array[]=new Object[v.size()];
v.copyInto(array);
System.out.println("Content of Array:");
for(int i =0;i<n;i++)
{
System.out.println(array[i]);
}
}
}
Output:-
Program-6
wap a program to check given string is
palindrom or not
import java.io.*;
class Palindromedemo
{
public static void
main(String []args)throws Exception
{
int
i,j;
InputStreamReader
isr=new InputStreamReader(System.in);
BufferedReader
br=new BufferedReader(isr);
System.out.println("Enter
the string to check");
String
str=br.readLine();
for(i=0,j=str.length();i<str.length();i++,j--)
{
if(str.charAt(i)!=str.charAt(j-1))
{
System.out.println("\n Entered String
is not palindrome");
break;
}
}
if(i==str.length())
System.out.println("\n Entered String is Palindrome");
}
}
output:
Q7 WAP in java to arrange the string
in alphabetical order.
class Stringordering
{
static
String name[]={"Ram","Pooja","Monu","Kiran"};
public
static void main(String arg[])
{
int
size=name.length;
String
temp=null;
for(int
i=0;i<size;i++)
{
for(int
j=i+1;j<size;j++)
{
if(name[i].compareTo(name[j])>0)
{
//swap the
string
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(int
i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}
Output:-
PROGRAM-8
Write a program for
string Buffer class which performs the all method of that class.
import java.io.*;
class Bufferstring
{
public static void main(String args[])throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.print("\n Enter the String :");
StringBuffer
str=new StringBuffer(br.readLine());
System.out.println("Enter the second string :");
StringBuffer st=new StringBuffer(br.readLine());
System.out.println("\n String Entered 1 : "+str);
System.out.println("\n String Entered 2 : "+st);
System.out.println("length of string1 : "+str.length());
System.out.println("Capacity of string1 : "+str.capacity());
System.out.println("Enter the String to Insert :");
String
str1=br.readLine();
System.out.println("Enter the String
to Insert :");
//String
str2=br.readLine();
System.out.println("\n After Insertion :"+str.insert(2,str1));
System.out.println("charAt(1)
"+str.charAt(1));
System.out.println("Append :
"+str.append(st));
}
}
OUTPUT:-
Q9.
Write a program to calculate simple interest using the wrapper class
class Wrap
{
public static void main(String
args[])
{
float
p=Float.parseFloat(args[0]);
System.out.println("Principle
amount is: "+p);
float r=
Float.parseFloat(args[1]);
System.out.println("rate
is: "+r);
int
t=Integer.parseInt(args[2]);
System.out.println("Enter
Time: "+t);
float SI=(p*r*t)/100;
System.out.println("Simple
Interest is: "+SI);
}
}
Output
Q.10 WAP to calculate Area of various
geometrical figures using the abstract class.
CODE:-
import java.io.*;
abstract class Area
{
final static float pi=3.14F;
abstract float compute(float x, float y);
}
class Rectangle
extends Area
{
float compute(float x,float y)
{
return(x*y);
}
}
class Triangle
extends Area
{
float compute(float x,float y)
{
return(x*y/2);
}
}
class Geomatric
{
public static void main(String
args[])throws Exception
{
float
r,s;
Rectangle
rect=new Rectangle();
Triangle
tri = new Triangle();
BufferedReader
br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("1. Area of
Rectangle ");
System.out.println("2. Area of
Triangle\n ");
System.out.print("Enter your
choice : ");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
{
System.out.println("Enter
the side of Rectangle");
r=Float.parseFloat(br.readLine());
s=Float.parseFloat(br.readLine());
System.out.println("Area
is = "+rect.compute(r,s));
break;
}
case
2:
{
System.out.println("Enter
the base and height of traingle");
r=Float.parseFloat(br.readLine());
s=Float.parseFloat(br.readLine());
System.out.println("Area
is = "+tri.compute(r,s));
break;
}
}
}
}
OUTPUT:
Q11.
Write a program where single class implements more than one interface and with
help of interface reference variable user call the method.
CODE:-
import java.io.*;
interface First
{
void addition(int a,int b);
}
interface Second
{
void multiplication(int a, int b );
}
class IDemo
implements First,Second
{
public void addition(int a,int b)
{
System.out.println("Addition of
two number is: "+(a+b) );
}
public void multiplication(int c,int d )
{
System.out.println("Addition of
two number is: "+(c*d) );
}
}
class ID
{
public static void main(String args[])
throws Exception
{
IDemo ii=new IDemo();
First f;
Second s;
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter
Numbers for Addition and Multiplication");
System.out.println("Enter First
number:");
int
a=Integer.parseInt(br.readLine());
System.out.println("Enter Second
number:");
int
b=Integer.parseInt(br.readLine());
f=ii;
f.addition(a,b);
s=ii;
s.multiplication(a,b);
}
}
OUTPUT:-
Program-12
Write a program that uses multiple
catch statement with try-catch mechanism.
import java.io.*;
class MultiDemo
{
public static void main(String args[])
{
int
a,b;
BufferedReader
br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("****Arithmetic
Operation****");
System.out.println("Enter
First number:" );
a=Integer.parseInt(br.readLine());
System.out.println("Enter
Second number:" );
b=Integer.parseInt(br.readLine());
System.out.println("Sum
of the number is:"+(a+b));
System.out.println("Subtraction
of the number is:"+(a-b));
System.out.println("Multiplication
of the number is:"+(a*b));
System.out.println("Division
of the number is:"+(a/b));
}catch(IOException
ioe)
{
System.out.println(ioe);
}
catch(ArithmeticException
ae)
{
System.out.println(ae);
}
catch(NumberFormatException
ne)
{
System.out.println(ne);
}
}
}
Output:
Q13
Write a Program where user will create a self-Exception using the
"throw" keyword.
import java.lang.Exception;
class SelfException extends Exception
{
SelfException(String message)
{
super(message);
}}
class TestSelfException
{
public static void main(String args[])
{
int x=5, y=1000;
try
{
float z=(float)x /(float) y;
if(z<0.01)
{
throw new SelfException("No. is not
enlarged");
}}
catch(SelfException e)
{
System.out.println("Caught my
exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("we like java");
}
} }
Output:-
Q14. Write a
program for multithread using the isAlive(), join(), and synchronized method of
thread class.
CODE:-
class CallMe
{
synchronized void call(String
msg)
{
System.out.print("["+msg);
try
{
Thread.sleep(100);
}
catch(InterruptedException
e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable
{
String msg;
CallMe target;
Thread t;
public Caller(CallMe
targ,String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run()
{
target.call(msg);
}
}
class SynchronizeTest
{
public static void main(String
args[])
{
CallMe target=new CallMe();
Caller ob1=new
Caller(target,"Hi");
Caller ob2=new
Caller(target,"I Am");
Caller ob3=new
Caller(target,"Synchronized");
System.out.println("Thread one is alive:"+ob1.t.isAlive());
System.out.println("Thread
Two is alive:"+ob2.t.isAlive());
System.out.println("Thread
Three is alive:"+ob3.t.isAlive());
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException ie)
{
System.out.println("Interrupted");
}
System.out.println("Thread one is alive:"+ob1.t.isAlive());
System.out.println("Thread Two is alive:"+ob2.t.isAlive());
System.out.println("Thread Three is alive:"+ob3.t.isAlive());
}
}
OUTPUT:-
Q15 WAP to create a
package using command & one package will import the another package.
import
package1.ClassA;
import
package2.*;
Class PackageTest2
{
Public static void main(String args[] )
{
ClassA objectA = new ClassA();
ClassB objectB= new ClassB();
objectA.display();
objectB.display();
}
}
Output:-
Class A
Class B
m = 10
Program-16
Write a
program for AWT to create menu and popup menu for Frame.
Code:
import java.awt.*;
import java.awt.event.*;
class MenuDemo extends Frame
{
MenuBar
mbr;
Menu
m1,m2,sm;
MenuItem
mi1,mi2,mi3,mi4,mi5,mi6,mi7,mi8,mi9,mi10,pmi6,pmi7,pmi8,pmi9,pmi10;
PopupMenu
p;
MenuShortcut
msc1;
MenuDemo()
{
setTitle("Menu");
mbr=new
MenuBar();
setMenuBar(mbr);
m1=new
Menu("File");
msc1=new
MenuShortcut('F');
mi1=new
MenuItem("New",msc1);
mi2=new
MenuItem("Open");
mi3=new
MenuItem("Save");
mi4=new
MenuItem("SaveAs");
mi5=new
MenuItem("Exit");
m1.add(mi1);
m1.add(mi2);
m1.addSeparator();
m1.add(mi3);
m1.add(mi4);
m1.add(mi5);
mbr.add(m1);
m2=new
Menu("Edit");
mi6=new
MenuItem("Cut");
mi7=new
MenuItem("Copy");
mi8=new
MenuItem("paste");
m2.add(mi6);
m2.add(mi7);
m2.add(mi8);
sm=new
Menu("Tools");
m2.add(sm);
mi9=new
MenuItem("Undo");
mi10=new
MenuItem("Redo");
sm.add(mi9);
sm.add(mi10);
mbr.add(m2);
p=new
PopupMenu("Floating Menu");
pmi6=new
MenuItem("Cut");
pmi7=new
MenuItem("Copy");
pmi8=new
MenuItem("paste");
pmi9=new
MenuItem("Undo");
pmi10=new
MenuItem("Redo");
p.add(pmi6);
p.add(pmi7);
p.add(pmi8);
p.add(pmi9);
p.add(pmi10);
add(p);
addMouseListener(new
MouseAdapter()
{
public
void mousePressed(MouseEvent me)
{
display(me);
}
public
void mouseReleased(MouseEvent me)
{
display(me);
}
public
void mouseClicked(MouseEvent me)
{
display(me);
}
});
setVisible(true);
validate();
setLocation(100,10);
setSize(200,200);
}
public
void display(MouseEvent me)
{
if(me.isPopupTrigger())
p.show(this,me.getX(),me.getY());
}
public
static void main(String agrs[])
{
MenuDemo
fr=new MenuDemo();
}
}
Output:
Z:\jaya>javac
menuDemo.java
Z:\jaya>java
menuDemo
Q17 WAP in java for Applet that handle the KeyBoard Event.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=prg17.class height=400 width=500>
</applet>*/
public class prg17 extends Applet implements KeyListener
{
String msg=" ";
int x=30,y=40;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void KeyPressed(KeyEvent ke)
{
showStatus("Key Pressed");
}
public void KeyRealsed(KeyEvent ke)
{
showStatus("Key UP");
}
public void KeyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}
Output:-
PROGRAM-18
Write a
program which support the TCP/IP protocol, where client gives the message and
server will be, receives the message.
Code:-
// clientdemo.java
import
java.net.*;
import
java.io.*;
class Clientdemo
{
public
static void main(String args[]) throws Exception
{
InetAddress
add=InetAddress.getByName("disha-8");
System.out.println("Cnnecting
clint is="+add);
Socket s=new
Socket(add,9000);
OutputStream
os=s.getOutputStream();
PrintWriter
pw=new PrintWriter(os);
InputStreamReader
isr=new InputStreamReader(System.in);
BufferedReader
br=new BufferedReader(isr);
String
str=br.readLine();
while(str.length()!=0)
{
pw.println(str);
str=br.readLine();
}
pw.close();
br.close();
isr.close();
s.close();
os.close();
}
}
//serverdemo.java
import
java.net.*;
import
java.io.*;
class Serverdemo
{
public
static void main(String args[]) throws Exception
{
InetAddress
seradd=InetAddress.getLocalHost();
System.out.println("server
address is="+seradd);
System.out.println("server
is up and waiting for the client");
ServerSocket
ss=new ServerSocket(9000);
Socket
s1=ss.accept();
System.out.println("Connection
is established===");
try{
InputStream
is=s1.getInputStream();
InputStreamReader
isr1=new InputStreamReader(is);
BufferedReader
br1=new BufferedReader(isr1);
String
str1=br1.readLine();
while(str1.length()!=0)
{
System.out.println(str1);
str1=br1.readLine();
}
br1.close();
isr1.close();
s1.close();
}
catch(Exception
e){}
}
}
Output:-
Z:\vinu\corejava\net>javac
serverdemo.java
Z:\vinu\corejava\net>java
serverdemo
server
address is=Disha-7/10.0.0.7
server is up
and waiting for the client
Connection
is established===
hai hello.
Z:\vinu\corejava\net>
Z:\vinu\corejava\net>javac
clientdemo.java
Z:\vinu\corejava\net>java
clientdemo
Cnnecting
clint is=Disha-7/10.0.0.7
hai hello.
Z:\vinu\corejava\net>
Q19. Write
a Program to illustrate the use of all the method of URL class.
CODE:-
//URL Class
// ParseURL.java
import java.net.*;
import java.io.*;
public class ParseURL
{
public static void
main(String[] args) throws Exception
{
URL aURL = new
URL("http://java.sun.com:80/docs/books/"
+
"tutorial/index.html#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("host = " + aURL.getHost());
System.out.println("filename
= " + aURL.getFile());
System.out.println("port = " + aURL.getPort());
System.out.println("ref = " + aURL.getRef());
}
}
OUTPUT:-
E:\Java
Prac>javac ParseURL.java
E:\Java Prac>java
ParseURL
protocol = http
host = java.sun.com
filename =
/docs/books/tutorial/index.html
port = 80
ref = DOWNLOADING
E:\Java Prac>
Q20. Write a program for JDBC to
insert the values into the existing table by using prepared statement.
CODE:-
import java.sql.*;
import java.io.*;
class InsertDemo
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
conn=DriverManager.getConnection("jdbc:odbc:stuDSN");
PreparedStatement
pst=conn.prepareStatement("Insert into student values(?,?,?)");
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter
ROll no");
String a=br.readLine();
System.out.println("Enter
Name");
String b=br.readLine();
System.out.println("Enter
Marks");
String c=br.readLine();
int x=Integer.parseInt(a);
int y=Integer.parseInt(c);
pst.setInt(1,x);
pst.setString(2,b);
pst.setInt(3,y);
pst.executeUpdate();
System.out.println("One row
inserted");
conn.close();
pst.close();
br.close();
}catch(ClassNotFoundException cnfe)
{
}catch(IOException cnfe)
{
} catch(SQLException e)
{
}
}
}
OUTPUT:-
E:\Java
Prac>javac InsertDemo.java
E:\Java Prac>java
InsertDemo
Enter ROll no
3
Enter Name
mohan
Enter Marks
78
One row inserted
E:\Java Prac>
Q21.Write a program for jdbc to
display the records from existing table .
CODE:-
import java.sql.*;
class Show
{
public static void main(String[] args)
throws SQLException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
conn=DriverManager.getConnection("jdbc:odbc:stuDSN");
Statement
st=conn.createStatement();
String str="Select * from
student ";
ResultSet
rs=st.executeQuery(str);
if(rs.next())
{
while(rs.next())
{
System.out.print(rs.getInt("rollno")+"\t");
System.out.print(rs.getString("Name")+"\t");
System.out.print(rs.getInt("marks")+"\n");
System.out.println("________________");
}
}
}catch(ClassNotFoundException cnfe)
{
}
}
}
OUTPUT:-
E:\Java Prac>javac Show.java
E:\Java Prac>java Show
2 disha 88
________________
3 mohan 78
________________
4 ram 66
________________
Q22. Write a Program to demonstrate Border
Layout.
CODE:-
import java.awt.*;
import
java.awt.event.*;
class BorderDemo
extends Frame
{
public BorderDemo()
{
Label lbl1 = new
Label("NORTH");
Label lbl2=new
Label("SOUTH");
Button btn1 = new
Button("EAST");
Button btn2=new
Button("WEST");
TextArea ta = new TextArea(5,5);
ta.append("CENTER");
setLayout(new BorderLayout());
add(lbl1,BorderLayout.NORTH);
add(lbl2,BorderLayout.SOUTH);
add(btn1,BorderLayout.EAST);
add(btn2,BorderLayout.WEST);
add(ta,BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{
public
void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
public static void main(String args[])
{
BorderDemo
bd = new BorderDemo();
bd.setTitle("BorderLayout");
bd.setSize(300,200);
bd.setVisible(true);
}
}
OUTPUT:-
E:\Java
Prac>javac BorderDemo.java
E:\Java Prac>java
BorderDemo
Q24. WAP for Applet who generate the MouseMotionListener
event.
class emp
{
private int
empid;
private
String name;
public emp(
int x,String y)
{
empid=x;
name=y;
}
public void
show()
{
System.out.println("empid="+empid);
System.out.println("name="+name);
}
}
class encap
{
public
static void main(String arg[])
{
int
eid=Integer.parseInt(arg[0]);
String
ename=arg[1];
emp e1=new
emp(eid,ename);
e1.show();
}
}
Output:-
Q25. Write a program for
display chexkBox,labels and TextFields on an AWT.
CODE:-
import java.awt.*;
import java.awt.event.*;
public class AwtFrame
{
public static void main(String[] args)
{
Frame frame=new Frame("Frame");
Button button = new Button("Button");
Label label=new Label("Label");
TextArea txtArea=new TextArea(30,100);
txtArea.append("This is Text Area");
TextField text=new
TextField("TextBox",20);
frame.setSize(300,200);
frame.setLocation(100,100);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
frame.add(label);
frame.add(text);
frame.add(button);
frame.add(txtArea);
frame.setVisible(true);
frame.addWindowListener(new
WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
OUTPUT:-
E:\Java Prac>javac AwtFrame.java
E:\Java Prac>java AwtFrame
Q
27 WAP for creating a file and to store data into that file (using
FileWriterIOStream).
import java.io.*;
public classFileWriter{
public
static void main(String[] args) throws IOException{
BufferedReader
in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please
enter the file name to create : ");
String
file_name = in.readLine();
File
file = new File(file_name);
boolean
exist = file.createNewFile();
if
(!exist)
{
System.out.println("File
already exists.");
System.exit(0);
}
else
{
FileWriter
fstream = new FileWriter(file_name);
BufferedWriter
out = new BufferedWriter(fstream);
out.write(in.readLine());
out.close();
System.out.println("File
created successfully.");
}}}
Output:-
C:\Suyash>javac CreateFile.java
C:\Suyash>java CreateFile
Please enter the file name to create :
nande.txt
This is my name
File created successfully.
Q28 WAP to display your file in DOS console
use the IO stream.
import java.io.*;
class display
{
public static void
main(String[] args)
{
FileInputStream
file1=null;
int b;
try
{
file1
=new FileInputStream(args[0]);
while((b=file1.read())!=-1)
{
System.out.print((char)b);
}
file1.close(); }
catch
(IOException ioe)
{
System.out.println(ioe);
}}}
Output:-
Q29 WAP to create an Applet using HTML file, where
Parameter passes for Font size & font type and Applet message will change
to corresponding Parameters.
import java.awt.*;
import java.applet.*;
/*<applet code=prg29.class height=300 width=300>
<param name=t1 value="Comic Sans MS">
<param name=t2 value=38>
</applet>*/
public class prg29 extends Applet
{
int n;
String style;
public void init()
{
style=getParameter("t1");
String s=getParameter("t2");
n=Integer.parseInt(s);
Font f=new Font(style,Font.BOLD,n);
setFont(f);
setBackground(Color.red);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawString("disha college",20,100);
}
}
Output:-
---------------------------------------------x----------------------------------------x----------------------------------
Draw lines,rect,oval:
Save as choice.java
import javax.swing.*;
import java.awt.Graphics;
/*
<html>
<body>
<applet code="choice.class"
width=500
height=500>
</applet>
</body>
</html>
*/
public class choice extends JApplet
{
int i,ch;
public void init()
{
String input;
input=JOptionPane.showInputDialog
("enter your choice(
1-lines,2-rectangles,3-ovals)");
ch=Integer.parseInt(input);
}
public void
paint(Graphics g)
{
switch(ch)
{
case 1:{
for(i=1;i<=10;i++)
{
g.drawLine(10,10,250,10*i);
}
break;
}
case 2:{
for(i=1;i<=10;i++)
{
g.drawRect(10*i,10*i,50+10*i,50+10*i);
}
break;
}
case 3:{
for(i=1;i<=10;i++)
{
g.drawOval(10*i,10*i,50+10*i,50+10*i);
}
break;
}
}
}
}
--------------------------------------------------------------------------
JTable with data
enter:
Save as
JTableDemo.java
import java.awt.*;
import javax.swing.*;
/* <applet code = "JTableDemo"
width = 400
height=200> </applet> */
public class JTableDemo extends JApplet {
public void init() {
//Get Content Pane
Container contentPane = getContentPane();
//set layout manger
contentPane.setLayout(new BorderLayout());
//Initialize column headings
final String[] colHeads = { "Name",
"Phone", "Fax" };
//Initialize data
final Object[][] data = {
{ "Gail", "4567", "8675" },
{"Keen", "7566", "5555" },
{"Viviane", "5674", "5887"},
{"Anne", "1237", "3333" },
{ "John", "5656", "3144" },
{ "Ellen", "1134", "5335"},
{ "Gail", "4567", "8675" },
{"Keen", "7566", "5555" },
{"Viviane", "5674", "5887"},
{"Anne", "1237", "3333" },
{ "John", "5656", "3144" },
{ "Ellen", "1134", "5335"}
};
//Create the table
JTable table = new JTable(data, colHeads);
//Add table to a scroll pane
int v = ScrollPaneConstants
.VERTICAL_SCROLLBAR_AS_NEEDED ;
int h = ScrollPaneConstants.
HORIZONTAL_SCROLLBAR_AS_NEEDED ;
JScrollPane jsp = new JScrollPane(table, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp, BorderLayout.CENTER);
}
}
-----------------------------------------------------------------
Abstract class named
triagle,hexagon:
Save as
AbstractDemo.java
abstract class shape
{
void
numberofsides()
{
System.out.println("This is for abstract class");
}
}
class Trapezoid extends shape
{
void
numberofsides()
{
System.out.println("It is having 4 sides");
}
}
class Triangle extends shape
{
void numberofsides()
{
System.out.println("it is having 3 sides");
}
}
class Hexagonal extends shape
{
void numberofsides()
{
System.out.println("it is having 6 sides");
}
}
class AbstractDemo
{
public static void main(String args[])
{
Trapezoid tz=new
Trapezoid();
Triangle t=new Triangle();
Hexagonal h=new Hexagonal();
tz.numberofsides();
t.numberofsides();
h.numberofsides();
}
}
----------------------------------------------------------------------
Fibonacci
class Rfib
{
int fibo(int n)
{
int a=0,b=1,c=2,i;
if(n==1)
return(a);
else if(n==2)
return(b);
else
{
for(i=3;i<=n;i++)
{
c=a+b;
a=b;
b=c;
}
return(c);
}
}
}
class fib
{
public static void main(String args[])
{
int n,i,a=0,b=1,c;
Rfib f=new Rfib();
n=Integer.parseInt(args[0]);
for(i=1;i<=n;i++)
{
System.out.println(f.fibo(i));
}
for(i=1;i<n;i++)
{
if(i==1)
System.out.println(a);
else if(i==2)
System.out.println(b);
else
{
c=a+b;
a=b;
b=c;
System.out.println(c);
}
}
}
}
-------------------------------------------
Infix into postfix:
Save as InToPost.java
import java.io.*;
class stack
{
char stack1[]=new char[20];
int top;
void push(char ch)
{
top++;
stack1[top]=ch;
}
char pop()
{
char ch;
ch=stack1[top];
top--;
return ch;
}
int pre(char ch)
{
switch(ch)
{
case '-':return 1;
case '+':return 1;
case '*':return 2;
case '/':return 2;
}
return 0;
}
boolean operator(char ch)
{
if(ch=='/'||ch=='*'||ch=='+'||ch=='-')
return true;
else
return false;
}
boolean isAlpha(char ch)
{
if(ch>='a'&&ch<='z'||ch>='0'&&ch=='9')
return true;
else
return false;
}
void postfix(String str)
{
char output[]=new char[str.length()];
char ch;
int p=0,i;
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
if(ch=='(')
{
push(ch);
}
else if(isAlpha(ch))
{
output[p++]=ch;
}
else if(operator(ch))
{
if(stack1[top]==0||(pre(ch)>pre
(stack1[top]))||stack1[top]=='(')
{
push(ch);
}
}
else if(pre(ch)<=pre(stack1[top]))
{
output[p++]=pop();
push(ch);
}
else if(ch=='(')
{
while((ch=pop())!='(')
{
output[p++]=ch;
}
}
}
while(top!=0)
{
output[p++]=pop();
}
for(int j=0;j<str.length();j++)
{
System.out.print(output[j]);
}
}
}
class InToPost
{
public static void main(String[] args)throws Exception
{
String s;
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
stack b=new stack();
System.out.println("Enter input string");
s=br.readLine();
System.out.println("Input String:"+s);
System.out.println("Output String:");
b.postfix(s);
}
}
------------------------------------------------------------------------------------------
good morning and
welcome
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{ }
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{ }
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{ }
}
}
class ThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}
--------------------------------------------------------
count words
class Count
{
public static void main(String args[])
{ int i,c=0;
for(i=0;i<args.length;i++)
{
System.out.println(args[i]);
c++;
}
System.out.println("number of words="+c);
}
}
-----------------------------------------------------------
file exists r not
import java.io.*;
class FileDemo
{
public static void main(String args[])
{
File f1=new
File("/java/copyright","Goutham.java");
System.out.println("file name"+f1.getName());
System.out.println("path"+f1.getPath());
System.out.println("parent"+f1.getParent());
System.out.println(f1.exists());
System.out.println(f1.canRead());
System.out.println(f1.canWrite());
System.out.println(f1.isDirectory());
System.out.println(f1.isFile());
System.out.println(f1.lastModified());
System.out.println(f1.length());
System.out.println(f1.delete());
}
}
--------------------------------------
Calculator:
Save as Cal.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
public class Cal extends Applet
implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}
--------------------------------------------------------
sum of integer
import java.io.*;
import java.util.*;
class Sum
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int a[]=new int[10];
int i,sum=0;
System.out.println("enter integer:\n");
for(i=0;i<10;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
for(i=0;i<10;i++)
{
System.out.println("integers are:"+a[i]);
}
for(i=0;i<10;i++)
{
sum+=a[i];
}
System.out.println("sum is:\n"+sum);
}
}
import java.io.*;
import java.util.*;
class Sum
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int a[]=new int[10];
int i,sum=0;
System.out.println("enter integer:\n");
for(i=0;i<10;i++)
{
a[i]=Integer.parseInt(br.readLine());
}
for(i=0;i<10;i++)
{
System.out.println("integers are:"+a[i]);
}
for(i=0;i<10;i++)
{
sum+=a[i];
}
System.out.println("sum is:\n"+sum);
}
}
----------------------------------------------------------
applet message
import java.awt.*;
import java.applet.*;
/*<applet code="Hellojava" width=300
height=50>
</applet>*/
public class Hellojava extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to Applet",20,20);
}
}
-----------------------------------
Divide:
Save as Div.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Div"width=230 height=250>
</applet>*/
public class Div extends Applet implements ActionListener
{
String msg;
TextField num1,num2,res;Label l1,l2,l3;
Button div;
public void init()
{
l1=new Label("Number 1");
l2=new Label("Number 2");
l3=new Label("result");
num1=new TextField(10);
num2=new TextField(10);
res=new TextField(10);
div=new Button("DIV");
div.addActionListener(this);
add(l1);
add(num1);
add(l2);
add(num2);
add(l3);
add(res);
add(div);
}
public void actionPerformed(ActionEvent ae)
{
String arg=ae.getActionCommand();
if(arg.equals("DIV"))
{
String s1=num1.getText();
String s2=num2.getText();
int num1=Integer.parseInt(s1);
int num2=Integer.parseInt(s2);
if(num2==0)
{
try
{
System.out.println(" ");
}
catch(Exception e)
{
System.out.println("ArithematicException"+e);
}
msg="Arithemetic";
repaint();
}
else if((num1<0)||(num2<0))
{
try
{
System.out.println("");
}
catch(Exception e)
{
System.out.println("NumberFormat"+e);
}
msg="NumberFormat";
repaint();
}
else
{
int num3=num1/num2;
res.setText(String.valueOf(num3));
}
}
}
public void paint(Graphics g)
{
g.drawString(msg,30,70);
}
}
---------------------------------------------------
server.java:
import java.net.*;
import java.io.*;
public class server
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket s=ss.accept();
BufferedReader br=new BufferedReader
(new InputStreamReader(s.getInputStream()));
double rad,area;
String result;
rad=Double.parseDouble(br.readLine());
System.out.println("From Client : "+rad);
area=Math.PI*rad*rad;
result="Area is "+area;
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(result);
br.close();
ps.close();
s.close();
ss.close();
}
}
Client.java
import java.net.*;
import java.io.*;
public class client
{
public static void main(String args[]) throws Exception
{
Socket s=new Socket("localhost",2000);
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
String rad;
System.out.println("Enter radius of the circle ");
rad=br.readLine();
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(rad);
BufferedReader fs=new
BufferedReader(new InputStreamReader
(s.getInputStream()));
String result=fs.readLine();
System.out.println("From Server : "+result);
br.close();
fs.close();
ps.close();
s.close();
}
}
-------------------------------------------------------------
palindraom
class Palindrom
{
public static void main(String args[])
{
String s=args[0];
int len,i=0,n,c=0,p;
len=s.length();
n=len/2;
p=len-n+1;
while(i<len/2)
{
if(s.charAt [i]==s.charAt(p))
c++;
i++;
p--;
}
if(c==len/2)
{
System.out.println("palindrom");
}
else
{
System.out.println("not palindrom");
}
}
}
---------------------------------------------------------------
sorting
class Sort
{
static String s[]={"goutham","ravi","hari"};
public static void main(String args[])
{
int i,j;
int n=s.length;
String t=null;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[j].compareTo(s[i])<0)
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
}
System.out.println(s[i]);
}
}
}
----------------------------------------------------------------------
Signal:
Save as Signal.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Signal" width=300
height=100>
</applet>*/
public class Signal extends
Applet implements
ItemListener
{
Checkbox red,yellow,green;
Light light;
public void init()
{ Panel p1=new
Panel();
p1.setSize(200,200);
p1.setLayout(new FlowLayout());
p1.add(light=new Light());
light.setSize(40,90);
Panel p2=new Panel();
p2.setLayout(new FlowLayout());
CheckboxGroup g=new
CheckboxGroup();
p2.add(red=new
Checkbox("red",g,false));
p2.add(yellow=new
Checkbox("yellow",g,false));
p2.add(green=new
Checkbox("green",g,false));
add("center",p1);
add("south",p2);
red.addItemListener(this);
yellow.addItemListener(this);
green.addItemListener(this);
}
public void
itemStateChanged(ItemEvent ie)
{
if(red.getState())
{
light.red(); }
if(yellow.getState())
{
light.yellow(); }
if(green.getState())
{
light.green();
}
}
class Light extends Canvas
{
private boolean red;
private boolean yellow;
private boolean green;
public Light()
{
red=false;
yellow=false;
green=false;
}
public void red()
{
red=true;
yellow=false;
green=false;
repaint();
}
public void yellow()
{
red=false;
yellow=true;
green=false;
repaint();
}
public void green()
{
red=false;
yellow=false;
green=true;
repaint();
}
public void paint(Graphics g)
{
if(red)
{
g.setColor(Color.red);
g.fillOval(10,10,20,20);
g.setColor(Color.black);
g.drawOval(10,35,20,20);
g.drawOval(10,60,20,20);
g.drawRect(5,5,30,86);
}
else if(yellow)
{
g.setColor(Color.yellow);
g.fillOval(10,35,20,20);
g.setColor(Color.black);
g.drawRect(5,5,30,80);
g.drawOval(10,10,20,20);
g.drawOval(10,60,20,20);
}
else if(green)
{
g.setColor(Color.green);
g.fillOval(10,60,20,20);
g.setColor(Color.black);
g.drawRect(5,5,30,80);
g.drawOval(10,10,20,20);
g.drawOval(10,35,20,20);
}
else{
g.setColor(Color.black);
g.drawRect(5,5,30,80);
g.drawOval(10,10,20,20);
g.drawOval(10,35,20,20);
g.drawOval(10,60,20,20);
}
}
}
}
--------------------------------------------------
fact using applet
/* <applet code="Fact.java" width=300
height=100>
</applet> */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Fact extends Applet
implements ActionListener {
int n,f=1;
Button compute;
TextField t1;
String s1,s2;
public void init() {
t1=new TextField();
compute = new Button("compute");
add(t1);
add(compute);
t1.setText("0");
compute.addActionListener(this);
}
public void
actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
if(s.equals("compute"))
{ s1=t1.getText();
n=Integer.parseInt(s1);
while(n!=0) {
f*=n;
n--;
}
s2=String.valueOf(f);
}
repaint();
}
public void paint(Graphics g)
{
g.drawString("factorial:"+s2,6,50);
}
}
-----------------------------------------------
matrix mul
import java.io.*;
class Mmul
{
public static void main
(String args[])throws Exception
{
BufferedReader Br=new BufferedReader(new
InputStreamReader(System.in));
int i=0,j=0,k=0;
int a[][]=new int[10][10];
int b[][]=new int[10][10];
int c[][]=new int[10][10];
System.out.println("enter A matrix");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
a[i][j]=Integer.parseInt(Br.readLine());
System.out.println("enter B matrix");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
b[i][j]=Integer.parseInt(Br.readLine());
System.out.println("c matrix");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
c[i][j]=0;
for(k=0;k<2;k++)
c[i][j]+=a[i][k]*b[k][j];
System.out.println(" "+c[i][j]);
}
System.out.println(" ");
}
}
----------------------------------
Evaluate postfix:
Save as EvalPostFix
import java.io.*;
import java.util.*;
class StackDemo
{
static int index,pos;
int T;
float stk[];
StackDemo()
{
stk=new float[10];
T=-1;
index=0;
pos=0;
}
void push(float s)
{
if(T>=19)
{
System.out.println("Stack
overflow");
System.exit(0);
}else{
T=T+1;
stk[T]=s;
}
}
float pop()
{
float num;
if(T==-1)
{
System.out.println("Stack is empty");
return(0);
}
else
{
num=stk[T];
T--;
}
return(num);
}
float ExpEval(char sfix[],float data[])
{
int j=0;
float op1,op2,fs;
char ch;
while(sfix[j]!='\0')
{
ch=sfix[j];
if(sfix[j]>='a'||sfix[j]>=
'A'&&sfix[j]<='z'||sfix[j]<='Z')
{
push(data[j]);
}
else
{
op2=pop();
op1=pop();
switch(ch)
{
case
'+':push(op1+op2);
break;
case '-':push(op1-op2);
break;
case '*':push(op1*op2);
break;
case '/':push(op1/op2);
break;
case '%':push(op1%op2);
break;
}
}
j++;
}
fs=pop();
return(fs);
}
}
class EvalPostFix
{
public static void
main(String args[])
{
String str;
char postfix[]=new char[25];
float number[]=new float[25];
int j=0;
try{
BufferedReader br=new
BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a postfix expression:");
str=br.readLine();
str.getChars(0,str.length(),postfix,0);
while(postfix[j]!='\0')
{
if(postfix[j]>='a'||postfix[j]
>='A'&&postfix[j]<='z'||postfix[j]<='Z')
{
System.out.println("enter a number
for%c:"+postfix[j]);
number[j]=Integer.parseInt(br.readLine());
}
j++;
}
}
catch(Exception e)
{
System.out.println("Exception
\n Read:"+e);
}
StackDemo s1=new StackDemo();
System.out.println("The result
is
"+s1.ExpEval(postfix,number));
}
}
--------------------------------------------------------------------------------
quadratic
class Quad
{
public static void main(String args[])
{
int a,b,c,d;
double x1,x2,re,im;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);
if(a==0)
{
System.out.println("linear equation");
x1=-c/b;
System.out.println("x1="+x1);
}
else
{
d=b*b-(4*a*c);
if(d==0)
{
System.out.println("real and equal");
x1=-(b/(2*a));
System.out.println("x1=x2="+x1);
}
else
if(d>0)
{
System.out.println("real and unequal");
x1=(-b+Math.sqrt(d))/(2*a);
x2=(-b-Math.sqrt(d))/(2*a);
}
else
{
System.out.println("root are not real solutions");
re=(-b)/(2*a);
im=Math.sqrt(-d)/(2*a);
System.out.println("real="+re);
System.out.println("imaginary="+im);
}
}
}
}
---------------------------------------------------
prime range
class Primeran
{
public static void main(String args[])
{
int num,i=1,j=1,c=0;
num=Integer.parseInt(args[0]);
while(i<=num)
{
j=1;
c=0;
while(j<=i)
{
if(i%j==0)
c++;
j++;
}
if(c==2)
System.out.println(i+"prime");
i++;
}
}
}
----------------------------------------------------------
mouse event
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="MouseEventDemo
" width=300 height=100>
</applet>
*/
public class MouseEventDemo
extends Applet
implements MouseListener,
MouseMotionListener
{
String msg=" ";
int mouseX=0,mouseY=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="mouse clicked by me";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="mouse entered by me";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="mouse exited by me";
repaint();
}
public void mousePressed(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="Down";
showStatus(msg+"at"+mouseX+","+mouseY);
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="Up";
showStatus(msg+"at"+mouseX+" "+mouseY);
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="*";
showStatus("Dragging the mouse
at"+mouseX+","+mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
msg="mouse moved";
showStatus("mouse moved
at"+me.getX()+","+me.getY());
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,mouseX,mouseY);
}
}
--------------------------------------------------------------------------------
consumer
class Q
{
boolean valueSet=false;
int n;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Exception is:"+e);
}
System.out.println("got:"+n);
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println
("\n Exception in put:"+e);
}
this.n=n;
valueSet=true;
System.out.println("\nput:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
q.put(i++);
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
q.get();
}
}
class
ProdConsDemo
{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("\n press ctrl+c to stop");
}
}
------------------------------------------------------------
num of char and lines
import java.io.*;
class FileDemo2
{
public static void main(String args[])throws Exception
{
int i,l=0,w=0;
String s="it is java program";
char buffer[]=new char[s.length()];
s.getChars(0,s.length(),buffer,0);
System.out.println("no of
characters="+s.length());
for(i=0;i<s.length();i++)
{ char
c=s.charAt(i);
if(c=='\t'||c=='\b'||c==' '||c=='\n')
{ w++;
}
}
System.out.println("no of words:"+w);
FileWriter f1=new FileWriter("c:/goutham.txt");
f1.write(buffer);
f1.close();
FileReader fr=new FileReader("c:/goutham.txt");
BufferedReader br=new BufferedReader(fr);
String t;
while((t=br.readLine())!=null)
{
l++;
}
System.out.println("no of lines"+l);
fr.close();
}
}
--------------------------------------------------------------------------
line num b4re
import java.io.*;
class FileDemo1
{
public static void main(String args[])throws Exception
{
int c=0;
String s="i+ \n is \n java \n program \n";
char buffer[]=new char[s.length()];
s.getChars(0,s.length(),buffer,0);
FileWriter f1=new FileWriter("c:/index.txt");
f1.write(buffer);
f1.close();
FileReader fr=new FileReader("c:/index.txt");
BufferedReader br=new BufferedReader(fr);
String t;
while((t=br.readLine())!=null)
{
c++;
System.out.println(c+t);
}
fr.close();
}
}
------------------------------------------------------------------------
stack adt
interface IntStack {
void push(int item);
int pop();
}
class FixedStack implements IntStack {
private int st[ ];
private int top;
FixedStack(int s) {
st=new int[s];
top=-1;
}
public void push(int item) {
if(top==st.length-1)
System.out.println("stack is full");
else
st[++top]=item;
}
public int pop() {
if(st.length<0) {
System.out.println("stack is empty");
return 0;
}
else
return st[top--];
}
}
class IFTest
{
public static void main(String args[ ])
{
FixedStack s1=new FixedStack(5);
FixedStack s2=new FixedStack(8);
int i;
for(i=0;i<5;i++)
s1.push(i);
for(i=0;i<8;i++)
s2.push(i);
System.out.println("stack in s1");
for(i=0;i<5;i++)
System.out.println(s1.pop());
System.out.println("stack in s2");
for(i=0;i<8;i++)
System.out.println(s2.pop());
}
}
Great post! I recently started a new blog aimed at helping people improve their learning activity in mobile technology, and will try utilize some of your tips. I hadn’t thought about a couple approaches that you suggested here.
ReplyDeleteipod service center in Chennai | Authorized ipod service center in Chennai | ipad service center in chennai | ipod service center in chennai | ipad service center in chennai | apple service center in chennai | iphone unlocking service | Laptop service center in chennai
very informative blog this will help a lot to website design and very useful for developers
ReplyDeleteThank you man for this useful content
very informative blog this will help a lot to website design and very useful for developers
ReplyDeleteThank you man for this useful content
SS-WEBSOLUTION is a Professional Web Design and Digital Marketing Agency in Pakistan. We have been working in the field of digital marketing since 2014. Now we have expanded our services to web designing, online reputation management, digital marketing , social media , SEO , SMO and much more. Our Dedicated Team is ready to serve you better than anyone else so please feel free to contact us at any time.
ReplyDeleteThis is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging.Visit us at mobile app development services in Lahore
ReplyDeleteThis is an Incredible blog.Nice information.For Best Real estate management system Visit Us.
ReplyDelete
ReplyDeleteI read your blog its is very informative find you can also find best finex digital services
This is some awesome blog.Thanks for sharing.For Best byfonts Visit Us.
ReplyDeleteIt is truly a well-researched content and excellent wording. I got so engaged in this material that I couldn’t wait reading. I am impressed with your work and skill.For Best instagram fonts Visit Us.
ReplyDeleteGood Post !
ReplyDeleteDHA (Defense Housing Authority) Lahore, is one of the most renowned and absolute previously gated housing societies in Lahore. At first, created to take special care of the groups of officials of the Military, it offers all necessities of day-to-day existence in closeness. In any case, because of the rising interest, DHA Lahore paved the way for regular folks and the overall population. DHA Lahore has different phases with Phases 1 and 2 being the most seasoned.