Thursday, January 9, 2020

Exercise - 11 (Threads continuity)

Exercise - 11 (Threads continuity)

a).Write a JAVA program Producer Consumer Problem

import java.util.LinkedList; 
public class Threadexample 

public static void main(String[] args) throws InterruptedException 

final PC pc = new PC(); 
Thread t1 = new Thread(new Runnable() 

@Override
public void run() 

try

pc.produce(); 

catch(InterruptedException e) 

e.printStackTrace(); 


}); 
Thread t2 = new Thread(new Runnable() 

@Override
public void run() 

try

pc.consume(); 

catch(InterruptedException e) 

e.printStackTrace(); 


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

public static class PC 

LinkedList<Integer> list = new LinkedList<>(); 
int capacity = 4; 
public void produce() throws InterruptedException 

int value = 0; 
while (true) 

synchronized (this) 

while (list.size()==capacity) 
wait(); 
System.out.println("Producer produced-"+ value); 
list.add(value++); 
notify(); 
Thread.sleep(1000); 



public void consume() throws InterruptedException 

while (true) 

synchronized (this) 

while (list.size()==0) 
wait(); 
int val = list.removeFirst(); 
System.out.println("Consumer consumed-"+ val); 
notify(); 
Thread.sleep(1000); 





}

b).Write a case study on thread Synchronization after solving the above producer consumer
problem

In computing, the producer-consumer problem (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, which share a common, fixed-size buffer used as a queue.
  • The producer’s job is to generate data, put it into the buffer, and start again.
  • At the same time, the consumer is consuming the data (i.e. removing it from the buffer), one piece at a time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer won’t try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer.
Implementation of Producer Consumer Class
  • LinkedList list – to store list of jobs in queue.
  • A Variable Capacity – to check for if the list is full or not
  • A mechanism to control the insertion and extraction from this list so that we do not insert into list if it is full or remove from it if it is empty.
In PC class (A class that has both produce and consume methods), a linked list of jobs and a capacity of the list is added to check that producer does not produce if the list is full.

In Producer class, the value is initialized as 0.Also, we have an infinite outer loop to insert values in the list. Inside this loop, we have a synchronized block so that only a producer or a consumer thread runs at a time.An inner loop is there before adding the jobs to list that checks if the job list is full, the producer thread gives up the intrinsic lock on PC and goes on the waiting state.If the list is empty, the control passes to below the loop and it adds a value in the list.

In the Consumer class, we again have an infinite loop to extract a value from the list.Inside, we also have an inner loop which checks if the list is empty.If it is empty then we make the consumer thread give up the lock on PC and passes the control to producer thread for producing more jobs. If the list is not empty, we go round the loop and removes an item from the list.


In both the methods, we use notify at the end of all statements. The reason is simple, once you have something in list, you can have the consumer thread consume it, or if you have consumed something, you can have the producer produce something. sleep() at the end of both methods just make the output of program run in step wise manner and not display everything all at once so that you can see what actually is happening in the program.


Wednesday, January 1, 2020

Exercise – 10 (Threads)

Exercise – 10 (Threads)

a). Write a JAVA program that creates threads by extending Thread class . First thread display
"Good Morning " every 1 sec, the second thread displays "Hello"every 2 seconds and the
third display Welcome" every 3 seconds , (Repeat the same by implementing Runnable)

import java.io.*;
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{ }
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{ }
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{ }
}
}
class Threadmsgs
{
    public static void main(String args[])
    {
        A t1=new A();
        B t2=new B();
        C t3=new C();
        t1.start();
        t2.start();
        t3.start();
    }
}

b). Write a program illustrating isAlive and join ()

public class AliveJoin extends Thread 
public void run() 
System.out.println("ABDUL KALAM "); 
try 
Thread.sleep(300); 
catch (InterruptedException ie) 
{ } 
System.out.println("SUBHASH CHANDRABOSH "); 
public static void main(String[] args) 
AliveJoin c1 = new AliveJoin(); 
AliveJoin c2 = new AliveJoin(); 
c1.start(); 
c2.start();
System.out.println(c1.isAlive());
System.out.println(c2.isAlive());
try 
c1.join(); // Waiting for c1 to finish 
catch (InterruptedException ie) 
{ } 
}

c). Write a Program illustrating Daemon Threads.

import java.io.*;
public class DaemonThread extends Thread 
public DaemonThread(String name)
super(name); 
public void run() 
{  
if(Thread.currentThread().isDaemon()) 
{  
            System.out.println(getName() + " is Daemon thread");  
}  
else
{  
System.out.println(getName() + " is User thread");  
}  
}  
public static void main(String[] args) 
{  

        DaemonThread t1 = new DaemonThread("t1"); 
        DaemonThread t2 = new DaemonThread("t2"); 
        DaemonThread t3 = new DaemonThread("t3");
        t1.setDaemon(true);                
        t1.start();  
        t2.start(); 
        t3.setDaemon(true);  
        t3.start();         
    }  
}

Monday, December 30, 2019

Exercise – 9 (User Defined Exception)

Exercise – 9 (User Defined Exception)

a). Write a JAVA program for creation of illustrating throw


public class TestThrow1
{  
    void validate()
    {  
try
{
                System.out.println("Inside of the try block");
throw new ArithmeticException("Not  valid,throwing Exception");
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
    }  
   public static void main(String args[])
   {  
      TestThrow1 t=new TestThrow1();
t.validate();
   }  
}  

b). Write a JAVA program for creation of Illustrating finally

class TestFinallyBlock
{  
  public static void main(String args[])
  {  
  try
  {  
   int data=25/5;  
   System.out.println(data);  
   }  
  catch(NullPointerException e)
  {
System.out.println(e);
  }  
  finally
  {
System.out.println("finally block is defaultly  executed");
   }  
  System.out.println("rest of the code...");  
 }  


c). Write a JAVA program for creation of Java Built-in Exceptions



import java.util.Scanner;
class Demo
{
  public static void main(String args[])
{
ArrayIndex_Demo  obj=new ArrayIndex_Demo();
obj.display();
}
}
class ArrayIndex_Demo
        void display()
        {
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter the element you want to insert:");
        int n=sc.nextInt();
        System.out.print("Enter the index of the array:");
        try
       
            int a[] = new int[5]; 
            int i=sc.nextInt();
            a[i]=n;
       
        catch (ArrayIndexOutOfBoundsException e)
       
            System.out.println("Array Index is Out Of Bounds"); 
        }
        } 

d).Write a JAVA program for creation of User Defined Exception


import java.lang.Exception;
class Myexception extends Exception 
{
private static double bal[]={10000.00,12000.00,5600.50,999.00,1100.55};
Myexception(String str)
{
super(str);
}
public static void main(String args[])
{
try
{
for(int i=0;i<=5;i++)
{
System.out.println(bal[i]);
if(bal[i]<1000)
{
Myexception me=new Myexception("This is user defined Error.");
throw me;
}
}
}
catch(Myexception me)
{
me.printStackTrace();
}
}
}

Monday, December 23, 2019

Exercise – 8 (Runtime Polymorphism)

Exercise – 8 (Runtime Polymorphism) 

a). Write a JAVA program that implements Runtime polymorphism 


import java.util.Scanner;
class One
{
int a,b;
void sum()
{
Scanner s=new Scanner(System.in);
System.out.print("Enter  a and b values:");
a=s.nextInt();
b=s.nextInt();
int sum=a+b;
System.out.println("Sum of two numbers in the class 'One' is:"+sum);

}

}
class Two extends One
{
int a=90,b=67;
int add;
void sum()
{
add=a+b;
System.out.println("Sum of the numbers in the class 'Two' is:"+add);
}

}
class Poly
{
public static void main(String args[])
{
One obj=new One();
obj.sum();
One t=new Two();
t.sum();

}

}


b). Write a Case study on run time polymorphism, inheritance that implements in above problem



Polymorphism:-
            Polymorphism is the process of performing the single task in different ways. Polymorphism is the Greek word . In which  ‘poly‘  means many and   morphs  means  forms. It means  many forms .
Polymorphism is classified into two types they are-
1.      Static  or Compile time Polymorphism
2.      Dynamic  or Run time  Polymorphism
Runtime Polymorphism:-
            Runtime Polymorphism is also called as Dynamic polymorphism. It is the process of calling the Overriding methods in runtime rather than In compile time.
In  this process  the  overriding methods are called with reference of super class.
Explanation:-
            In the above program we use single inheritance two achieve the runtime polymorphism in our example.
We use two classes here. We call the base class with the reference of  the super class.
 We create different objects to the two classes and call the both base   class   as well as super class with reference of super class only.
So, Runtime polymorphism is achieved here.
           
           

Exercise - 7 (Exception)

Exercise - 7 (Exception) 

a).Write a JAVA program that describes exception handling mechanism



import java.util.Scanner;
class Exception_handle
{
public static void main(String args[])
{
Exception ex=new Exception();
}
}
class Exception
{
Exception()
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a and b values:");
int a=s.nextInt();
int b=s.nextInt();
try
{
int c=a/b;
System.out.print(c);
}
catch(ArithmeticException ae)
{
System.out.println("Arthmatic Exception occured");
}
}

}

b).Write a JAVA program Illustrating Multiple catch clauses 



import java.util.Scanner;
class Multiple_catch
{
public static void main(String args[])
{
Handle h=new Handle();

}
}
class Handle
{
Handle()
{
Scanner sc=new Scanner(System.in);
String str="The world is runs throgh software industry";
String str2=null;
System.out.print("Enter the index of 1st string where you want to retrive the charecter:");
int n1=sc.nextInt();
System.out.print("Enter the index of 2st string where you want to retrive the charecter:");
int n2=sc.nextInt();
try
{

char c=str.charAt(n1);
System.out.println("Charecter at the index of "+n1+" 1st string is:"+c);
char ch=str2.charAt(n2);
System.out.println(ch);

}
catch(StringIndexOutOfBoundsException sib)
{
System.out.println("String index out of range");
}
catch(NullPointerException np)
{
System.out.println("Null pointer exception");
}
}

}

Thursday, December 19, 2019

Exercise - 6 (Inheritance - Continued)

Exercise - 6 (Inheritance - Continued)


a). Write a JAVA program give example for “super” keyword.

//Write a program to implement 'super' keyword

class One
{
protected int a;
One(int i)
{
this.a=i;
}
void display()
{
System.out.println("Super class method:a="+a);
}
}
class Two extends One
{
protected int a;
        Two(int i,int j)
  {
  super(i);
    a=j;
  }
  void display()
  {
  super.display();
  System.out.println("Sub class method:a="+a);
 
  }
}
class Super1
{
  public static void main(String args[])
  {
  Two t=new Two(9,6);
  t.display();

}
}

b). Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?

mport java.util.Scanner;
interface Base1
{
final double pie=3.14;
        void area();
}
class Base2
{
protected int r;
public void getdata()
{
Scanner s=new Scanner(System.in);
System.out.print("Enter the radius of the Circle:");
r=s.nextInt();
}
}
class Derived extends Base2 implements Base1
{
double area;
public void area()
{
area=pie*r*r;
System.out.println("Area of the Circle is:"+area);
}
}
class Inheritance
{
public static void main(String args[])
{
Derived d=new Derived();
                d.getdata();
d.area();
}
}

Multiple inheritance is achieved through interfaces

Exercise - 5 (Inheritance)

Exercise - 5 (Inheritance)

a). Write a JAVA program to implement Single Inheritance

import java.util.Scanner;
class Add
{
  protected int a,b,sum;
  void add()
  {
    Scanner s=new Scanner(System.in);
    System.out.println("Enter two values");
    a=s.nextInt();
    b=s.nextInt();
    sum=a+b;
    System.out.println("The sum of the given numbers is:"+sum);
  }
}
class Mul extends Add
{
  int mul;
  void mul()
  {
    mul=a*b;
    System.out.println("The product of the given numbers is:"+mul);
  }
}
class Calculation
{
  public static void main(String args[])
  {
    Mul m=new Mul();
    m.add();
    m.mul(); 
  }
}

b). Write a JAVA program to implement multi level Inheritance

import java.util.Scanner;
class calculator
{
  public static void  main(String args[])
  {
  System.out.println("Enter the values:");
  Scanner s=new Scanner(System.in);
  int a=s.nextInt();
  int b=s.nextInt();
  Product pr=new Product();
  pr.Addition(a,b);
  pr.Substraction();
  pr.Mul();
  }
}
class Add
{
  protected int p,q;
  public void Addition(int x,int y)
  {
    p=x;
    q=y;
  int r=p+q;
  System.out.println("Inside of the class 'Addition' ......");
  System.out.println("The sum is:"+r);
}
}
class Sub extends Add
{
int diff;
public void Substraction()
{

  int diff=p-q;
  System.out.println("Inside of the class Sub.........");
  System.out.println("Difference is:"+diff);
}
}
class Product extends Sub
{
int prod;
public void  Mul()
{
  int prod=p*q;
  System.out.println("Inside of the class Product.......");
  System.out.println("Product is:"+prod);
}
}

c). Write a java program for abstract class to find areas of different shapes

import java.util.Scanner;
abstract class Areas
{
  public void display()
  {
  System.out.println("Inside of the abstract class....");
  }
  abstract void area();
}
class Rectangle extends Areas
{
  int base=10;
  int height=20;
  public void area()
  {
  int area=base*height;
  System.out.println("Area of the rectangle is:"+area);
  }
}
class Square extends Areas
{
  int base=15;
  public void area()
  {
  int area1=base*base;
  System.out.println("Area of the Square is:"+area1);
  }
}
class Triangle extends Areas
{
  int base=5;
  int height=15;
  public void area()
  {
  int area2=(base*height)/2;
  System.out.println("Area of the Triangle is:"+area2);
  }
}
class Geometry
{
  public static void main(String args[])
  {
  Rectangle r=new Rectangle();
  Square s=new Square();
  Triangle t=new Triangle();
  r.display();
  r.area();
  s.area();
  t.area();
  }
}

JAVA PROGRAMMING ASSIGNMENT 2 QUESTIONS

SIR C R REDDY COLLEGE OF ENGINEERING, ELURU DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING JAVA PROGRAMMING ASSIGNMENT 2 QUESTIONS ...