Java Programming Laboratory (10mca37)
Java Programming Laboratory (10mca37)
SOURCE CODE:
class cnst
{
int i,j;
cnst()
{
i=10;
j=20;
}
cnst(int i,int j)
{
this.i=i;
this.j=j;
}
cnst(int x)
{
i=x;
j=20;
}
void sum()
{
int sum=i+j;
System.out.println("Numbers are "+i+" and "+j+" \nSum is ="+sum);
}
void sum(int x )
{
int sum=x+i;
System.out.println("Numbers are "+i+" and "+x+"\nSum is ="+sum);
}
class moload
{
public static void main(String args[])
{
OUTPUT
SOURCE CODE:-
class Outer
{
int x=10;
public int y=20;
protected int z=30;
private int p=40;
void access()
{
Inner ob=new Inner();
ob.display();
}
class Inner
{
void display()
{
System.out.println("Default data X="+x);
System.out.println("Default data Y="+y);
System.out.println("Default data Z="+z);
System.out.println("Default data P="+p);
}
}
}
class Access
{
public static void main(String args[])
{
System.out.println("Demonstration of Inner class and Access protections\n");
Outer ob=new Outer();
ob.access();
}
}
OUTPUT
SOURCE CODE:
class Super
{
int i;
void setI(int i)
{
this.i=i;
}
int getI()
{
return i;
}
}
OUTPUT
SOURCE CODE:
class Nesting
{
public static void main(String args[])
{
try
{
int a = args.length;
int b=42/a;
System.out.println("a="+a);
try{
if(a==1) a=a/(a-a);
if(a==2)
{
int c[]={1};
c[32]=89;
}
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Array index out of bound\n");
}
catch(ArithmeticException ex)
{
System.out.println(" Divide By Zero\n");
}
}
catch(ArithmeticException ex)
{
System.out.println(" Divide By Zero\n");
}
finally
{
System.out.println("Finally Block is Executed\n");
}
}
}
OUTPUT
SOURCE CODE:
import java.io.*;
class LessBalanceException extends Exception
{
LessBalanceException(double amt)
{
System.out.println("Withdrawing"+amt+"is invalid");
}
}
class Account
{
static int count=124;
int an;
double bal;
String name;
Account(double bal,String n)
{
System.out.println("\nNew Account opened...!!!\n");
this.bal=bal;
count++;
an=count;
name=n;
}
void deposit(double amt)
{
System.out.println("Availabe Balance :"+bal);
bal=bal+amt;
System.out.println("Rs." +amt +"/- Credited");
System.out.println("Balance :"+bal);
}
void withdraw(double amt) throws LessBalanceException
{
System.out.println("\nAvailable Balance :"+bal);
bal=bal-amt;
if(bal<500)
{
bal=bal+amt;
if(f)
{
System.out.println("Enter the Amount for Deposit :");
amt=Double.parseDouble(br.readLine());
ob[k].deposit(amt);
}
else
System.out.println("Invalid Account Number....!!!");
break;
case 3:
System.out.println("Enter Account number\n");
an=Integer.parseInt(br.readLine());
for(k=0;k<2;k++)
if(an==ob[k].an)
{
f=true; break;
}
if(f)
{
System.out.println("Enter the Amount for Withdraw :");
amt=Double.parseDouble(br.readLine());
try
{
ob[k].withdraw(amt);
}
catch(LessBalanceException e)
{
}
}
else
System.out.println("Invalid Account Number....!!!");
break;
case 4:
System.out.println("Enter Account number\n");
an=Integer.parseInt(br.readLine());
for(k=0;k<2;k++)
if(an==ob[k].an)
{
f=true; break;
}
if(f)
{
ob[k].Balance();
}
else
System.out.println("Invalid Account Number....!!!");
break;
case 5:
b=false;
System.exit(1);
default: System.out.println("Invalid Choice !!!\n");
}
}
}
}
OUTPUT
SOURCE CODE:
try
{
sleep((int)(Math.random()*100));
}
catch(InterruptedException e){}
}
}
}
public class Consumer extends Thread{
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c ,int number){
cubbyhole=c;
this.number=number;
}
public void run(){
int value=0;
for(int i=0;i<10;i++)
{
value=cubbyhole.get();
System.out.println("Consumer #"+this.number+"got :"+value);
}
}
OUTPUT
SOURCE CODE:
interface IntStack
{
void push(int item);
int pop();
}
{
if(tos==stck.length-1)
{
}
else
stck[++tos]=item;
}
OUTPUT
SOURCE CODE:
class TwoGen<T,V>
{
T ob1;
V ob2;
TwoGen(T o1,V o2)
{
ob1=o1;
ob2=o2;
}
public String toString()
{
return "Type of T is:"+ob1.getClass().getName()+" "+"content of
T="+ob1+"\nType of V is :"+ob2.getClass().getName()+" "+"contents of
V="+ob2;
}
}
class import java.io.*;
import java.lang.String;
class first
{
String s1;
first(String s)
{
s1=s;
}
void disp()
{
System.out.println(s1);
}
}
class second
{
String s2;
second(String s)
{
s2=s;
}
void disp()
{
System.out.println(s2);
}
}
class tg<T,V>
{
T ob1;
V ob2;
tg(T o1,V o2)
{
ob1=o1;
ob2=o2;
}
Public String toString(){
System.out.println("type of T is " +ob1.getClass().getName());
System.out.println("type of V is " +ob2.getClass().getName());
return("object referece is used to call toString()");
}
T getob1()
{
return ob1;
}
V getob2()
{
return ob2;
}
}
class lab6
{
public static void main(String args[])
{
System.out.println("Initializing Strings in class Constructors:");
System.out.println("------------------------------");
first f = new first("class1");
second s = new second("class2");
f.disp();
s.disp();
System.out.println("------------------------------");
System.out.println("Two Type parameters using generic class");
System.out.println("------------------------------");
tg<Integer,String> conobj=new tg<Integer,String>(99,"Stringgenerics");
System.out.println(conobj);
int v=conobj.getob1();
System.out.println("Value is : " +v);
String str=conobj.getob2();
System.out.println("String is : " +str);
System.out.println("--------------------------------------");
System.out.println("By using above two classes");
tg<first,second> obfs = new tg<first,second>(f,s);
System.out.println(obfs);
System.out.println("--------------------------------------");
}
}
OUTPUT
SOURCE CODE:-
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList <String> ll=new LinkedList<String>();
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.add("Z");
ll.add("A");
ll.add(1,"A2");
System.out.println("Contents of LL:"+ll);
ll.remove("F");
ll.remove(2);
System.out.println("Contents of LL after Deleting:"+ll);
Object val=ll.get(2);
ll.set(2,(String)val+"changed");
System.out.println("Contents of LL after change :"+ll);
}
}
OUTPUT
SOURCE CODE:
import java.io.*;
public class FileInStreamDemo
{
public static void main(String[] args)
{
File file=new File("DevFile.txt");
int ch;
StringBuffer strContent=new StringBuffer(" ");
FileInputStream fin=null;
try{
fin= new FileInputStream(file);
while((ch=fin.read())!=-1)
strContent.append((char)ch);
fin.close();
}
catch(FileNotFoundException e)
{
System.out.println("File"+file.getAbsolutePath()+"could not be found on file
System");
}
catch(IOException ioe){
System.out.println("Exception while reading file"+ioe);}
System.out.println("File Contents:");
System.out.println(strContent);
}
OUTPUT
OR
import java.io.*;
public class FileOutputStreamDemo
{
public static void main(String[] args)
{
FileOutputStream out;
PrintStream p;
try
{
out=new FileOutputStream("DevFile.txt");
p=new PrintStream(out);
p.println("The Text Shown here will write to a file After run");
System.out.println("The is Written DevFile.txt");
p.close();
}catch(Exception e){
System.out.println("Error Writing to file");
}
}
}
OUTPUT
DevFile.txt
SOURCE CODE:
import java.util.Vector;
import java.io.*;
public class SerializationTest
{
static long start,end;
OutputStream out=null;
OutputStream outBuffer=null;
ObjectOutputStream objectOut=null;
public person getObject(){
person p = new person("SID","austin");
Vector<String> v=new Vector <String>();
for(int i=0;i<7000;i++)
{
v.addElement("SringObject"+i);
}
p.setData(v);
return p;
}
public static void main(String args[])
{
SerializationTest st=new SerializationTest();
start=System.currentTimeMillis();
st.writeObject();
end=System.currentTimeMillis();
System.out.println("Time taken"+(end-start)+"Milliseconds");
}
public void writeObject()
{
Try
{
out=new FileOutputStream("e:\\test.txt");
outBuffer=new BufferedOutputStream(out);
objectOut=new ObjectOutputStream(outBuffer);
objectOut.writeObject(getObject());
}
catch(Exception e){e.printStackTrace();}
finally
{
if(objectOut!=null)
try{ objectOut.close(); }
catch(IOException e){e.printStackTrace();}
}
}
}
class person implements java.io.Serializable
{
private String name;
OUTPUT
10. WRITE A JAVA PROGRAM TO WHICH USES DATAGRAM SOCKET FOR CLIENT
SERVER COMMUNICATION.
SOURCE CODE:
import java.net.*;
class WriteServer{
public static int serverPort=998;
public static int clientPort=999;
public static int buffer_size=1024;
public static DatagramSocket ds;
public static byte buffer[]=new byte[buffer_size];
public static void TheServer()throws Exception
{
int pos=0;
while(true){
int c=System.in.read();
switch(c)
{
case -1:
System.out.println("Server Quits");
return;
case '\r':
break;
case '\n':
ds.send(newDatagramPacket(buffer,pos,InetAddress.get
LocalHost(),clientPort));
pos=0;
break;
default: buffer[pos++]=(byte)c;
}
}
}
public static void TheClient() throws Exception
{
while(true)
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(),0,p.getLength()));
}
}
{
ds=new DatagramSocket(clientPort);
TheClient();
}
}
}
OUTPUT
SOURCE CODE:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents 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="mouseClicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="Mouse Entered";
repaint();
}
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="UP";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="*";
showStatus("Dragged at "+mouseX+","+mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
//mouseX=me.getX();
//mouseY=me.getY();
//msg="*";
showStatus("Moved at "+me.getX()+","+me.getY());
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,mouseX,mouseY);
}
OUTPUT
SOURCE CODE:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="SimpleKey"
width=300 height=100>
</applet>*/
public class SimpleKey extends Applet implements KeyListener{
String msg=" ";
int x=10,y=20;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("key down");
}
public void keyReleased(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
SOURCE CODE:
import java.rmi.*;
public class AddClient
{
public static void main(String arg[])
{
try
{
String AddServerURL="rmi://"+arg[0]+"/AddServer";
AddServerIntf
addServerIntf=(AddServerIntf)Naming.lookup(AddServerURL);
System.out.println("the 1st number is: "+arg[1]);
double d1= Double.valueOf(arg[1]).doubleValue();
System.out.println("the 2st number is: "+arg[2]);
double d2= Double.valueOf(arg[2]).doubleValue();
System.out.println("THE SUM IS:"+addServerIntf.add(d1,d2));
}
catch(Exception e)
{
}
}
}
import java.net.*;
import java.rmi.*;
public class AddServer
{
public static void main(String arg[])
{
try
{
AddServerImpl addServerImpl=new AddServerImpl();
Naming.rebind("AddServer",addServerImpl);
}
catch(Exception e)
{
}
}
}
import java.rmi.*;
import java.net.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf
{
public AddServerImpl() throws RemoteException { }
public double add(double d1,double d2)throws RemoteException
{
return d1+d2;
}
import java.rmi.*;
public interface AddServerIntf extends Remote
{
double add(double d1,double d2)throws RemoteException;
}
OUTPUT
SOURCE CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
/*
<applet code="lab14" width=600 height=600>
</applet>
*/
public class lab14 extends JApplet
{
public void init()
{
try
{
SwingUtilities.invokeAndWait
(
new Runnable()
{
public void run()
{
makeGUI();
}
}
);
}
catch(Exception e)
{
System.out.println(e);
}
}
private void makeGUI()
{
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("cities",new citiesPanel());
jtp.addTab("color",new colorPanel());
jtp.addTab("flavours",new flavourPanel());
jtp.addTab("gender",new genderPanel());
jtp.addTab("USN",new USNPanel());
jtp.addTab("Course",new CoursePanel());
add(jtp);
}
}
class citiesPanel extends JPanel implements ActionListener
{
JLabel clab;
public citiesPanel()
{
JButton b1=new JButton("NewYork");
b1.setActionCommand("NewYork");
b1.addActionListener(this);
add(b1);
JButton b2=new JButton("london");
b2.setActionCommand("london");
b2.addActionListener(this);
add(b2);
JButton b3=new JButton("HongKong");
b3.setActionCommand("HongKong");
b3.addActionListener(this);
add(b3);
JButton b4=new JButton("Toko");
b4.setActionCommand("Toko");
b4.addActionListener(this);
add(b4);
clab=new JLabel("click a boutton");
add(clab);
}
public void actionPerformed(ActionEvent ae)
{
clab.setText("you clicked:"+ae.getActionCommand());
}
}
class colorPanel extends JPanel implements ItemListener
{
JLabel colab;
JCheckBox cb;
public colorPanel()
{
cb=new JCheckBox("red");
cb.addItemListener(this);
add(cb);
cb=new JCheckBox("green");
cb.addItemListener(this);
add(cb);
cb=new JCheckBox("Blue");
cb.addItemListener(this);
add(cb);
colab=new JLabel("Select A color");
add(colab);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb=(JCheckBox)ie.getItem();
if(cb.isSelected())
colab.setText(cb.getText()+" is selected");
else
colab.setText(cb.getText()+" is cleared");
}
}
class flavourPanel extends JPanel implements ActionListener
{
String clist[]={"vanila","choclate","strawbery"};
JLabel flab;
JComboBox jcb;
public flavourPanel()
{
jcb=new JComboBox(clist);
jcb.addActionListener(this);
add(jcb);
flab=new JLabel("Select From Combo");
add(flab);
}
public void actionPerformed(ActionEvent ae)
{
flab.setText("you Selected:"+jcb.getSelectedItem());
}
}
class genderPanel extends JPanel implements ActionListener
{
JLabel glab;
public genderPanel()
{
JRadioButton rb1=new JRadioButton("M");
rb1.addActionListener(this);
add(rb1);
JRadioButton rb2=new JRadioButton("F");
rb2.addActionListener(this);
add(rb2);
ButtonGroup bg1= new ButtonGroup();
bg1.add(rb1);
bg1.add(rb2);
glab=new JLabel("Select One");
add(glab);
}
public void actionPerformed(ActionEvent ae)
{
glab.setText("You Clicked:"+ae.getActionCommand());
}
}
class USNPanel extends JPanel implements ListSelectionListener
{
JLabel ulab;
JList jlst;
String
USN[]={"1mv10mca01","1mv10mca02","1mv10mca03","1mv10mca04","1mv10mca05","1
mv10mca06","1mv10mca07","1mv10mca08","1mv10mca09","1mv10mca10"};
public USNPanel()
{
jlst=new JList(USN);
jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane JScrlp = new JScrollPane(jlst);
JScrlp.setPreferredSize(new Dimension(100,80));
jlst.addListSelectionListener(this);
add(JScrlp);
ulab=new JLabel("Select One");
add(ulab);
}
public void valueChanged(ListSelectionEvent le)
{
int idx=jlst.getSelectedIndex();
if(idx!=-1)
ulab.setText("current Selection"+USN[idx]);
else
ulab=new JLabel("selectone");
}
}
class CoursePanel extends JPanel implements TreeSelectionListener
{
JLabel tlab;
public CoursePanel()
{
DefaultMutableTreeNode top = new DefaultMutableTreeNode("course");
DefaultMutableTreeNode a = new DefaultMutableTreeNode("UG");
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("BA");
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("BCA");
DefaultMutableTreeNode a3 = new DefaultMutableTreeNode("BSC");
DefaultMutableTreeNode b = new DefaultMutableTreeNode("PG");
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("MCA");
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("MA");
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("MSC");
top.add(a);
a.add(a1);
a.add(a2);
a.add(a3);
top.add(b);
b.add(b1);
b.add(b2);
b.add(b3);
JTree jt =new JTree(top);
JScrollPane jsp = new JScrollPane(jt);
jsp.setPreferredSize(new Dimension(150,200));
jt.addTreeSelectionListener(this);
add(jsp);
tlab=new JLabel("select one");
add(tlab);
}
public void valueChanged(TreeSelectionEvent tse)
{
tlab.setText("Airrent Selection" +tse.getPath());
}
}
OUTPUT