Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday 12 December 2012

java program to develope chat server using ServerSocket and Socket class.

Client side:-

import java.net.*;
import java.io.*;
class Client
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),8888);
InputStream in=soc.getInputStream();
OutputStream out=soc.getOutputStream();

DataInputStream sin=new DataInputStream(in);
DataOutputStream sout=new DataOutputStream(out);
BufferedReader br=new BufferedReader(new       InputStreamReader(System.in));
String str;
while(true)
{
System.out.println("Server :"+sin.readUTF());
System.out.print("ME :");
str=br.readLine();
sout.writeUTF(str);
sout.flush();
}
}
}
               Server Side:-

          import java.net.*;
               import java.io.*;


             class Server
            {
          public static void main(String args[]) throws Exception
                 {
             //*******************************
                 //Remember we are storing Server socket into Socket by calling accept() method

            ServerSocket ss=new ServerSocket(8888);
            Socket soc =ss.accept();
                //*****************
          InputStream in=soc.getInputStream();
                OutputStream out=soc.getOutputStream();

               DataInputStream sin=new DataInputStream(in);
           DataOutputStream sout=new DataOutputStream(out);
             BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

           String str;

             sout.writeUTF("Wel come...Ready to recived you.");

       while(true)
        {
System.out.println("Client :"+sin.readUTF());
System.out.print("ME :");
str=br.readLine();
sout.writeUTF(str);
sout.flush();
      }


}
}


java swing program to retrive data from database and display using JTABLE



import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

class ShowFrame extends JFrame
{
ShowFrame()
{ try
{



JTable tab = new JTable();
  JScrollPane sc=new JScrollPane(tab);
DefaultTableModel df=new DefaultTableModel();
add(sc);

Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost/nirav","root","root");
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery("select * from t1 ");


ResultSetMetaData meta= rs.getMetaData();
int count=meta.getColumnCount();
String c[]=new String[count];
for(int i=0;i<count;i++)
{
c[i]=meta.getColumnName(i+1);
df.addColumn(c[i]);
}


Object row[]=new Object[count];
while(rs.next())
{
for(int i=0;i<count;i++)
{
row[i]=rs.getString(i+1);
}
df.addRow(row);
}

tab.setModel(df);
//add(pan);
rs.close();
  cn.close();
}
catch(Exception e)
{
}
}

             }


class MainRetrive
{
public static void main(String str[])
{
ShowFrame sf=new ShowFrame();
//sf.setSize(200,200);
sf.setBounds(200,200,400,300);
sf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sf.setVisible(true);

}

}

java swing program with jdbc to performed insert and retrive opeartion.




import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

class ShowFrame extends JFrame
{
ShowFrame()
{ try
{

JTable tab = new JTable();
JScrollPane sc=new JScrollPane(tab);


DefaultTableModel df=new DefaultTableModel();
add(sc);
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost/nirav","root","root");
Statement st=cn.createStatement();


ResultSet rs=st.executeQuery("select * from t1 where");
ResultSetMetaData meta= rs.getMetaData();
int count=meta.getColumnCount();
String c[]=new String[count];


for(int i=0;i<count;i++)
{
c[i]=meta.getColumnName(i+1);
df.addColumn(c[i]);
}
Object row[]=new Object[count];
while(rs.next())
{
for(int i=0;i<count;i++)
{
row[i]=rs.getString(i+1);
}
df.addRow(row);
}
tab.setModel(df);

rs.close();
cn.close();
}

catch(Exception e)
{
System.out.println(e.toString());
}
}

}
class MyClass extends JFrame
{
JLabel l1,l2,l3;
JTextField id,name;
JPanel pan;
JButton insert,retrive;
MyClass()
{
l1=new JLabel("Id");
l2=new JLabel("Name");
l3=new JLabel("");
id=new JTextField(15);
name=new JTextField(15);
insert=new JButton("Insert");
retrive=new JButton("Retrive");

pan=new JPanel(new GridLayout(4,2));
pan.add(l1);
pan.add(id);
pan.add(l2);
pan.add(name);
pan.add(insert);
pan.add(retrive);
pan.add(l3);
add(pan,BorderLayout.CENTER);

insert.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{ try{

Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost/nirav","root","root");

Statement st=cn.createStatement();
int idd=Integer.parseInt(id.getText());
String n=name.getText();
int i=st.executeUpdate("insert into t1(id,name) values("+ idd +",'"+ n +"')");
cn.close();
l3.setText(i+"successFully inserted");
}
catch(Exception e)
{l3.setText(e.toString());}
}
});
retrive.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
ShowFrame sf=new ShowFrame();
//sf.setSize(200,200);
sf.setBounds(200,200,400,300);
sf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sf.setVisible(true);

}
});
}
}


class MainInsert
{
public static void main(String str[])
{

MyClass frm=new MyClass();
frm.setSize(200,200);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frm.setVisible(true);

}

}

Thursday 6 September 2012

java program to find string matching in another string.


import java.io.*;

class paturn_match
{
       public static void main(String args[]) throws IOException
       {
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             char test[] = new char[100];
             char given_str[] = new char[15];
             String temp;
             int i,j,lentext,lenp,flag=0,count=0;
         
             System.out.print("Enter Text  =  ");
             temp = br.readLine();
             test = temp.toCharArray();
             lentext = temp.length();
         
             System.out.print("Enter Paturn  =  ");
             temp = br.readLine();
             given_str = temp.toCharArray();
             lenp = temp.length();

             for(i=0;i!=lentext-1;i++)
             {
                   j=i;
                   int k=0;
                   flag=0;
                         while((test[i] == given_str[k]) && (flag !=1))
                         {
                               j=j+1;
                               k=k+1;
                                    if(k>=(lenp-1))
                                    {
                                          flag=1;
                                          break;
                                    }
                         } //WHILE
                     
                         if((k>0) && (flag==1))
                         {
                               System.out.println(" Paturn found at  " + i);
                               count++;
                         }
            }  // FOR LOOP
        
            System.out.println(" count = " + count);
    }
} //paturn_match.java

output:


Enter Text  =  hello hello
Enter Paturn  =  he
 Paturn found at  0
 Paturn found at  6
 count = 2

Tuesday 4 September 2012

java program to use awt check box in applet.


// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet implements ItemListener
{
String msg = "";
Checkbox obj1, obj2, obj3, obj4;
public void init()
{
obj1 = new Checkbox("A",  false);
obj2 = new Checkbox("B",  false);
obj3 = new Checkbox("C",  true);
obj4 = new Checkbox("D",  false);
add(obj1);
add(obj2);
add(obj3);
add(obj4);
obj1.addItemListener(this);
obj2.addItemListener(this);
obj3.addItemListener(this);
obj4.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
//repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g)
{
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " A: " + obj1.getState();
g.drawString(msg, 6, 100);
msg = " B: " + obj2.getState();
g.drawString(msg, 6, 120);
msg = " C: " + obj3.getState();
g.drawString(msg, 6, 140);
msg = " D: " + obj4.getState();
g.drawString(msg, 6, 160);
}
}

Output:

java program to use awt check box group in applet.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/
public class CBGroup extends Applet implements ItemListener
{
String msg = "";
Checkbox obj1, obj2, obj3, obj4;
CheckboxGroup cbg;

public void init()
{
cbg = new CheckboxGroup();
obj1 = new Checkbox("A", cbg, false);
obj2 = new Checkbox("B", cbg, false);
obj3 = new Checkbox("C", cbg, true);
obj4 = new Checkbox("D", cbg, false);
add(obj1);
add(obj2);
add(obj3);
add(obj4);
obj1.addItemListener(this);
obj2.addItemListener(this);
obj3.addItemListener(this);
obj4.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g)
{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
}
output:

Wednesday 29 August 2012

Program for calculating total elapsed time using the concept of multithreading and System.currentTimeMillis() method.


import  java.io.*;
class Child extends Thread
{
Child(String str)
{
super(str);
start();
}
public void run()
{

try
{
for(int n=1;n<=5;n++)
{
System.out.println("Child thread: "+n);
Thread.sleep(1000);
}

}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}

}
}

class prog
{
public static void main(String a[]) throws Exception
{
long timestart = System.currentTimeMillis();
new Child("child");

Thread t = Thread.currentThread();
//System.out.println("current thread"+t);
t.setName("my thread");

try
{

for(int n=1;n<=5;n++)
{
System.out.println("main thread: "+n);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println("not  valid");
}
long timelast = System.currentTimeMillis();
float result =(timelast-timestart)/1000;
System.out.println("total time elapsed in seconds :  "+result);

}
}


main thread: 1
Child thread: 1
main thread: 2
Child thread: 2
main thread: 3
Child thread: 3
Child thread: 4
main thread: 4
main thread: 5
Child thread: 5
total time elapsed in seconds :  5.0

Sunday 19 August 2012

insertion and deletion of node (value) in singly linked list in java

import java.io.*;
class Node
{
    private Node next;
    private int data;
    Node(int data)
    {
        this.data=data; 
    } 
 
    public    Node getNext()
    {
        return next;
    }

  public void setNext(Node next)
    {
        this.next=next;
    }

    public    int getData()
    {
        return data;
    }
    public void setData(int data)
    {
        this.data=data;

    }
}



class LinkList
{
    Node head=null;
 
    public void addValue(int data,int pdata)
    {
        Node newNode=new Node(data);
        if(head == null)
        {
            head=newNode;
        }
        else if(head.getData() == pdata && head.getNext() == null)
        {
            head.setNext(newNode);
     
        }
        else
        {
            Node trav=head;
            //Node prev=null;
            while(trav != null && trav.getData() != pdata)
            {
                //prev=trav;
                trav=trav.getNext();
             
            }
         
            if(trav == null)
            {
                System.out.println("Give Value not found");
            }
            else
            { 
                Node temp= trav.getNext();
                newNode.setNext(temp);
                trav.setNext(newNode);
            }
         
        }
    }
    public void deleteValue(int data)
    {
     
        if(head==null)
        {
            System.out.println("LInk LIst is empty");
        }
        else if(head.getData() == data)
        {
            head=head.getNext();
     
        }
        else
        {
            Node trav=head;
            Node prev=null;
            while(trav != null &&  trav.getData() != data)
            {
                prev=trav;
                trav=trav.getNext();
             
            }
         
            if(trav == null)
                System.out.println("Give Value not found");
         
            else
            {
                prev.setNext(trav.getNext());
            }
         
        }
    }
    public void display()
    {
        if(head==null)
        {
            System.out.println("LInk LIst is empty");
        }
        else
        {
            Node trav=head; 
            while(trav.getNext() !=null )
            {
                System.out.print(trav.getData()+"->");
                trav=trav.getNext();
             
            }
         
            System.out.println(trav.getData());
        }
    }
}

class PracQuiz
{
        public static void main(String args[]) throws IOException
        {
            LinkList ls=new LinkList();
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            int ch,d,p;
            do
            {
                System.out.println("Menu----");     
                System.out.println("1.Insert after value"); 
                System.out.println("2.Delete By value"); 
                System.out.println("3.Display"); 
                System.out.println("4.Exit"); 
                System.out.println("ENter Your Choice"); 
                ch=Integer.parseInt(br.readLine());
             
                switch(ch)
                {
                case 1:
                    System.out.println("Insert data after you want your New Node"); 
                    d=Integer.parseInt(br.readLine());
                    System.out.println("Insert  value  after you want to enter new Node"); 
                    p=Integer.parseInt(br.readLine());
                    ls.addValue( d, p);
                    break;
                case 2:
                    System.out.println("Insert  data of node that you want to delete"); 
                    d=Integer.parseInt(br.readLine());
                    ls.deleteValue(d);
                    break;
                case 3:
                    System.out.println("Your Link list is:");
                    ls.display();
                    break;
                case 4:         
                    break;
                }
             
            }while(ch!=4);
                   
        }
 
}

Friday 10 August 2012

program to use of MosueListener and MouseMotionListener interfaces in applet.



import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MyMouse" width=500 height=400>
</applet>
*/
public class MyMouse extends Applet implements MouseListener,MouseMotionListener
{
String msg=" ";
int x,y;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="click";
showStatus("x--"+x+"  y--"+y +"moused clicked");
repaint();
}
public void mouseEntered(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="";
showStatus("x--"+x+"  y--"+y +"moused Enterd");
repaint();
}
public void mouseExited(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="";
showStatus("x--"+x+"  y--"+y +"moused Exited");
repaint();
}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="";
showStatus("x--"+x+"  y--"+y +"moused Pressed");
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="Released";
showStatus("x--"+x+"  y--"+y +"moused Released");
repaint();
}
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="*";
showStatus("x--"+x+"  y--"+y +"moused Dragged");
repaint();
}
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="";
showStatus("x--"+x+"  y--"+y +" moused moved");
repaint();
}
public void paint(Graphics g)
{
 
g.drawString(msg,x,y);
}
}

Thursday 19 July 2012

Display all properties in java

public class Display 
{
    public static void main(String[] args) 

   {
         System.getProperties().list(System.out);
    }
}

Saturday 7 July 2012

program that describe use of ActionListener interface in applet

import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="text" width=200 height=200>
</applet>
*/
 public class text extends Applet implements ActionListener
{
    Label lbl1,lbl2;
    TextField txt1,txt2;
    Button b;
    String s;
      public void init()
      {
       lbl1=new Label("Text1");
       txt1=new TextField(10);
       lbl2=new Label("Text2");
       txt2=new TextField(20);
        b=new Button("Enter");
        add(lbl1); 
        add(txt1); 
        add(lbl2); 
        add(txt2);
         add(b); 
        txt1.addActionListener(this);
        txt2.addActionListener(this);
        b.addActionListener(this);
       }
        public void actionPerformed (ActionEvent ae)
       { int n1,n2,ans;
    try
    {
    n1=Integer.parseInt(txt1.getText());
    n2=Integer.parseInt(txt2.getText());
    ans=n1+n2;
    s="Addition of n1 ans n2  is "+ ans;
    repaint();
    }
    catch(NumberFormatException e)
    {
       
    s=txt1.getText()+" "+txt2.getText();
    repaint();
    }
       }
       public void paint(Graphics g)
       {
        g.drawString(s,100,100);
     

       }
}

program to illustrate use of Label, TextField in applet.


import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/* <applet code = "applet1" height=150 width=380>
   </applet>
*/

public class applet1 extends Applet implements ActionListener
{
   TextField age,hobby;
  public void init()
      {
            Label l1,l2;
            l1 = new Label("Age :- ",Label.RIGHT);
            l2 = new Label("Hobby :- ");
     
            age=new TextField(5);
            hobby=new TextField(12);
           
            add(l1);
            add(age);
            add(l2);
            add(hobby);
           
            age.addActionListener(this);
            hobby.addActionListener(this);
               
       }
   // User pressed Enter
   public void actionPerformed(ActionEvent ae)
   {
    repaint();
    }
   public void paint(Graphics g)
    {
     g.drawString("Age :- " + age.getText(),6,60);
     g.drawString("Hobby :- " + hobby.getText(),6,80);
    }     
}      

program that dispaly rotating banner in applet

import java.awt.*;
import java.applet.*;

/* <applet code="banner" width=300 height=200>
   </applet> */

 public class banner extends Applet implements Runnable 
   {
     Font f;
    String mgs="welcome to applet programming language...";
    Thread t=null;
    int state;
    boolean stopflag;
 public void init()
   {
     f=new Font(mgs,Font.ITALIC|Font.BOLD,30);
    setBackground(Color.red);
    setForeground(Color.black);
    setFont(f);

   }
 public void start()
   {
    t=new Thread(this);
    stopflag=false;
    t.start();
   }
 public void run()
   {
    char ch;
    for(;;)
    {
    try
     {
      repaint();
      Thread.sleep(500);
      ch=mgs.charAt(0);
      mgs=mgs.substring(1,mgs.length());
      mgs +=ch;
      if(stopflag)
        break;
     }catch(InterruptedException e){}
   }
 }
 public void stop()
   {
    stopflag=true;
    t=null;
   }
 public void paint(Graphics g)
   {
    g.drawString(mgs,100,100);
   }
 }

Wednesday 4 July 2012

program that demostrate used of for in loop in java.

import java.io.*;

class ForInLoop
{
    public static void main(String args[])
    {
    int a[ ]=new int[10];
    a[0]=1;
    a[1]=2;
    a[2]=3;
   
    a[4]=5;
    a[5]=6;
    a[6]=7;
    a[7]=8;
    a[8]=9;
   

program to performed quick sort using java.

import java.io.*;
class QuickSort
{
int lb,ub,a[];
QuickSort(int n)
{
    a=new int[n];   
}

   
void quick(int lb,int ub)
{    int i;
    int j;
    boolean flag;
    int key;
    if(lb<ub)
        {   
             i=lb;
             j=ub+1;
             flag=true;
             key=a[lb];
       

program to perfomed Shell sort using java.

import java.io.*;
class ShellSort
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int a[]=new int[9];
        int h;
        int inc[]=new int[9];
        int t,i,j,k;
        for(i=0;i<9;i++)
        {
            a[i]=Integer.parseInt(br.readLine());
        }  
      

Monday 2 July 2012

program that performed insertion after value and deletion by value operation in Linked List.

import java.io.*;
class Node
{
    private Node next;
    private int data;
    Node(int data)
    {
        this.data=data;   
    }   
   
    public    Node getNext()
    {
        return next;
    }

Performed Insertion sort on array in java.

import java.io.*;
class InsertionSort
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int a[]=new int[4];
        int t,i,j;
        for(i=0;i<4;i++)
        {
            t=Integer.parseInt(br.readLine());
            a[i]=t;
        }   
        for(i=1;i<a.length;i++)
        {    t=a[i];   
            System.out.println("pass :"+i);
            for(j=i-1;j>=0 && t<a[j];j--)
            {
                               
                    System.out.println("exchange");
                    a[j+1]=a[j];
                 
            }
            a[j+1]=t;       
        }
        for(i=0;i<a.length;i++)
        {
            System.out.println(a[i]);
   
        }
   
    }
}

program that display reverse string in java.

import java.io.*;
import java.util.*;
class Revs
{
   public static void main(String args[]) throws IOException
   {
     final String s;
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     s=br.readLine();
    final char[] word = s.toCharArray();
    final int l = s.length() - 2;
    final int ll = s.length() - 1;
    for (int i = 0; i < l; i++)
    {
        char x = word[i];
        word[i] = word[ll - i];
        word[ll - i] = x;
    }
System.out.println(s);
System.out.println();
System.out.println(new String(word));
   }
}

Saturday 30 June 2012

program to calculate factorial for given number using Recursion in java.

class Factorial
{
    int fact(int n)
    {
        int result;
        if(n==1) return 1;
        result = fact(n-1) * n;
    return result;
    }
}

class Recursion
{
  public static void main(String args[])
  {
    Factorial f = new Factorial();

    System.out.println("Factorial of 5 is " + f.fact(5));

  }
}