Saturday, January 14, 2012

Java Programs

I have posted all the JAVA programs except a few. It totals upto 20. The list is :

1a Recursive Fibonacci
1b Non-Recursive Fibonacci
2a Prime Nos.
2b Matrix Multiplication
2c String Tokenizer Class
3a Inheritance
3b String Class and String Buffer Calss
4a Vector Class
4c Stack Class
5a Applet Program
5b Text Field and Label Applet
6 Exceptions
7a Multiple Threading
7b Inter-Thread Communication
8 Package and Interface
9 Abstract Classes
10a Client Application
10b Server Application
11 Read and Write a file
12 Drawing Shapes

10b Server Application


import java.net.*;
import java.io.*;
class Server
  {
    public static DatagramSocket ds;
    public static byte buffer[]=new byte[1024];
    public static int clientport=790,serverport=789;
    public static void main(String args[])throws IOException
     {
       ds=new DatagramSocket(serverport);
       System.out.println("\t\t*****************\n\t\t**SEVER PROGRAM**\n\t\t*****************\nPRESS ctrl+C TO COMEPROMPT");
       while(true)
        {
  DatagramPacket p=new DatagramPacket(buffer,buffer.length);
  ds.receive(p);
  String psx=new String(p.getData(),0,p.getLength());
  System.out.println(psx);
        }

     }
  }


11 Read and Write a file


import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;

public class ReadWriteFile
   {
    private static void doReadWriteTextFile()
     {
        try
         {
            String inputFileName  = "sample.txt";
            String outputFileName = "sample1.txt";
            FileReader inputFileReader   = new FileReader(inputFileName);
            FileWriter outputFileReader  = new FileWriter(outputFileName);
            BufferedReader inputStream   = new BufferedReader(inputFileReader);
            PrintWriter    outputStream  = new PrintWriter(outputFileReader);
            String s = null;
            while ((s = inputStream.readLine()) != null)
             {
System.out.println(s);
                outputStream.println(s);
             }

            outputStream.close();
            inputStream.close();

         }
        catch (IOException e)
         {

            System.out.println("IOException:");
            e.printStackTrace();
         }

    }

    public static void main(String[] args)
    {
        doReadWriteTextFile();
    }

 }

12 Drawing Shapes


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

public class Drawing extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
g.drawRect(10,10,60,40);
g.drawOval(60,60,50,50);
}
}

//<applet code="Drawing" width="300" height="300">
//</applet>

8 Package and Interface


import a.*;

interface Area
 {
   float compute(float x, float y);
 }

class Rectangle implements Area
 {
   public float compute(float x, float y)
    {
return(x * y);
    }
 }

class Triangle implements Area
 {
   public float compute(float x,float y)
    {
return(x * y/2);
    }
 }

class InterfaceArea
 {
   public static void main(String args[])
    {
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
System.out.println("Area Of Rectangle = "+ area.compute(1,2));
area = tri;
System.out.println("Area Of Triangle = "+ area.compute(10,2));
    }
 }

9 Abstract Classes


abstract class Figure
 {
   double dim1;
   double dim2;
   Figure(double a, double b)
    {
      dim1 = a;
      dim2 = b;
    }

   abstract double area();
 }

class Rectangle extends Figure
 {
   Rectangle(double a, double b)
    {
      super(a, b);
    }

   double area()
    {
      System.out.println("Inside Area for Rectangle.");
      return dim1 * dim2;
    }
 }

class Triangle extends Figure
 {
   Triangle(double a, double b)
    {
      super(a, b);
    }

   double area()
    {
      System.out.println("Inside Area for Triangle.");
      return dim1 * dim2 / 2;
    }
 }

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

      Rectangle r = new Rectangle(9, 5);
      Triangle t = new Triangle(10, 8);
      Figure figref;
      System.out.println("Area is " + r.area());
      System.out.println("Area is " + t.area());
    }
 }

10a Client Application


import java.net.*;
import java.io.*;
class Client
  {
     public static DatagramSocket ds;
     public static int clientport=790,serverport=789;
     public static void main(String args[])throws IOException
      {
        byte buffer[]=new byte[1024];
        ds=new DatagramSocket(clientport);
        BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("\t\t******************\n\t\t**CLIENT PROGRAM**\n\t\t*********\nCLIENT WAITING FOR INPUT");
        InetAddress ia=InetAddress.getByName("localhost");
        while(true)
         {
   String str=dis.readLine();
   if(str==null||str.equals("end"))
   break;
   buffer=str.getBytes();
   ds.send(new DatagramPacket(buffer,str.length(),ia,serverport));
         }
      }

}


6 Exceptions

Will Come soon ;)

7a Multiple Threading


//MULTITHREAD

class mul1 implements Runnable
{
  public void run()
   {
try
{
    for(int i=1;i<=10;i++)
    {
         System.out.println(i+"x2="+(i*2));
         Thread.sleep(800);
     }
  }        
  catch(Exception e)
    {     }    
 }
}
class multible
  {
 public static void main(String args[])

   {
    mul1 ob=new mul1();  
    Thread t1=new Thread(ob);
    Thread t2=new Thread(ob);
    Thread t3=new Thread(ob);

    t1.start();
    t2.start();
    t3.start();
   }
 }

7b Inter-Thread Communication

Will come Soon ;)

5b Text Field and Label Applet

Will come Soon ;)

4c Stack Class


import java.util.*;

public class StackDemo
{
  public static void main(String[] args)
  {
    Stack stack=new Stack();
    stack.push(new Integer(10));
    stack.push("a");
    System.out.println("The contents of Stack is" + stack);
    System.out.println("The size of an Stack is" + stack.size());
    System.out.println("The number poped out is" + stack.pop());
    System.out.println("The number poped out is " + stack.pop());
    System.out.println("The contents of stack is" + stack);
    System.out.println("The size of an stack is" + stack.size());
  }
}

5a Applet Program


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

public class SampleApplet extends Applet
  {
     public void init()
       {
           setBackground(Color.blue);
           setForeground(Color.red);
       }
    public void paint(Graphics g)
      {
          g.drawString("Welcome to java",20,20);
      }
 }

//<applet code="SampleApplet" width=300 height=200>
//</applet>

3b String Class and String Buffer Calss


import java.io.*;

public class stringBuffer
  {
    public static void main(String[] args) throws Exception
     {
       BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
       String str;
       try
{
   //String

   String s=new String("Welcome");

   //length
   System.out.println("String Length:  "+s.length());

   //concat
     s=s.concat(" to BDU");
                System.out.println("New String   "+ s);

                //charat
                System.out.println("Character at 2nd position: "+s.charAt(2));

                //Substring

                System.out.println("Sub String: "+ s.substring(0,5));

   //String Buffer

                StringBuffer strbuf=new StringBuffer();
       
                //append
           strbuf.append("Hello");
             strbuf.append("World");          
                System.out.println(strbuf);
   
                //insert
                strbuf.insert(5,"_Java ");        
                System.out.println(strbuf);
   
                //reverse
                strbuf.reverse();
                System.out.print("Reversed string : ");
                System.out.println(strbuf);        
                strbuf.reverse();
                System.out.println(strbuf);        
   
                //setCharAt
                strbuf.setCharAt(5,' ');
                System.out.println(strbuf);        
   
                //charAt
                System.out.print("Character at 6th position : ");
                System.out.println(strbuf.charAt(6));  

                //substring
                System.out.print("Substring from position 3 to 6 : ");
       System.out.println(strbuf.substring(3,7));
         
                //deleteCharAt
       strbuf.deleteCharAt(3);
               System.out.println(strbuf);        
   
               //capacity
        System.out.print("Capacity of StringBuffer object : ");
       System.out.println(strbuf.capacity());    
   
          }
       catch(StringIndexOutOfBoundsException e)
         {
                System.out.println(e.getMessage());
         }
     }
  }

3a Inheritance

Will come Soon ;)

2c String Tokenizer Class


import java.util.StringTokenizer;
class StringToken
  {
    static String in = "Welcome to CSBDU";
    public static void main(String args[])
     {
StringTokenizer st = new StringTokenizer(in);
while(st.hasMoreTokens())
{
String t = st.nextToken();
System.out.println(t);
}
     }
 }

4a Vector Class


// Vector Class Example

import java.util.*;
public class VectorDemo
{
  public static void main(String[] args)
  {
    Vector v = new Vector();
    int i = 10;
    Integer j = new Integer(20);
    String s = "Welcome";
    v.add(i);
    v.add(j);
    v.add(s);
    System.out.println("the elements of vector: " + v);
    System.out.println("The size of vector are: " + v.size());
    System.out.println("The elements at position 2 is: " + v.elementAt(2));
    System.out.println("The first element of vector is: " + v.firstElement());
    System.out.println("The last element of vector is: " + v.lastElement());
    v.removeElementAt(2);
    Enumeration e=v.elements();
    System.out.println("The elements of vector: " + v);
    while(e.hasMoreElements())
    {
      System.out.println("The elements are: " + e.nextElement());
    }
  }
}


2b Matrix Multiplication


import java.io.*;
import java.util.*;
public class Matrix
{
    public static void main(String a[]) throws Exception
    {
         int r;
         int c;
         int r1;
         int c1;
         int[][] matrix_A;
        int[][] matrix_B;
        int[][] matrix_ans;

        Scanner cin=new Scanner(System.in);
        System.out.println("Enter the number of rows in matrix A : ");
        r=cin.nextInt();
        System.out.println("Enter the number of columns in matrix A : ");
        c=cin.nextInt();
        System.out.println("Enter the number of rows in matrix B : ");
        r1= cin.nextInt();
        System.out.println("Enter the number of columns in matrix B : ");
        c1=cin.nextInt();
     
        if(c==r1)
        {
            matrix_A=new int[r][c];
            matrix_B=new int[r1][c1];
            matrix_ans=new int[r][c1];
            int x,y;
            x=matrix_A.length;
            y=matrix_B.length;
          System.out.println("Enter the elements of matrix A : ");
             for(int i=0;i<r;i++)
                 for(int j=0;j<c;j++)
                 {
                    matrix_A[i][j]=cin.nextInt();
                 }
          System.out.println("Enter the elements of matrix B : ");
            for(int i=0;i<r1;i++)
                 for(int j=0;j<c1;j++)
                 {
                    matrix_B[i][j]=cin.nextInt();
                 }
   for(int i = 0; i < x; i++)
    {
      for(int j = 0; j < y; j++)
       {
         for(int k = 0; k < y; k++)
           {
              matrix_ans[i][j] += matrix_A[i][k]*matrix_B[k][j];
           }
       }
    }
  for(int i = 0; i < x; i++)
    {
      for(int j = 0; j < y; j++)
       {
         System.out.print(" "+matrix_ans[i][j]);
       }
      System.out.println();
    }
             }
     
        else
        {
        System.out.println("Cant multiply");
        }
    }
}

2a Prime Nos.


import java.io.*;

class PrimeNumber
  {
    public static void main(String[] args) throws Exception
     {
int i;
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter number:");
        int num = Integer.parseInt(bf.readLine());
        System.out.println("Prime number: ");
        for (i=1; i < num; i++ )
         {
           int j;
           for (j=2; j<i; j++)
            {
        int n = i%j;
       if (n==0)
                 {
                    break;
                 }
            }
           if(i == j)
            {
        System.out.print("  "+i);
            }
        }
     }
  }  

1b Non-Recursive Fibonacci


import java.io.*;

public class FibonnaciSeries
  {

    public void generateSeries(int num)
     {

       int f1, f2 = 0, f3 = 1;

       System.out.println("fib(0) = " + f2);

       for (int i = 1; i <= num; i++)
        {
  System.out.println("fib(" + i + ") = " + f3);
  f1 = f2;
  f2 = f3;
  f3 = f1 + f2;
}
     }

    public static void main(String[] args) throws Exception
     {
        System.out.println("Fibonnaci Series");
System.out.println("Enter n value");
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int n;
n=Integer.parseInt(b.readLine());
        FibonnaciSeries fb = new FibonnaciSeries();
fb.generateSeries(n);
     }

  }

1a Recursive Fibonacci


import java.io.*;
 public class Fibonacci
   {
      public static void main(String[] args) throws Exception
        {
System.out.println("Enter n value");
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int n;
n=Integer.parseInt(b.readLine());

          for (int i = 1; i <= n; i++)
           {
             int f = fib(i);
             System.out.println("fib(" + i + ") = " + f);
           }
          System.exit(0);
     
        }

      public static int fib(int n)
        {
            if (n <= 2)
              return 1;
            else
              return fib(n - 1) + fib(n - 2);
        }
   }