Coding Lab - TechOnTechnology

Java Program to Demonstrates Multi Threadng Using Prime and Fibonacci Number Concepts.





Write a multi-threaded Java program to print all numbers below 100,000 that are both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below 100,000 and writes them into an array. Design another thread that generates fibonacci numbers and writes them to another array. The main thread should read both the arrays to identify numbers common to both. 


import java.io.*;
import java.io.PipedWriter;
import java.io.PipedReader;
class fibonacci extends Thread
{
            PipedWriter fw=new PipedWriter();
            public PipedWriter getwrite()
            {
                        return fw;
            }
            public void run()
            {
                        super.run();
                        fibo();
            }
            int f(int n)
            {
                        if(n<2)
                                    return n;
                                    else
                                                return f(n-1)+f(n-2);
            }
            void fibo()
            {
                        for(int i=2,fibv=0;(fibv=f(i))<100000;i++)
                        {
                                    try{
                                  
                                    fw.write(fibv);
                                    }
                                    catch(IOException e){
                                    }
                        }
            }
}
class receiver extends Thread
{
            PipedReader fibr,primer;
            public receiver(fibonacci fib,prime pr)throws IOException
            {
                        fibr=new PipedReader(fib.getwrite());
                        primer=new PipedReader(pr.getwrite());
            }
            public void run()
            {
                        int p=0,f=0;
                        try{
                      
                        p=primer.read();
                        f=fibr.read();
                        }
                        catch(IOException e)
                        {
                        }
                        while(true)
                        {
                                    try
                                                {
                                  
                                    if(p==f){
                                  
                                                System.out.println ("Match:"+p);
                                                p=primer.read();
                                                f=fibr.read();
                                    }
                                    else if(f<p)
                                                f=fibr.read();
                                                else
                                                            p=primer.read();
                        }catch(IOException e)
                        {System.exit(-1);
                        }
                        }
                      
            }
}
class prime extends Thread
{
            PipedWriter pw=new PipedWriter();
            public PipedWriter getwrite()
            {
                        return pw;
            }
            public void run()
            {
                        super.run();
                        prim();
            }
            public void prim()
            {
                        for(int i=2;i<100000;i++)
                        {
                                    if(isprime(i))
                                    {
                                                try{
                                                            pw.write(i);
                                                }
                                                catch(IOException e){
                                                }
                                    }
                        }
            }
            boolean isprime(int n)
            {
                        boolean p=true;
                        int s=(int)Math.sqrt(n);
                        for(int i=2;i<=s;i++)
                        {
                                    if(n%i==0)
                                                p=false;
                        }
                        return p;
            }
}
class fibprime
{
            public static void main (String[] args)throws IOException {
                        fibonacci fi=new fibonacci();
                        prime pri=new prime();
                        receiver r=new receiver(fi,pri);
                        fi.start();
                        pri.start();
                        r.start();
                      
}
}

Java GUI program to handle the various keyboard events for printable characters.




// Demonstrate some virtual key codes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
public class KeyEvents extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
requestFocus(); // request input focus
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}

HTML File Code to load Applet.
Make Sure that Java Configured Properly.

<html>
<body>
<applet code=KeyEvents.class width=300 height=200>
</applet>
</body>
</html>

Java GUI program to handle the various mouse events.




// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}



HTML Code to Load Applet.
Make Sure that Java Configured properly.


<html>
<body>
<applet code=MouseEvents.class width=300 height=200>
</applet>
</body>
</html>

Java Program to implement Various Operations Using Student Concept.

 



Create a class Student with attributes roll no, name, age and course. Initialize values through parameterized constructor. If age of student is not in  between 15 and 21 then generate user-defined exception “AgeNotWithinRangeException”. If name contains numbers or special symbols raise exception “NameNotValidException”. Define the two exception classes.  

 
import java.io.*;

class AgeOutOfRangeException extends Exception{}

class NameNotValidException extends Exception{}

class Student
{
    int RollNo, Age,j,k=-1;
    String Name,Course;
    char ch[]={'!','@','#','$','%','^','&','*'};
    Student(int rno, String name, int age, String course)
    {
    try
    {
        RollNo = rno;
        Name = name;
        Age = age;
        Course = course;
        if(Age<15 || Age>21)
        throw new AgeOutOfRangeException();
        for(int i=0,j=0; i<Name.length() && j<ch.length ; i++,j++)
        if(Character.isDigit(Name.charAt(i))||(k!=Name.indexOf(ch[j])))
        throw new NameNotValidException();
    }
    catch(AgeOutOfRangeException e)
    {
        System.out.println("\nAGE NOT WITHIN RANGE !!!");
        System.exit(0);
    }
    catch(NameNotValidException e)
    {
        System.out.println("\nNAME IS NOT VALID !!!");
        System.exit(0);
    }
    }
    public void printData()
    {
        System.out.println("\nROLL NO :"+RollNo+"\n"+
        "NAME :"+Name+"\n"+
        "AGE :"+Age+"\n"+
        "COURSE  :"+Course);
    }
}
class StudentException
{
    public static void main(String args[]) throws Exception
    {
       
        DataInputStream in=new DataInputStream(System.in);

        System.out.print("\nENTER ROLL NO :");
        int rno=Integer.parseInt(in.readLine());
       
        System.out.print("ENTER NAME :");
        String sn=in.readLine();
       
        System.out.print("ENTER AGE :");
        int age=Integer.parseInt(in.readLine());
       
        System.out.print("ENTER COURSE :");
        String cn=in.readLine();
       
        Student s1 = new Student(rno,sn,age,cn);
       
        s1.printData();
    }
}a

Java program to implement Producer Consumer Program.




class Q
{
    int n;
    boolean valueset=false;
       synchronized int get()
       {
       if(!valueset)
       try
       {
          wait();
       }
      catch(InterruptedException e){
        System.out.println("Interrupted Exception cought !! ");
        }
        System.out.println("Get:"+n);
        valueset=false;
        notify();
        return n;
    }
    synchronized void put(int n)
    {
       if(valueset)
       try
       {
          wait();
       }
       catch(InterruptedException e){
                  System.out.println("Interrupt");
        }
     this.n=n;
     valueset=true;
    System.out.println("Put:"+n);
    notify();
    }

 }

class Producer implements Runnable
{
    Q q;
    Producer(Q q)
    {
        this.q=q;
        new Thread(this,"Producer").start();
    }
   public void run()
    {
        int i=0;
        while(true)
        {
         q.put(i++);
        }
    }
 }

class Consumer implements Runnable
{
   Q q;
   Consumer(Q q)
   {
        this.q=q;
        new Thread(this,"Consumer").start();
   }
   public void run()
   {
      while(true)
      {
          q.get();
      }
   }
}
class Producerconsumer
 {
    public static void main(String args[])
        {
          Q q=new Q();
        new Producer(q);
        new Consumer(q);
        System.out.println("Press Control plus c to stop");
        }
}

Java Program to do Following : Define a class called Time. Implement the following methods Add T1 and T2 ,Display the Time.




import java.io.*;
import java.lang.*;
class timedemo
{
    int hour,min,sec;
    timedemo(int x,int y,int z)
    {
        hour=x;
        min=y;
        sec=z;
    }
}
class time
{
public static timedemo add(timedemo t1,timedemo t2)
{
    int hour=t1.hour+t2.hour;
    int min=t1.min+t2.min;
    int sec=t1.sec+t2.sec;
    if ( sec>= 60)
    {
        sec=sec-60;
        min=min+1;
    }
    if(min>=60)
    {
        min=min-60;
        hour=hour+1;
    }
    if(hour>=12)
    {
        hour=hour-12;
    }
timedemo t3=new timedemo(hour,min,sec);
return (t3);
}
public static void display(timedemo t)
{
    System.out.println("TIME : "+t.hour+"hours :"+t.min+"minutes :"+t.sec+"seconds");
}
public static void main(String args[]) throws IOException
{
    int h,m,s;
    DataInputStream in=new DataInputStream(System.in);
   
        System.out.println("\nENTER TIME : ");
        System.out.println("\nENTER Ist [ T1 ] TIME [ HH:MM:SS ] : ");
        System.out.print("Hours : ");
        h = Integer.parseInt(in.readLine());
        System.out.print("Minutes : ");
        m = Integer.parseInt(in.readLine());
        System.out.print("Seconds : ");
        s = Integer.parseInt(in.readLine());
       
        timedemo t1=new timedemo(h,m,s);
       
        System.out.println("\nENTER IInd [ T2 ] TIME [ HH:MM:SS ] : ");
        System.out.print("Hours : ");
        h = Integer.parseInt(in.readLine());
        System.out.print("Minutes : ");
        m = Integer.parseInt(in.readLine());
        System.out.print("Seconds : ");
        s = Integer.parseInt(in.readLine());

        timedemo t2=new timedemo(h,m,s);
   
        timedemo t3;
        t3=add(t1,t2);    // calling add method to add two time
        System.out.println("\nIst ");display(t1);      // calling display method
        System.out.println("\nIInd ");display(t2);
        System.out.println("\nI+II ");display(t3);
}
}

Java recursive program to compute the determinant of a matrix.




import java.io.*;
import java.lang.*;
class Matrixdet{

public static double determinent(int b[][],int m)
    {
        int c[][]=new int[m][m];

        int i,j,k;
        double sum=0;
        if(m==1) { sum=b[0][0];  }
        else if(m==2)
        {
            sum=(( b[0][0]*b[1][1] ) - ( b[0][1]*b[1][0] ));
        }
        else
        {
            for(int p=0;p<m;p++)
            {
              int h=0;k=0;
              for(i=1;i<m;i++)
              {
                for(j=0;j<m;j++)
                    {
                     if(j==p)
                     continue;
                     c[h][k]=b[i][j];
                     k++;
                     if(k==m-1)
                      {
                         h++;
                         k=0;
                      }
                    }
              }
            sum=sum+b[0][p]*Math.pow((-1),p)*determinent(c,m-1);
            }
        }
        return sum;
    }

        public static void main(String[] args) throws IOException{
            DataInputStream in=new DataInputStream(System.in);
            System.out.println("\nMATRIX  :");
            System.out.print("\nENTER THE ORDER OF THE MATRIX YOU HAVE : ");
            int order=Integer.parseInt(in.readLine());
           
            int[][] A = new int[order][order];
           
            System.out.println("\nENTER ELEMENTS OF MATRIX : ");
            for (int i=0 ; i < order ; i++)
            for  (int j=0 ; j < order ; j++)
            {
            A[i][j] = Integer.parseInt(in.readLine());
            }
           
            System.out.println("MATRIX : ");
                    for (int i=0 ; i < order ; i++)
                    {       System.out.println();
                            for  (int j=0 ; j < order ; j++)
                              {
                            System.out.print(A[i][j]+" ");
                              }
                    }
            System.out.println();
            System.out.println("\nDETERMINENT OF MATRIX : "+ determinent(A,order));
        }
}

Name

Email *

Message *