SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
Date: 16-12-2008
Week-1a)
Aim: Write a java program that print all roots of equation of quadratic a,b,c will be supplied
through keyboard
Code:
import java.lang.*;
import java.math.*;
class Quad
{
       public static void main(String arg[])
       {
              int a,b,c;
              a=Integer.parseInt(arg[0]);
              b=Integer.parseInt(arg[1]);
              c=Integer.parseInt(arg[2]);
              int delta=(b*b)-(4*a*c);
               if(delta<0)
              {
                       System.out.println("roots are imaginary,no real values");
                }
               else
               {
                      double x1=(-b+Math.sqrt(delta))/(2*a);
                      double x2=(-b-Math.sqrt(delta))/(2*a);
                      System.out.println(x1+" "+x2);
              }
       }
 }

Output:




                                               WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-1b)
Aim: Write a java program that uses both recursive and non recursive functions to print the
nth value in Fibonacci series.
Code:
import java.lang.*;
class Fibo
{
       public static void main(String arg[ ])
       {
              int f,f1=0,f2=1,n;
              n=Integer.parseInt(arg [0]);
              System.out.println(f1);
              System.out.println(f2);
              for(int i=0;i<n-1;i++)
              {
                      f=f1+f2;
                      f1=f2;
                      f2=f;
                      System.out.println(f);
              }
              System.out.println("Fibonacci series using recursion");
              for(int i=0;i<n;i++)
                      System.out.println(fib(i));
}
              static int fib(int n)
              {
                      if(n==0||n==1)
                             return 1;
                      else
                             return fib(n-1)+fib(n-2);
              }

}




                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Output:




          WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Date: 23-12-2008
Week-2a)
Aim: Write a java program that prompts the user for an integer and then prints out all
prime numbers upto the integer.
Code:
import java.lang.*;
class Prime
{
       public static void main(String arg[])
       {
              int n,c,i,j;
              n=Integer.parseInt(arg[0]);
              System.out.println("prime numbers are");
              for(i=1;i<=n;i++)
              {
                     c=0;
                     for(j=1;j<=i;j++)
                     {
                            if(i%j==0)
                            c++;
                     }
              if(c==2)
              System.out.println("       "+i);
       }
   }
}


Output:




                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-2b)
Aim: Write a java program to multiply two given matrices.
Code:
import java.lang.*;
import java.io.*;
class Matrix
{
       public static void main(String arg[])throws IOException
       {
              DataInputStream dis=new DataInputStream(System.in);
              System.out.println("Enter The Row Size Of The First Matrix");
              int r1=Integer.parseInt(dis.readLine());
              System.out.println("Enter The Column Size Of The First Matrix");
              int c1=Integer.parseInt(dis.readLine());
              System.out.println("Enter The Row Size Of The Second Matrix");
              int r2=Integer.parseInt(dis.readLine());
              System.out.println("Enter The Column Size Of The Second Matrix");
              int c2=Integer.parseInt(dis.readLine());
              int a[][]=new int[r1][c1];
              int b[][]=new int[r2][c2];
              int c[][]=new int[r1][c2];
              int i,j,k;
              System.out.println("Enter The Elements Into The First Matrix");
              for(i=0;i<r1;i++)
              for(j=0;j<c1;j++)
              {
                      a[i][j]=Integer.parseInt(dis.readLine());
              }
              System.out.println("Enter The Elements Into The Second Matrix");
              for(i=0;i<r2;i++)
              for(j=0;j<c2;j++)
              {
                      b[i][j]=Integer.parseInt(dis.readLine());
              }
              if(c1!=r2)
              System.out.println("Multiplication Is Not Possible");
              else
              {
                      for(i=0;i<r1;i++)
                      {
                              for(j=0;j<c1;j++)
                              {
                                     c[i][j]=0;
                                     for(k=0;k<r2;k++)
                                     {


                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
c[i][j]=c[i][j]+a[i][k]*b[k][j];
                            }
                     }
              }
              for(i=0;i<r1;i++)
              {
                     for(j=0;j<c2;j++)
                     {
                             System.out.println(c[i][j]+"        ");
                     }
                     System.out.println("        ");
              }
          }
     }
}


Output:




                                          WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-2c)
Aim: Write a program that display each integer and sum of all integers using stringtokenizer.
Code:
import java.util.*;
class Stringtoken
{
       public static void main(String arg[])
       {
              int sum=0;
              StringTokenizer sto=new StringTokenizer(arg[0],":");
              System.out.println(sto.countTokens());
              while(sto.hasMoreTokens())
              {
                     int a=Integer.parseInt(sto.nextToken());
                     sum=sum+a;
                     System.out.println(a);
              }
                     System.out.println("sum= "+sum);

      }
}

Output:




                                              WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Date: 30-12-2008
Week-3a)
Aim: Write a java program that checks whether a given string is a palindrome or
not.Ex:MADAM
Code:
import java.lang.*;
import java.io.*;
import java.util.*;
class Palindrome
{
       public static void main(String arg[ ]) throws IOException
       {
              DataInputStream dis=new DataInputStream(System.in);
              String word=dis.readLine( );
              int flag=1;
              int left=0;
              int right=word.length( )-1;
              while(left<right)
              {
                      if(word.charAt(left)!=word.charAt(right))
                      {
                             flag=0;
                             //break;
                      }
                      left++;
                      right--;}
              if(flag==1)
                      System.out.println("palindrome");
              else
                      System.out.println("not palindrome");
       }
}
Output:




                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-3b)
Aim:Write a java program for sorting a given list of name in ascending order.
Code:
import java.lang.*;
import java.io.*;
import java.util.*;
class Sort
{
       public static void main(String arg[ ]) throws IOException
       {
              DataInputStream dis=new DataInputStream(System.in);
              System.out.println("enter the size");
              int n=Integer.parseInt(dis.readLine());
              String array[ ]=new String[n];
              System.out.println("enter names");
              for(int i=0;i<n;i++)
              {
                     array[i]=dis.readLine();
              }
              for(int i=0;i<n;i++)
              {
                     for(int j=0;j<n-1;j++)
                     {
                             if(array[j].compareTo(array[j+i])>0)
                             {
                                    String temp=array[j];
                                    array [j]=array[j+1];
                                    array[j+1]=temp;
                             }
                     }
              }
              System.out.println("the sorted strings are");
              for(int i=0;i<n;i++)


                                              WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
System.out.println(array[i]);
     }
}




Output:




                                     WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-3c)
Aim: Write a java program to make frequency count of words in a given text.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class Fre
{
       public static void main(String[ ] args) throws IOException
       {
              DataInputStream dis=new DataInputStream(System.in);
              String str=dis.readLine();
              String temp;
              StringTokenizer st=new StringTokenizer(str);
              int n=st.countTokens( );
              String a[ ]=new String[n];
              int i=0,count=0;
              while(st.hasMoreTokens())
              {
                     a[i]=st.nextToken();
                     i++;
              }
              for(int x=1;x<n;x++)
              {
                     for(int y=0;y<n-x;y++)
                     {
                            if(a[y].compareTo(a[y+1])>0)
                            {
                                    temp=a[y];
                                    a[y]=a[y+1];
                                    a[y+1]=temp;
                            }
                     }


                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
}
          System.out.println("the sorted string are:");
          for(i=0;i<n;i++)
          {
                 System.out.println(a[i]+" ");
          }
          System.out.println();
          for(i=0;i<n;i++)
          {count=1;
                 if(i<n-1)
                 {

                       while(a[i].compareTo(a[i+1])==0)
                       {
                             count++;
                             i++;
                             if(i>=n-1)
                             {
                                    System.out.println(a[i]+" "+count);
                                    System.exit(0);
                             }
                       }
                }
                System.out.println(a[i]+" "+count);

          }
     }
}


Output:




                                            WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Date: 06-01-2009
Week-4a)
Aim: Write a java program that reads a filename from user then displays information from
user then displays information about whether the file exists,whether file is readable,
whether file is writable the type of file and length of file in bytes.
Code:
import java.lang.*;
import java.io.*;
import java.util.*;
class FileOp
{
       public static void main(String arg[ ])throws IOException
       {
              File f=new File("Z:/week 3/Palindrome.java");
              System.out.println(f.getName());
              System.out.println(f.getPath());
              System.out.println(f.getName());
              System.out.println(f.canRead()?"Readable":"Not Readable");
              System.out.println(f.exists()?"Exist":"Non Exist");


                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
System.out.println(f.canWrite()?" " :" ");
             System.out.println(f.length()+"bytes");
      }
}

Output:




Week-4b)
Aim: Write a java program that reads a file and displays the file on the screen with a line
number before each line.
Code:
import java.util.*;
import java.io.*;
import java.lang.*;
class FileNo
{
       public static void main(String arg[ ])throws IOException
       {
              int linenum=0;
              String line;
              try{
                      File f=new File("Z:/f.txt ");
                      if(f.exists())
                      {
                              Scanner infile=new Scanner(f);



                                               WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
while(infile.hasNext())
                          {
                                  line=infile.nextLine();
                                  System.out.println(++linenum+"   "+line);
                          }
                          infile.close();
                   }
             }
             catch(Exception e)
             {
                   System.out.println(e);
             }
      }
}
Output:




Week-4c)
Aim: Write a java program that displays the number of characters,lines and words in atext
file
import java.lang.*;
import java.io.*;
class FileCount
{
       public static void main(String arg[])
       {
              int ccount=0,lcount=0,wcount=0;
              try
              {
                     FileInputStream f=new FileInputStream("Z:/week 3/Palindrome.java");
                     int i;
                     do{
                            i=f.read();
                            if(i!=-1)
                            {


                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
ccount++;
                               if(i=='n')
                                       lcount++;
                               if((char)i==' '||(char)i=='n')
                                       wcount++;
                         }
                       }while(i!=-1);
                  f.close();
                                 System.out.println("line count is "+lcount);
                                 System.out.println("Character count is "+ccount);
                                 System.out.println("word count is "+wcount);
                  }
            catch(Exception e)
            {
                  System.out.println(e);
            }
      }
}
Output:




Date:03-02-2009
Week-5a)i)
Aim: Write a java program that Implements stack ADT.
Code:
import java.lang.*;
import java.io.*;
import java.util.*;
interface Mystack
{
   int n=10;
   public void pop();
   public void push();
   public void peek();
   public void display();
}
class Stackimp implements Mystack
{


                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
int stack[]=new int[n];
 int top=-1;
 public void push()
 {
                 try{
                  DataInputStream dis=new DataInputStream(System.in);
                     if(top==(n-1))
                     {
                                 System.out.println("overflow");
                                 return;
                    }
                      else
                   {
                                System.out.println("enter element");
                                 int ele=Integer.parseInt(dis.readLine());
                                   stack[++top]=ele;
                    }
          }
          catch(Exception e)
          {
                   System.out.println("e");
          }
 }
 public void pop()
 {
         if(top<0)
        {
                  System.out.println("underflow");
                   return;
         }
          else
       {
                          int popper=stack[top];
                top--;
                  System.out.println("popped element" +popper);
       }
 }
 public void peek()
{
          if(top<0)
          {
                          System.out.println("underflow");
                           return:
              }
          else
          {


                                           WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
int popper=stack[top];
                           System.out.println("popped element" +popper);
                    }
      }
      public void display()
     {
              if(top<0)
                     {
                     System.out.println("empty");
                        return;
                 }
              else
              {
                             String str=" ";
                             for(int i=0;i<=top;i++)
                      str=str+" "+stack[i];
                       System.out.println("elements are"+str);
                     }
      }
 }
class Stackadt
{
           public static void main(String arg[])throws IOException
          {
                     DataInputStream dis=new DataInputStream(System.in);
                      Stackimp stk=new Stackimp();
                     int ch=0;
                     do{
                                    System.out.println("enter ur choice for 1.push 2.pop
                             3.peek 4.peek 5.display”);
                                     ch=Integer.parseInt(dis.readLine());
                                            switch(ch){
                                                  case 1:stk.push();
                                                   break;
                                                  case 2:stk.pop();
                                                   break;
                                                  case 3:stk.peek();
                                                   break;
                                                  case 4:stk.display();
                                                   break;
                                                  case 5:System.exit(0);
                                          }
                     }while(ch<=5);
         }
}
Output:


                                               WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-5a)ii)
Aim: Write a java program that evaluates the postfix expression
Code:
import java.lang.*;
import java.io.*;
import java.util.*;
class IntoPo
{
        public static void main(String arg[])throws IOException
        {
               Stack stk=new Stack();
                DataInputStream dis=new DataInputStream(System.in);
               char input;
               String output=" ";
               System.out.println("enter expresion");
               String exp=dis.readLine();


                                            WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
for(int pos=0;pos<exp.length();pos++)
          {
                 input=exp.charAt(pos);
                        switch(input)
                 {
                         case '+' :
                         case '-' :
                         case '*' :
                                case '/' :
                                        stk.push(input);
                                        break;
                                case ')' : char ch=((Character)stk.pop());
                                        output=output+ch;
                                          break;
                                case '(' : break;
                                        default : output=output+input;
                                          break;
                 }
          }
          System.out.println("result is"+output);
      }
}




Output:




                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
.




Week-5a)iii)
Aim:Write a java program that evaluates the postfix expression


                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
import java.lang.*;
import java.io.*;
import java.util.*;
class Evaluation
{
       static int dooperation(int fo,int so,char op)
       {
               int val=0;
               switch(op){
                             case '+' : val=fo+so;
                             break;
                             case '-' : val=fo-so;
                             break;
                               case '*' : val=fo*so;
                             break;
                               case '/' : val=fo/so;
                              break;
                         }
                 return val;
       }
       public static void main(String arg[])throws IOException
       {
               Stack stk=new Stack();
               DataInputStream dis=new DataInputStream(System.in);
               String str=dis.readLine();
               char ch;
               for(int pos=0;pos<str.length();pos++)
               {
                       ch=str.charAt(pos);
                       switch(ch){
                                     case '0' :
                                     case '1' :
                                     case '2' :
                                     case '3' :
                                     case '4' :
                                     case '5' :
                                     case '6' :
                                     case '7' :
                                     case '8' :
                                     case '9' :
                                              stk.push(new Integer((Character.digit(ch,10))));
                                              break;
                                     case '+':
                                     case '-':
                                     case '/':
                                     case '*':


                                                 WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
int fo=((Integer)stk.pop()).intValue();
                                          int so=((Integer)stk.pop()).intValue();
                                          int result=dooperation(fo,so,ch);
                                             stk.push(new Integer(result));
                                          break;
             }
     }
     System.out.println("result is" +stk.pop());
 }
}




Date: 10-02-2009
Week-6a)
Aim:Develop an applet that receives an integer in one text field, and computes as factorial
value and returns it in another text field,when the button named “Compute” is clicked


                                                   WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
import java.io.*;
import java.awt.*;
import java.applet.Applet;
/*<applet code="appletTest.class" height=100 width=500></applet>*/
public class appletTest extends Applet
{
       public void paint(Graphics g)
       {
              g.drawString("This is IT IInd Year IInd sem",50,60);
              setForeground(Color.blue);
       }
}

Output:




Week-6b)
Aim:Develop an applet that displays a simple message
Code:



                                            WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*<applet code="AddEvent.class" height=100 width=500></applet>*/
public class AddEvent extends Applet implements ActionListener
{
       TextField tf1;
       TextField tf2;
       Button b;
       Label l;
       public void init()
       {
              l=new Label("Enter the number & press the button");
              tf1=new TextField("",5);
              tf2=new TextField("",10);
              b=new Button("press me");
              add(l);
              add(tf1);
              add(tf2);
              add(b);
              b.addActionListener(this);
       }
       public void actionPerformed(ActionEvent ae)
       {
              String str=ae.getActionCommand();
              String str1;
              int fact=1;
              if(str=="press me")
              {
                     int n=Integer.parseInt(tf1.getText());
                     for(int i=1;i<=n;i++)
                            fact=fact*i;
                     str1=""+fact;
                     tf2.setText(str1);
              }
       }
}




Output:




                                            WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Date: 24-02-2009
Week-7)


                   WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Aim: Write a java program that works as a simple calculator.Use a grid layout to arrange
buttons for the digits +,-,*,/,% operations.Adda text field to display the result.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Calculator extends Applet implements ActionListener
{
       TextField t1;
       String a="",b;
       String oper="",s="",p="";
       int first=0,second=0,result=0;
       Panel p1;
       Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9;
       Button add,sub,mul,div,mod,res,space;
       public void init()
       {
               Panel p2,p3;
               p1=new Panel();
               p2=new Panel();
               p3=new Panel();
               t1=new TextField(a,20);
               p1.setLayout(new BorderLayout());
               p2.add(t1);
               b0=new Button("0");
               b1=new Button("1");
               b2=new Button("2");
               b3=new Button("3");
               b4=new Button("4");
               b5=new Button("5");
               b6=new Button("6");
               b7=new Button("7");
               b8=new Button("8");
               b9=new Button("9");
               add=new Button("+");
               sub=new Button("-");
               mul=new Button("*");
               div=new Button("/");
               mod=new Button("%");
               res=new Button("=");
               space=new Button("c");
               p3.setLayout(new GridLayout(4,4));
               b0.addActionListener(this);
               b1.addActionListener(this);
               b2.addActionListener(this);
               b3.addActionListener(this);
               b4.addActionListener(this);


                                              WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
b5.addActionListener(this);
            b6.addActionListener(this);
            b7.addActionListener(this);
            b8.addActionListener(this);
            b9.addActionListener(this);
            add.addActionListener(this);
            sub.addActionListener(this);
            mul.addActionListener(this);
            div.addActionListener(this);
            mod.addActionListener(this);
            res.addActionListener(this);
            space.addActionListener(this);
            p3.add(b0);
            p3.add(b1);
            p3.add(b2);
            p3.add(b3);
            p3.add(b4);
            p3.add(b5);
            p3.add(b6);
            p3.add(b7);
            p3.add(b8);
            p3.add(b9);
            p3.add(add);
            p3.add(sub);
            p3.add(mul);
            p3.add(div);
            p3.add(mod);
            p3.add(res);
            p3.add(space);
            p1.add(p2,BorderLayout.NORTH);
            p1.add(p3,BorderLayout.CENTER);
            add(p1);
       }
       public void actionPerformed(ActionEvent ae)
       {
              a=ae.getActionCommand();
              if(a=="0"||a=="1"||a=="2"||a=="3"||a=="4"||a=="5"||a=="6"||a=="7"||a=="8"||
a=="9")
              {
                     t1.setText(t1.getText()+a);
              }
              if(a=="+"||a=="-"||a=="*"||a=="/"||a=="%")
              {
                     first=Integer.parseInt(t1.getText());
                     oper=a;
                     t1.setText("");


                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
}
            if(a=="=")
            {
                   if(oper=="+")
                   result=first+Integer.parseInt(t1.getText());
                   if(oper=="-")
                   result=first-Integer.parseInt(t1.getText());
                   if(oper=="*")
                   result=first*Integer.parseInt(t1.getText());
                   if(oper=="/")
                   result=first/Integer.parseInt(t1.getText());
                   if(oper=="%")
                   result=first%Integer.parseInt(t1.getText());
                   t1.setText(result+"");
            }
            if(a=="c")
            t1.setText("");
      }
}
/*<applet code=Calculator width=200 height=200></applet>*/



Output:




Date: 10-02-2009



                                              WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-8
Aim: Write a java program for handling mouse events.
Code:
import java.io.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*<applet code=Mouse height=400 width=400></applet>*/
public class Mouse extends Applet implements MouseListener,MouseMotionListener
{
       String txt="";
       int x=10,y=30;
       public void init()
       {
              addMouseListener(this);
              addMouseMotionListener(this);
       }
       public void mouseClicked(MouseEvent me)
       {
              txt="Mouse Clicked";
              setForeground(Color.pink);
              repaint();
       }
       public void mouseEntered(MouseEvent me)
       {
              txt="Mouse Entered";
              repaint();
       }
       public void mouseExited(MouseEvent me)
       {
              txt="Mouse Exited";
              setForeground(Color.blue);
              repaint();
       }
       public void mousePressed(MouseEvent me)
       {
              txt="Mouse Pressed";
              setForeground(Color.blue);
              repaint();
       }
       public void mouseMoved(MouseEvent me)
       {
              txt="Mouse Moved";
              setForeground(Color.red);
              repaint();
       }


                                           WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
public void mouseDragged(MouseEvent me)
      {
             txt="Mouse Dragged";
             setForeground(Color.green);
             repaint();
      }
      public void mouseReleased(MouseEvent me)
      {
             txt="Mouse Released";
             setForeground(Color.yellow);
             repaint();
      }
      public void paint(Graphics g)
      {
             g.drawString(txt,30,40);
             showStatus("Mouse events Handling");
      }
}

Output:




Date: 24-02-2009


                                            WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-9a)
Aim: Write a java program that creates three threads.First thread displays”Good Morning”
every one second,the second thread displays “Hello” every two seconds and the third thread
displays “Welcome” every three seconds.
Code:
class Frst implements Runnable
{
       Thread t;
       Frst()
       {
               t=new Thread(this);
               System.out.println("Good Morning");
               t.start();
       }
       public void run()
       {
               for(int i=0;i<10;i++)
               {
                     System.out.println("Good Morning"+i);
                     try{
                               t.sleep(1000);
                       }
                     catch(Exception e)
                     {
                          System.out.println(e);
                     }
               }
       }
}
class sec implements Runnable
{
        Thread t;
        sec()
        {
                t=new Thread(this);
                System.out.println("hello");
              t.start();
        }
        public void run()
        {
               for(int i=0;i<10;i++)
               {
                     System.out.println("hello"+i);
                     try{
                               t.sleep(2000);
                     }


                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
catch(Exception e)
                   {
                       System.out.println(e);
                   }
             }
        }
}
class third implements Runnable
{
        Thread t;
        third()
        {
                t=new Thread(this);
              System.out.println("welcome");
              t.start();
        }
        public void run()
        {
                for(int i=0;i<10;i++)
                {
                      System.out.println("welcome"+i);
                        try{
                                t.sleep(3000);
                }
                      catch(Exception e)
                      {
                           System.out.println(e);
                      }
            }
       }
}
public class Multithread
{
        public static void main(String arg[])
        {
                  new Frst();
                  new sec();
                  new third();
        }
}




                                                WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Output:




Week-9b)


           WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Aim: Write a java program that correctly implements producer consumer problem using the
concept of inter thread communication.
Code:
import java.lang.*;
import java.lang.Thread;
class Q
{
       int n;
       boolean valueSet=false;
       synchronized int get()
       {
              if(!valueSet)
              try{
                      wait();
              }
              catch(InterruptedException e)
              {
                      System.out.println("InterruptedException catch");
              }
              System.out.println("got:"+n);
              valueSet=false;
              notify();
              return n;
       }
       synchronized void put(int n)
       {
              if(valueSet)
              try{
                      wait();
              }
              catch(InterruptedException e)
              {
                      System.out.println("InterruptedException catch");
              }
              this.n=n;
              valueSet=true;
              System.out.println("put:"+n);
              notify();
       }
}

class Producer implements Runnable
{
       Q q;
       Producer(Q q)
       {


                                            WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
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 PCFixed
{
       public static void main(String args[])
       {
              Q q=new Q();
              new Producer(q);
              new Consumer(q);
       }
}




Output:


                                              WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Date: 03-03-2009


                   WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-10 )
Aim: Write a program that creates a user interface to perform integer divisions.The user
enters two numbers int the textfields,Num1 and Num2.The divison of Num1 and Num2 is
displayed in the Result field when the Divide button is clicked.If Num1 or Num2 were not an
integer,the program would throw a NumberFormatException.If Num2 were Zero,the program
would throw an ArithmeticException Display the exception in a message dialog box.
Code:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
/*<applet code="AddEvent.class" height=100 width=500></applet>*/
public class AddEvent extends Applet implements ActionListener
{
       TextField tf1;
       TextField tf2;
       Button b;
       TextField tf3;
       Label l;
       public void init()
       {
              l=new Label("enter the numbers and press divide button");
              tf1=new TextField("",5);
              tf2=new TextField("",5);
              tf3=new TextField("",5);
              b=new Button("Divide");
              add(l);
              add(tf1);
              add(tf2);
              add(b);
              add(tf3);
              b.addActionListener(this);
       }
       public void actionPerformed(ActionEvent ae)
       {
              if(ae.getActionCommand()=="Divide")
              {
                     try{
                            int n1=Integer.parseInt(tf1.getText());
                            int n2=Integer.parseInt(tf2.getText());
                            int n=n1/n2;
                            tf3.setText(""+n);
                     }
                     catch(ArithmeticException e1)
                     {
                            JOptionPane.showMessageDialog(null,"Arthimetic Exception");


                                             WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
}
                   catch(NumberFormatException e2)
                   {
                         JOptionPane.showMessageDialog(null,"NumberFormatException");
                   }
            }
      }
}

Output:




Date: 03-03-2009
Week-11)


                                           WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Aim: Write a java program that implements a simple client/server application. The client
sends a data to a server. The server receives the data uses it to produce a result, and then
sends the result back to the client. The client displays the result on the console .For Ex: The
data sent from the client is the radius of a circle ,and the result produced by the server is
the area of the circle,(Use java.net)
Code:
import java.io.*;
import java.net.*;
class Client
{
       public static void main(String ar[])throws Exception
       {
              Socket s=new Socket(InetAddress.getLocalHost(),10000);
              System.out.println("enter the radius of the circle ");
              DataInputStream dis=new DataInputStream(System.in);
              int n=Integer.parseInt(dis.readLine());
              PrintStream ps=new PrintStream(s.getOutputStream());
              ps.println(n);
              DataInputStream dis1=new DataInputStream(s.getInputStream());
              System.out.println("area of the circle from server:"+dis1.readLine());
       }
}

import java.io.*;
import java.net.*;
class Server
{
       public static void main(String ar[])throws Exception
       {
              ServerSocket ss=new ServerSocket(10000);
              Socket s=ss.accept();
              DataInputStream dis=new DataInputStream(s.getInputStream());
              int n=Integer.parseInt(dis.readLine());
              PrintStream ps=new PrintStream(s.getOutputStream());
              ps.println(3.14*n*n);
       }
}




Output:



                                               WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Date: 10-03-2009
Week-12a)


                   WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Aim: Write a java program that stimulates a traffic light. The program lets the user select
one of three lights: red, yellow, or green. When a radio button is selected, the light is
turned on, and only one light can be on at a time No light is on when the program starts.
Code:
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 Red,Green,Yellow;
       CheckboxGroup cbg;
       public void init()
       {
              cbg=new CheckboxGroup();
              Red=new Checkbox("RED",cbg,false);
              Green=new Checkbox("GREEN",cbg,false);
              Yellow=new Checkbox("YELLOW",cbg,false);
              add(Red);
              add(Yellow);
              add(Green);
              Red.addItemListener(this);
              Green.addItemListener(this);
              Yellow.addItemListener(this);
       }
       public void itemStateChanged(ItemEvent ie)
       {
              repaint();
       }
       public void paint(Graphics g)
       {
              //g.drawOval(10,10,50,50);
              if(cbg.getSelectedCheckbox().getLabel()=="RED")
              {
                     g.setColor(Color.red);
                     g.fillOval(10,10,50,50);
              }
              if(cbg.getSelectedCheckbox().getLabel()=="YELLOW")
              {
                     g.setColor(Color.yellow);
                     g.fillOval(10,10,50,50);
              }

             if(cbg.getSelectedCheckbox().getLabel()=="GREEN")
             {


                                              WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
g.setColor(Color.green);
                g.fillOval(10,10,50,50);
            }

     }
}

Output:




Week-12b)


                                           WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Aim: Write a java program that allows the user to draw lines,rectangles and ovals.
Code:
import java.awt.*;
import java.applet.*;
public class Draw extends Applet
{
       public void paint(Graphics g)
       {
              g.setColor(Color.BLUE);
              g.drawLine(3,4,10,23);
              g.drawOval(195,100,90,55);
              g.drawRect(100,40,90,5);
              g.drawRoundRect(140,30,90,90,60,30);
       }
}
/*<applet code="Draw.class" width=300 height=300></applet>*/

Output:




Date: 17-03-2009


                                              WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-13a)
Aim: Write a java program to create an abstract class named Shape that contains an empty
method name numberOfSides().Provide three classes named Trapezoid,Traingle and Hexagon
such that each of the classes extends the class Shape. Each one of the classes contains only
the method numberOfSides() that shows the number of sides in the given geometrical
figures.
Code:
import java.lang.*;
abstract class Shape
{
       abstract void numberOfSides();

}
class Traingle extends Shape
{
       public void numberOfSides()
       {
              System.out.println("three");
       }
}
class Trapezoid extends Shape
{
       public void numberOfSides()
       {
              System.out.println("four");
       }
}
class Hexagon extends Shape
{
       public void numberOfSides()
       {
              System.out.println("six");
       }
}
public class Sides
{
       public static void main(String arg[])
       {
              Traingle T=new Traingle();
              Trapezoid Ta=new Trapezoid();
              Hexagon H=new Hexagon();
              T.numberOfSides();
              Ta.numberOfSides();
              H.numberOfSides();




                                               WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Output:




          WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
Week-13b)
Aim: Suppose that a table named Table.txt is stored in a text file. The first line in the file is
the header, and the remaining lines corresponding to rows in the table. The elements are
separated by commas. Write a java program to display the tabe using JTable Component.
Code:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
public class JTableEx extends JPanel
{
       public JTableEx()
       {
              super(new GridLayout(1, 0));
              File file = new File("I:/Table.txt");
              FileInputStream fis = null;
              BufferedInputStream bis = null;
              DataInputStream dis = null;
              String initData[] = new String[100];
              String[] columnNames = null;
              Object[][] data = null;
              int rows = 0;
              try
              {
                      fis = new FileInputStream(file);
                      bis = new BufferedInputStream(fis);
                      dis = new DataInputStream(bis);
                      while (dis.available() != 0)
                      {
                              initData[rows++] = dis.readLine();
                      }
                      StringTokenizer st = new StringTokenizer(initData[0],",");
                      columnNames = new String[st.countTokens()];
                      data = new Object[rows - 1][st.countTokens()];
                      for (int i = 0; i < rows; i++)
                      {
                              if (i != 0)
                              {
                                       int k = 0;
                                       StringTokenizer st1 = new StringTokenizer(initData[i],",");
                                       while (st1.hasMoreTokens())
                                       {
                                              data[i - 1][k++] = st1.nextToken();
                                       }
                              }
                              else


                                                WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
{
                           int j = 0;
                           while (st.hasMoreTokens())
                           {
                                   columnNames[j++] = st.nextToken();
                           }
                   }
            }
            fis.close();
            bis.close();
            dis.close();
      }
      catch (FileNotFoundException e)
      {
             e.printStackTrace();
      }
      catch (IOException e)
      {
             e.printStackTrace();
      }
      final JTable table = new JTable(data, columnNames);
      table.setPreferredScrollableViewportSize(new Dimension(500, 100));
      //table.setFillsViewportHeight(true);
      JScrollPane scrollPane = new JScrollPane(table);
      add(scrollPane);
}

private static void createAndShowGUI()
{
       JFrame frame = new JFrame("SimpleTableDemo");
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       JTableEx newContentPane = new JTableEx();
       newContentPane.setOpaque(true);
       frame.setContentPane(newContentPane);
       frame.pack();
       frame.setVisible(true);
}
public static void main(String[] args)
{
       javax.swing.SwingUtilities.invokeLater(new Runnable()
       {
              public void run()
              {
                     createAndShowGUI();
              }
       });


                                       WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
}
}
Output:




          WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR

Contenu connexe

Tendances

Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
Adan Hubahib
 

Tendances (20)

Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Strings in c
Strings in cStrings in c
Strings in c
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
String c
String cString c
String c
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
String in java
String in javaString in java
String in java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Pointers
PointersPointers
Pointers
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 

En vedette

Java simple programs
Java simple programsJava simple programs
Java simple programs
VEERA RAGAVAN
 
Advance java practicalty bscit sem5
Advance java practicalty bscit sem5Advance java practicalty bscit sem5
Advance java practicalty bscit sem5
ashish singh
 
Java collections
Java collectionsJava collections
Java collections
Amar Kutwal
 
Java Collections Framework
Java  Collections  FrameworkJava  Collections  Framework
Java Collections Framework
guestd8c458
 

En vedette (17)

Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Advance java practicalty bscit sem5
Advance java practicalty bscit sem5Advance java practicalty bscit sem5
Advance java practicalty bscit sem5
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programs
 
Java codes
Java codesJava codes
Java codes
 
Suresh Gyan Vihar University Distance Education Prospectus
Suresh Gyan Vihar University Distance Education ProspectusSuresh Gyan Vihar University Distance Education Prospectus
Suresh Gyan Vihar University Distance Education Prospectus
 
Tybsc it sem5 advanced java_practical_soln_downloadable
Tybsc it sem5 advanced java_practical_soln_downloadableTybsc it sem5 advanced java_practical_soln_downloadable
Tybsc it sem5 advanced java_practical_soln_downloadable
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 Certifications
 
Java: Collections
Java: CollectionsJava: Collections
Java: Collections
 
java collections
java collectionsjava collections
java collections
 
Java collections
Java collectionsJava collections
Java collections
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Event management 2nd Lecture in sports facilities
Event management 2nd Lecture in sports facilitiesEvent management 2nd Lecture in sports facilities
Event management 2nd Lecture in sports facilities
 
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conferenceJava Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Java Collections Framework
Java  Collections  FrameworkJava  Collections  Framework
Java Collections Framework
 

Similaire à Java Simple Programs

WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
MaruMengesha
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
anupamfootwear
 
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
eyewatchsystems
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
MaruMengesha
 

Similaire à Java Simple Programs (20)

Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Java practical
Java practicalJava practical
Java practical
 
Programs of java
Programs of javaPrograms of java
Programs of java
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_17-Feb-2021_L8-...
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
 
.net progrmming part2
.net progrmming part2.net progrmming part2
.net progrmming part2
 
informatics practices practical file
informatics practices practical fileinformatics practices practical file
informatics practices practical file
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
 
Presentation1 computer shaan
Presentation1 computer shaanPresentation1 computer shaan
Presentation1 computer shaan
 
Network security
Network securityNetwork security
Network security
 
java program assigment -2
java program assigment -2java program assigment -2
java program assigment -2
 
Java binary subtraction
Java binary subtractionJava binary subtraction
Java binary subtraction
 
Computer java programs
Computer java programsComputer java programs
Computer java programs
 
C programs
C programsC programs
C programs
 
QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
 

Plus de Upender Upr (7)

Dynamic cache management technique
Dynamic cache management techniqueDynamic cache management technique
Dynamic cache management technique
 
Grid computing Seminar PPT
Grid computing Seminar PPTGrid computing Seminar PPT
Grid computing Seminar PPT
 
Sniffer for the mobile phones
Sniffer for the mobile phonesSniffer for the mobile phones
Sniffer for the mobile phones
 
Internet access via cable tv network seminar byupender
Internet access via cable tv network seminar byupenderInternet access via cable tv network seminar byupender
Internet access via cable tv network seminar byupender
 
Internet access via cable tv network ppt
Internet access via cable tv network pptInternet access via cable tv network ppt
Internet access via cable tv network ppt
 
Internet access via cable tv network ppt
Internet access via cable tv network pptInternet access via cable tv network ppt
Internet access via cable tv network ppt
 
OOP Principles
OOP PrinciplesOOP Principles
OOP Principles
 

Dernier

Dernier (20)

latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

Java Simple Programs

  • 1. Date: 16-12-2008 Week-1a) Aim: Write a java program that print all roots of equation of quadratic a,b,c will be supplied through keyboard Code: import java.lang.*; import java.math.*; class Quad { public static void main(String arg[]) { int a,b,c; a=Integer.parseInt(arg[0]); b=Integer.parseInt(arg[1]); c=Integer.parseInt(arg[2]); int delta=(b*b)-(4*a*c); if(delta<0) { System.out.println("roots are imaginary,no real values"); } else { double x1=(-b+Math.sqrt(delta))/(2*a); double x2=(-b-Math.sqrt(delta))/(2*a); System.out.println(x1+" "+x2); } } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 2. Week-1b) Aim: Write a java program that uses both recursive and non recursive functions to print the nth value in Fibonacci series. Code: import java.lang.*; class Fibo { public static void main(String arg[ ]) { int f,f1=0,f2=1,n; n=Integer.parseInt(arg [0]); System.out.println(f1); System.out.println(f2); for(int i=0;i<n-1;i++) { f=f1+f2; f1=f2; f2=f; System.out.println(f); } System.out.println("Fibonacci series using recursion"); for(int i=0;i<n;i++) System.out.println(fib(i)); } static int fib(int n) { if(n==0||n==1) return 1; else return fib(n-1)+fib(n-2); } } WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 3. Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 4. Date: 23-12-2008 Week-2a) Aim: Write a java program that prompts the user for an integer and then prints out all prime numbers upto the integer. Code: import java.lang.*; class Prime { public static void main(String arg[]) { int n,c,i,j; n=Integer.parseInt(arg[0]); System.out.println("prime numbers are"); for(i=1;i<=n;i++) { c=0; for(j=1;j<=i;j++) { if(i%j==0) c++; } if(c==2) System.out.println(" "+i); } } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 5. Week-2b) Aim: Write a java program to multiply two given matrices. Code: import java.lang.*; import java.io.*; class Matrix { public static void main(String arg[])throws IOException { DataInputStream dis=new DataInputStream(System.in); System.out.println("Enter The Row Size Of The First Matrix"); int r1=Integer.parseInt(dis.readLine()); System.out.println("Enter The Column Size Of The First Matrix"); int c1=Integer.parseInt(dis.readLine()); System.out.println("Enter The Row Size Of The Second Matrix"); int r2=Integer.parseInt(dis.readLine()); System.out.println("Enter The Column Size Of The Second Matrix"); int c2=Integer.parseInt(dis.readLine()); int a[][]=new int[r1][c1]; int b[][]=new int[r2][c2]; int c[][]=new int[r1][c2]; int i,j,k; System.out.println("Enter The Elements Into The First Matrix"); for(i=0;i<r1;i++) for(j=0;j<c1;j++) { a[i][j]=Integer.parseInt(dis.readLine()); } System.out.println("Enter The Elements Into The Second Matrix"); for(i=0;i<r2;i++) for(j=0;j<c2;j++) { b[i][j]=Integer.parseInt(dis.readLine()); } if(c1!=r2) System.out.println("Multiplication Is Not Possible"); else { for(i=0;i<r1;i++) { for(j=0;j<c1;j++) { c[i][j]=0; for(k=0;k<r2;k++) { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 6. c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } } for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { System.out.println(c[i][j]+" "); } System.out.println(" "); } } } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 7. Week-2c) Aim: Write a program that display each integer and sum of all integers using stringtokenizer. Code: import java.util.*; class Stringtoken { public static void main(String arg[]) { int sum=0; StringTokenizer sto=new StringTokenizer(arg[0],":"); System.out.println(sto.countTokens()); while(sto.hasMoreTokens()) { int a=Integer.parseInt(sto.nextToken()); sum=sum+a; System.out.println(a); } System.out.println("sum= "+sum); } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 8. Date: 30-12-2008 Week-3a) Aim: Write a java program that checks whether a given string is a palindrome or not.Ex:MADAM Code: import java.lang.*; import java.io.*; import java.util.*; class Palindrome { public static void main(String arg[ ]) throws IOException { DataInputStream dis=new DataInputStream(System.in); String word=dis.readLine( ); int flag=1; int left=0; int right=word.length( )-1; while(left<right) { if(word.charAt(left)!=word.charAt(right)) { flag=0; //break; } left++; right--;} if(flag==1) System.out.println("palindrome"); else System.out.println("not palindrome"); } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 9. Week-3b) Aim:Write a java program for sorting a given list of name in ascending order. Code: import java.lang.*; import java.io.*; import java.util.*; class Sort { public static void main(String arg[ ]) throws IOException { DataInputStream dis=new DataInputStream(System.in); System.out.println("enter the size"); int n=Integer.parseInt(dis.readLine()); String array[ ]=new String[n]; System.out.println("enter names"); for(int i=0;i<n;i++) { array[i]=dis.readLine(); } for(int i=0;i<n;i++) { for(int j=0;j<n-1;j++) { if(array[j].compareTo(array[j+i])>0) { String temp=array[j]; array [j]=array[j+1]; array[j+1]=temp; } } } System.out.println("the sorted strings are"); for(int i=0;i<n;i++) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 10. System.out.println(array[i]); } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 11. Week-3c) Aim: Write a java program to make frequency count of words in a given text. Code: import java.util.*; import java.lang.*; import java.io.*; class Fre { public static void main(String[ ] args) throws IOException { DataInputStream dis=new DataInputStream(System.in); String str=dis.readLine(); String temp; StringTokenizer st=new StringTokenizer(str); int n=st.countTokens( ); String a[ ]=new String[n]; int i=0,count=0; while(st.hasMoreTokens()) { a[i]=st.nextToken(); i++; } for(int x=1;x<n;x++) { for(int y=0;y<n-x;y++) { if(a[y].compareTo(a[y+1])>0) { temp=a[y]; a[y]=a[y+1]; a[y+1]=temp; } } WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 12. } System.out.println("the sorted string are:"); for(i=0;i<n;i++) { System.out.println(a[i]+" "); } System.out.println(); for(i=0;i<n;i++) {count=1; if(i<n-1) { while(a[i].compareTo(a[i+1])==0) { count++; i++; if(i>=n-1) { System.out.println(a[i]+" "+count); System.exit(0); } } } System.out.println(a[i]+" "+count); } } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 13. Date: 06-01-2009 Week-4a) Aim: Write a java program that reads a filename from user then displays information from user then displays information about whether the file exists,whether file is readable, whether file is writable the type of file and length of file in bytes. Code: import java.lang.*; import java.io.*; import java.util.*; class FileOp { public static void main(String arg[ ])throws IOException { File f=new File("Z:/week 3/Palindrome.java"); System.out.println(f.getName()); System.out.println(f.getPath()); System.out.println(f.getName()); System.out.println(f.canRead()?"Readable":"Not Readable"); System.out.println(f.exists()?"Exist":"Non Exist"); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 14. System.out.println(f.canWrite()?" " :" "); System.out.println(f.length()+"bytes"); } } Output: Week-4b) Aim: Write a java program that reads a file and displays the file on the screen with a line number before each line. Code: import java.util.*; import java.io.*; import java.lang.*; class FileNo { public static void main(String arg[ ])throws IOException { int linenum=0; String line; try{ File f=new File("Z:/f.txt "); if(f.exists()) { Scanner infile=new Scanner(f); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 15. while(infile.hasNext()) { line=infile.nextLine(); System.out.println(++linenum+" "+line); } infile.close(); } } catch(Exception e) { System.out.println(e); } } } Output: Week-4c) Aim: Write a java program that displays the number of characters,lines and words in atext file import java.lang.*; import java.io.*; class FileCount { public static void main(String arg[]) { int ccount=0,lcount=0,wcount=0; try { FileInputStream f=new FileInputStream("Z:/week 3/Palindrome.java"); int i; do{ i=f.read(); if(i!=-1) { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 16. ccount++; if(i=='n') lcount++; if((char)i==' '||(char)i=='n') wcount++; } }while(i!=-1); f.close(); System.out.println("line count is "+lcount); System.out.println("Character count is "+ccount); System.out.println("word count is "+wcount); } catch(Exception e) { System.out.println(e); } } } Output: Date:03-02-2009 Week-5a)i) Aim: Write a java program that Implements stack ADT. Code: import java.lang.*; import java.io.*; import java.util.*; interface Mystack { int n=10; public void pop(); public void push(); public void peek(); public void display(); } class Stackimp implements Mystack { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 17. int stack[]=new int[n]; int top=-1; public void push() { try{ DataInputStream dis=new DataInputStream(System.in); if(top==(n-1)) { System.out.println("overflow"); return; } else { System.out.println("enter element"); int ele=Integer.parseInt(dis.readLine()); stack[++top]=ele; } } catch(Exception e) { System.out.println("e"); } } public void pop() { if(top<0) { System.out.println("underflow"); return; } else { int popper=stack[top]; top--; System.out.println("popped element" +popper); } } public void peek() { if(top<0) { System.out.println("underflow"); return: } else { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 18. int popper=stack[top]; System.out.println("popped element" +popper); } } public void display() { if(top<0) { System.out.println("empty"); return; } else { String str=" "; for(int i=0;i<=top;i++) str=str+" "+stack[i]; System.out.println("elements are"+str); } } } class Stackadt { public static void main(String arg[])throws IOException { DataInputStream dis=new DataInputStream(System.in); Stackimp stk=new Stackimp(); int ch=0; do{ System.out.println("enter ur choice for 1.push 2.pop 3.peek 4.peek 5.display”); ch=Integer.parseInt(dis.readLine()); switch(ch){ case 1:stk.push(); break; case 2:stk.pop(); break; case 3:stk.peek(); break; case 4:stk.display(); break; case 5:System.exit(0); } }while(ch<=5); } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 19. Week-5a)ii) Aim: Write a java program that evaluates the postfix expression Code: import java.lang.*; import java.io.*; import java.util.*; class IntoPo { public static void main(String arg[])throws IOException { Stack stk=new Stack(); DataInputStream dis=new DataInputStream(System.in); char input; String output=" "; System.out.println("enter expresion"); String exp=dis.readLine(); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 20. for(int pos=0;pos<exp.length();pos++) { input=exp.charAt(pos); switch(input) { case '+' : case '-' : case '*' : case '/' : stk.push(input); break; case ')' : char ch=((Character)stk.pop()); output=output+ch; break; case '(' : break; default : output=output+input; break; } } System.out.println("result is"+output); } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 21. . Week-5a)iii) Aim:Write a java program that evaluates the postfix expression WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 22. import java.lang.*; import java.io.*; import java.util.*; class Evaluation { static int dooperation(int fo,int so,char op) { int val=0; switch(op){ case '+' : val=fo+so; break; case '-' : val=fo-so; break; case '*' : val=fo*so; break; case '/' : val=fo/so; break; } return val; } public static void main(String arg[])throws IOException { Stack stk=new Stack(); DataInputStream dis=new DataInputStream(System.in); String str=dis.readLine(); char ch; for(int pos=0;pos<str.length();pos++) { ch=str.charAt(pos); switch(ch){ case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : stk.push(new Integer((Character.digit(ch,10)))); break; case '+': case '-': case '/': case '*': WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 23. int fo=((Integer)stk.pop()).intValue(); int so=((Integer)stk.pop()).intValue(); int result=dooperation(fo,so,ch); stk.push(new Integer(result)); break; } } System.out.println("result is" +stk.pop()); } } Date: 10-02-2009 Week-6a) Aim:Develop an applet that receives an integer in one text field, and computes as factorial value and returns it in another text field,when the button named “Compute” is clicked WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 24. import java.io.*; import java.awt.*; import java.applet.Applet; /*<applet code="appletTest.class" height=100 width=500></applet>*/ public class appletTest extends Applet { public void paint(Graphics g) { g.drawString("This is IT IInd Year IInd sem",50,60); setForeground(Color.blue); } } Output: Week-6b) Aim:Develop an applet that displays a simple message Code: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 25. import java.awt.*; import java.awt.event.*; import java.applet.Applet; /*<applet code="AddEvent.class" height=100 width=500></applet>*/ public class AddEvent extends Applet implements ActionListener { TextField tf1; TextField tf2; Button b; Label l; public void init() { l=new Label("Enter the number & press the button"); tf1=new TextField("",5); tf2=new TextField("",10); b=new Button("press me"); add(l); add(tf1); add(tf2); add(b); b.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str=ae.getActionCommand(); String str1; int fact=1; if(str=="press me") { int n=Integer.parseInt(tf1.getText()); for(int i=1;i<=n;i++) fact=fact*i; str1=""+fact; tf2.setText(str1); } } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 26. Date: 24-02-2009 Week-7) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 27. Aim: Write a java program that works as a simple calculator.Use a grid layout to arrange buttons for the digits +,-,*,/,% operations.Adda text field to display the result. import java.awt.*; import java.applet.*; import java.awt.event.*; public class Calculator extends Applet implements ActionListener { TextField t1; String a="",b; String oper="",s="",p=""; int first=0,second=0,result=0; Panel p1; Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9; Button add,sub,mul,div,mod,res,space; public void init() { Panel p2,p3; p1=new Panel(); p2=new Panel(); p3=new Panel(); t1=new TextField(a,20); p1.setLayout(new BorderLayout()); p2.add(t1); b0=new Button("0"); b1=new Button("1"); b2=new Button("2"); b3=new Button("3"); b4=new Button("4"); b5=new Button("5"); b6=new Button("6"); b7=new Button("7"); b8=new Button("8"); b9=new Button("9"); add=new Button("+"); sub=new Button("-"); mul=new Button("*"); div=new Button("/"); mod=new Button("%"); res=new Button("="); space=new Button("c"); p3.setLayout(new GridLayout(4,4)); b0.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 28. b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); add.addActionListener(this); sub.addActionListener(this); mul.addActionListener(this); div.addActionListener(this); mod.addActionListener(this); res.addActionListener(this); space.addActionListener(this); p3.add(b0); p3.add(b1); p3.add(b2); p3.add(b3); p3.add(b4); p3.add(b5); p3.add(b6); p3.add(b7); p3.add(b8); p3.add(b9); p3.add(add); p3.add(sub); p3.add(mul); p3.add(div); p3.add(mod); p3.add(res); p3.add(space); p1.add(p2,BorderLayout.NORTH); p1.add(p3,BorderLayout.CENTER); add(p1); } public void actionPerformed(ActionEvent ae) { a=ae.getActionCommand(); if(a=="0"||a=="1"||a=="2"||a=="3"||a=="4"||a=="5"||a=="6"||a=="7"||a=="8"|| a=="9") { t1.setText(t1.getText()+a); } if(a=="+"||a=="-"||a=="*"||a=="/"||a=="%") { first=Integer.parseInt(t1.getText()); oper=a; t1.setText(""); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 29. } if(a=="=") { if(oper=="+") result=first+Integer.parseInt(t1.getText()); if(oper=="-") result=first-Integer.parseInt(t1.getText()); if(oper=="*") result=first*Integer.parseInt(t1.getText()); if(oper=="/") result=first/Integer.parseInt(t1.getText()); if(oper=="%") result=first%Integer.parseInt(t1.getText()); t1.setText(result+""); } if(a=="c") t1.setText(""); } } /*<applet code=Calculator width=200 height=200></applet>*/ Output: Date: 10-02-2009 WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 30. Week-8 Aim: Write a java program for handling mouse events. Code: import java.io.*; import java.applet.Applet; import java.awt.*; import java.awt.event.*; /*<applet code=Mouse height=400 width=400></applet>*/ public class Mouse extends Applet implements MouseListener,MouseMotionListener { String txt=""; int x=10,y=30; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { txt="Mouse Clicked"; setForeground(Color.pink); repaint(); } public void mouseEntered(MouseEvent me) { txt="Mouse Entered"; repaint(); } public void mouseExited(MouseEvent me) { txt="Mouse Exited"; setForeground(Color.blue); repaint(); } public void mousePressed(MouseEvent me) { txt="Mouse Pressed"; setForeground(Color.blue); repaint(); } public void mouseMoved(MouseEvent me) { txt="Mouse Moved"; setForeground(Color.red); repaint(); } WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 31. public void mouseDragged(MouseEvent me) { txt="Mouse Dragged"; setForeground(Color.green); repaint(); } public void mouseReleased(MouseEvent me) { txt="Mouse Released"; setForeground(Color.yellow); repaint(); } public void paint(Graphics g) { g.drawString(txt,30,40); showStatus("Mouse events Handling"); } } Output: Date: 24-02-2009 WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 32. Week-9a) Aim: Write a java program that creates three threads.First thread displays”Good Morning” every one second,the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every three seconds. Code: class Frst implements Runnable { Thread t; Frst() { t=new Thread(this); System.out.println("Good Morning"); t.start(); } public void run() { for(int i=0;i<10;i++) { System.out.println("Good Morning"+i); try{ t.sleep(1000); } catch(Exception e) { System.out.println(e); } } } } class sec implements Runnable { Thread t; sec() { t=new Thread(this); System.out.println("hello"); t.start(); } public void run() { for(int i=0;i<10;i++) { System.out.println("hello"+i); try{ t.sleep(2000); } WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 33. catch(Exception e) { System.out.println(e); } } } } class third implements Runnable { Thread t; third() { t=new Thread(this); System.out.println("welcome"); t.start(); } public void run() { for(int i=0;i<10;i++) { System.out.println("welcome"+i); try{ t.sleep(3000); } catch(Exception e) { System.out.println(e); } } } } public class Multithread { public static void main(String arg[]) { new Frst(); new sec(); new third(); } } WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 34. Output: Week-9b) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 35. Aim: Write a java program that correctly implements producer consumer problem using the concept of inter thread communication. Code: import java.lang.*; import java.lang.Thread; class Q { int n; boolean valueSet=false; synchronized int get() { if(!valueSet) try{ wait(); } catch(InterruptedException e) { System.out.println("InterruptedException catch"); } System.out.println("got:"+n); valueSet=false; notify(); return n; } synchronized void put(int n) { if(valueSet) try{ wait(); } catch(InterruptedException e) { System.out.println("InterruptedException catch"); } this.n=n; valueSet=true; System.out.println("put:"+n); notify(); } } class Producer implements Runnable { Q q; Producer(Q q) { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 36. 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 PCFixed { public static void main(String args[]) { Q q=new Q(); new Producer(q); new Consumer(q); } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 37. Date: 03-03-2009 WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 38. Week-10 ) Aim: Write a program that creates a user interface to perform integer divisions.The user enters two numbers int the textfields,Num1 and Num2.The divison of Num1 and Num2 is displayed in the Result field when the Divide button is clicked.If Num1 or Num2 were not an integer,the program would throw a NumberFormatException.If Num2 were Zero,the program would throw an ArithmeticException Display the exception in a message dialog box. Code: import java.awt.*; import java.awt.event.*; import java.applet.Applet; import javax.swing.*; /*<applet code="AddEvent.class" height=100 width=500></applet>*/ public class AddEvent extends Applet implements ActionListener { TextField tf1; TextField tf2; Button b; TextField tf3; Label l; public void init() { l=new Label("enter the numbers and press divide button"); tf1=new TextField("",5); tf2=new TextField("",5); tf3=new TextField("",5); b=new Button("Divide"); add(l); add(tf1); add(tf2); add(b); add(tf3); b.addActionListener(this); } public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand()=="Divide") { try{ int n1=Integer.parseInt(tf1.getText()); int n2=Integer.parseInt(tf2.getText()); int n=n1/n2; tf3.setText(""+n); } catch(ArithmeticException e1) { JOptionPane.showMessageDialog(null,"Arthimetic Exception"); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 39. } catch(NumberFormatException e2) { JOptionPane.showMessageDialog(null,"NumberFormatException"); } } } } Output: Date: 03-03-2009 Week-11) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 40. Aim: Write a java program that implements a simple client/server application. The client sends a data to a server. The server receives the data uses it to produce a result, and then sends the result back to the client. The client displays the result on the console .For Ex: The data sent from the client is the radius of a circle ,and the result produced by the server is the area of the circle,(Use java.net) Code: import java.io.*; import java.net.*; class Client { public static void main(String ar[])throws Exception { Socket s=new Socket(InetAddress.getLocalHost(),10000); System.out.println("enter the radius of the circle "); DataInputStream dis=new DataInputStream(System.in); int n=Integer.parseInt(dis.readLine()); PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(n); DataInputStream dis1=new DataInputStream(s.getInputStream()); System.out.println("area of the circle from server:"+dis1.readLine()); } } import java.io.*; import java.net.*; class Server { public static void main(String ar[])throws Exception { ServerSocket ss=new ServerSocket(10000); Socket s=ss.accept(); DataInputStream dis=new DataInputStream(s.getInputStream()); int n=Integer.parseInt(dis.readLine()); PrintStream ps=new PrintStream(s.getOutputStream()); ps.println(3.14*n*n); } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 41. Date: 10-03-2009 Week-12a) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 42. Aim: Write a java program that stimulates a traffic light. The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time No light is on when the program starts. Code: 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 Red,Green,Yellow; CheckboxGroup cbg; public void init() { cbg=new CheckboxGroup(); Red=new Checkbox("RED",cbg,false); Green=new Checkbox("GREEN",cbg,false); Yellow=new Checkbox("YELLOW",cbg,false); add(Red); add(Yellow); add(Green); Red.addItemListener(this); Green.addItemListener(this); Yellow.addItemListener(this); } public void itemStateChanged(ItemEvent ie) { repaint(); } public void paint(Graphics g) { //g.drawOval(10,10,50,50); if(cbg.getSelectedCheckbox().getLabel()=="RED") { g.setColor(Color.red); g.fillOval(10,10,50,50); } if(cbg.getSelectedCheckbox().getLabel()=="YELLOW") { g.setColor(Color.yellow); g.fillOval(10,10,50,50); } if(cbg.getSelectedCheckbox().getLabel()=="GREEN") { WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 43. g.setColor(Color.green); g.fillOval(10,10,50,50); } } } Output: Week-12b) WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 44. Aim: Write a java program that allows the user to draw lines,rectangles and ovals. Code: import java.awt.*; import java.applet.*; public class Draw extends Applet { public void paint(Graphics g) { g.setColor(Color.BLUE); g.drawLine(3,4,10,23); g.drawOval(195,100,90,55); g.drawRect(100,40,90,5); g.drawRoundRect(140,30,90,90,60,30); } } /*<applet code="Draw.class" width=300 height=300></applet>*/ Output: Date: 17-03-2009 WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 45. Week-13a) Aim: Write a java program to create an abstract class named Shape that contains an empty method name numberOfSides().Provide three classes named Trapezoid,Traingle and Hexagon such that each of the classes extends the class Shape. Each one of the classes contains only the method numberOfSides() that shows the number of sides in the given geometrical figures. Code: import java.lang.*; abstract class Shape { abstract void numberOfSides(); } class Traingle extends Shape { public void numberOfSides() { System.out.println("three"); } } class Trapezoid extends Shape { public void numberOfSides() { System.out.println("four"); } } class Hexagon extends Shape { public void numberOfSides() { System.out.println("six"); } } public class Sides { public static void main(String arg[]) { Traingle T=new Traingle(); Trapezoid Ta=new Trapezoid(); Hexagon H=new Hexagon(); T.numberOfSides(); Ta.numberOfSides(); H.numberOfSides(); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 46. Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 47. Week-13b) Aim: Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the remaining lines corresponding to rows in the table. The elements are separated by commas. Write a java program to display the tabe using JTable Component. Code: import javax.swing.*; import java.awt.*; import java.io.*; import java.util.*; public class JTableEx extends JPanel { public JTableEx() { super(new GridLayout(1, 0)); File file = new File("I:/Table.txt"); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; String initData[] = new String[100]; String[] columnNames = null; Object[][] data = null; int rows = 0; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); while (dis.available() != 0) { initData[rows++] = dis.readLine(); } StringTokenizer st = new StringTokenizer(initData[0],","); columnNames = new String[st.countTokens()]; data = new Object[rows - 1][st.countTokens()]; for (int i = 0; i < rows; i++) { if (i != 0) { int k = 0; StringTokenizer st1 = new StringTokenizer(initData[i],","); while (st1.hasMoreTokens()) { data[i - 1][k++] = st1.nextToken(); } } else WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 48. { int j = 0; while (st.hasMoreTokens()) { columnNames[j++] = st.nextToken(); } } } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } final JTable table = new JTable(data, columnNames); table.setPreferredScrollableViewportSize(new Dimension(500, 100)); //table.setFillsViewportHeight(true); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane); } private static void createAndShowGUI() { JFrame frame = new JFrame("SimpleTableDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTableEx newContentPane = new JTableEx(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR
  • 49. } } Output: WWW.ABHIROX.CO.CC, WWW.ABHIROX.CO.NR