Monday, March 14, 2022

R20- JAVA PROGRAMMING LAB SOLUTIONS

JAVA PROGRAMMING LAB 

R-20 Syllabus for CSE, JNTUK w. e. f. 2020 – 21 

Exercise - 1   (Basics) 

a) Write a JAVA program to display default value of all primitive data type of JAVA 

b) Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate the discriminate D and basing on value of D, describe the nature of root.  

c) Five Bikers Compete in a race such that they drive at a constant speed which may or may not be the same as the other. To qualify the race, the speed of a racer must be more than the average speed of all 5 racers. Take as input the speed of each racer and print back the speed of qualifying racers.  

Exercise - 2 (Operations, Expressions, Control-flow, Strings) 

a) Write a JAVA program to search for an element in a given list of elements using binary search mechanism. 

b) Write a JAVA program to sort for an element in a given list of elements using bubble sort 

c) Write a JAVA program to sort for an element in a given list of elements using merge sort. 

d) Write a JAVA program using StringBuffer to delete, remove character.  

Exercise - 3 (Class, Objects) 

a) Write a JAVA program to implement class mechanism. Create a class, methods and invoke them inside main method. 

b) Write a JAVA program to implement constructor.

 Exercise - 4 (Methods) 

a) Write a JAVA program to implement constructor overloading. 

b) Write a JAVA program implement method overloading. 

Exercise - 5 (Inheritance) 

a) Write a JAVA program to implement Single Inheritance  

b) Write a JAVA program to implement multi level Inheritance  

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

Exercise - 6 (Inheritance - Continued) 

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

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

Exercise - 7 (Exception) 

a) Write a JAVA program that describes exception handling mechanism  

b) Write a JAVA program Illustrating Multiple catch clauses  

Exercise – 8 (Runtime Polymorphism) 

a) Write a JAVA program that implements Runtime polymorphism  

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

Exercise – 9 (User defined Exception) 

a) Write a JAVA program for creation of Illustrating throw b) Write a JAVA program for creation of Illustrating finally  c) Write a JAVA program for creation of Java Built-in Exceptions  d) d)Write a JAVA program for creation of User Defined Exception 

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)   

b) Write a program illustrating isAlive and join () 

c) Write a Program illustrating Daemon Threads.   

Exercise - 11 (Threads continuity) 

a) Write a JAVA program Producer Consumer Problem 

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

Exercise – 12 (Packages)  

a) Write a JAVA program illustrate class path 

b) Write a case study on including in class path in your os environment of your package.  

c) Write a JAVA program that import and use the defined your package in the previous Problem 

Exercise - 13 (Applet) 

a) Write a JAVA program to paint like paint brush in applet. 

b) Write a JAVA program to display analog clock using Applet. c) Write a JAVA program to create different shapes and fill colors using Applet. 

Exercise - 14 (Event Handling) 

a) Write a JAVA program that display the x and y position of the cursor movement using Mouse. 

b) Write a JAVA program that identifies key-up key-down event user entering text in a Applet.   


--------------------------------------------------------------------------------------------------------------------------

Lab solutions 

Exercise - 1 (Basics)


a). Write a JAVA program to display default value of all primitive data type of JAVA


import java.io.*;

class Primitivevalues

{

 static boolean B1;

 static byte T1; 

 static int I1; 

 static float F1;

 static double D1; 

 static char C1;

 public static void main(String args[])

 {


  System.out.println("static  variable  Default values for BYTE:"+T1);

  System.out.println("static  variable  Default values for INT:"+I1);

  System.out.println("static  variable  Default values for FLOAT:"+F1);

  System.out.println("static  variable  Default values for DOUBLE:"+D1);

  System.out.println("static  variable  Default values for CHAR:"+C1);

  System.out.println("static  variable  Default values for BOOLEAN:"+B1);

 }

}


b). Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate

the discriminate D and basing on value of D, describe the nature of root.




import java.io.*;

import static java.lang.Math.sqrt;

import java.util.*;

class Roots

{


  void m1(int a,int b,int c)

 {

  double value=(Math.pow(b,2.0)-4*a*c);

   double discriminant=(double)Math.sqrt(value);

  if(value>0)

  {

   System.out.println("Roots are real numbers");

   double root1=(discriminant-b)/(2*a);

      double root2=(-b-discriminant)/(2*a);

      System.out.println("FirstRoot"+root1+"\nSecond Root"+root2);

  }

  else if(value==0)

  {

   double root1=(discriminant-b)/(2*a);

   System.out.println("Polynomial has one Root"+root1);

  }

  if(value<0)

  {

   System.out.println("Roots are imaginary numbers");

   System.out.println((-b+"i"+"+"+(-1*value))+"/"+(2*a));

   System.out.println((-b+"i"+"-"+(-1*value))+"/"+(2*a));

  }



 }

 public static void main(String [] args)

  {

   int a,b,c;

   System.out.print("Enter a,b,c values:");

   Scanner br=new Scanner(System.in);

    a=br.nextInt();

    b=br.nextInt();

    c=br.nextInt();

    new Roots().m1(a,b,c);

  }

}


c). Five Bikers Compete in a race such that they drive at a constant speed which may or may

not be the same as the other. To qualify the race, the speed of a racer must be more than the

average speed of all 5 racers. Take as input the speed of each racer and print back the speed

of qualifying racers.


import java.io.*;

import java.util.*;

class Race

{

 public static void main(String [] args)

 {

  int R[]=new int[20];

  float avg;

  int sum=0;

  System.out.println("Enter Speed of 5 members");

  Scanner sc=new Scanner(System.in);

  for(int j=1;j<=5;j++)

  {

   R[j]=sc.nextInt();

   sum+=R[j];

  }

  avg=sum/5;    

  for(int i=1;i<=5;i++)

  {

   if(avg<R[i])

   {

    System.out.println("QualifiedRaceris:"+i+"with value="+R[i]);

   }

  }

 }

}


Exercise - 2 (Operations, Expressions, Control-flow, Strings)



a). Write a JAVA program to search for an element in a given list of elements using binary

search mechanism.


import java.util.Scanner;

import java.io.*;

class Binarys

{

  public static void main(String args[])

   {

      int c,first,last,middle,n,search,array[];

      boolean status=false;

       Scanner s=new Scanner(System.in);

       System.out.println("Enter number of elements:");

       n=s.nextInt();

       array=new int[n];

        System.out.println("Enter"+n+"integer:");

      for(c=0;c<n;c++) 

        array[c]=s.nextInt();

     for (int i = 0; i < array.length; i++)

         {

            for (int j = i + 1; j < array.length; j++)

            {

                if (array[i] > array[j])

                {

                  int  temp = array[i];

                    array[i] = array[j];

                    array[j] = temp;

                }

            }

      }

        System.out.println("Enter value to find:");

        search=s.nextInt();

        first=0;

        last=n-1;

        middle=(first+last)/2;

    for(int i=0;i<n;i++)

     {

        if(first<=last)

         {

             if(array[middle]<search)

                  first=middle+1;

             else if(array[middle]==search)

              {

                  status=true;

              }

           else

            {

                last=middle-1;

            }

                 middle=(first+last)/2;

         }

    }

       if(status==true)

       {

           System.out.println(search+"found at location"+(middle+1));

       }

     else

         System.out.println(search+"is not found in the list");

   }

}

       

b). Write a JAVA program to sort for an element in a given list of elements using bubble sort.


import java.util.Scanner;

public class Bubblesort

{

 public static void main(String[] args)

 {

         Scanner s=new Scanner(System.in);

         System.out.println("enter the size of the array:");

         int size=s.nextInt();

         System.out.println("enter the values into the array:");

         int arr[]=new int[size];

         for(int i=0;i<size;i++)

         {

              arr[i]=s.nextInt();

         }

         sorting(arr);

     }

     public static void sorting(int arr[])

     {

         int n=arr.length;

         int temp=0;

         for(int i=0;i<n;i++)

         {

           for(int j=1;j<(n-i);j++)

          {

            if(arr[j-1]>arr[j])

            {

               temp=arr[j-1];

               arr[j-1]=arr[j];

               arr[j]=temp;

            }

          }

        }

         System.out.println("the sorted arraty is:");

         for(int i=0;i<arr.length;i++)

         {

            System.out.print(arr[i]+"\t");

         }

     }

}



(c). Write a JAVA program to sort for an element in a given list of elements using merge sort.


import java.util.Scanner;

class merge

{

 public static void main(String args[])

 {

   Scanner s=new Scanner(System.in);

   System.out.println("enter size of the array:");

   int size=s.nextInt();

   int arr[]=new int[size];

   System.out.println("enter elements into the array:");

   for(int i=0;i<size;i++)

   {

     arr[i]=s.nextInt();

   }

  int start=0;

  int end=size-1;

  sort(arr,start,end);

  System.out.println("the sorted array is:");

  for(int j=0;j<size;j++)

  {

    System.out.print(arr[j]+"\t");

  }

 }

 public static void sort(int arr[],int start,int end)

 {

   if(start<end)

   {

     int middle=(start+end)/2;

     sort(arr,start,middle);

     sort(arr,middle+1,end);

     merge(arr,start,middle,end);

   }

 }

 public static void merge(int arr[],int start,int middle,int end)

 {

   int n1 = middle -start + 1;

    int n2 = end - middle;

    int L[] = new int [n1];

    int R[] = new int [n2];

    for (int i=0; i<n1; ++i)

    {

        L[i] = arr[start + i];

     }

     for (int j=0; j<n2; ++j)

     {

         R[j] = arr[middle + 1+ j];

      }

      int i = 0, j = 0;

      int k = start;

      while (i < n1 && j < n2)

      {

          if (L[i] <= R[j])

          {

             arr[k] = L[i];

              i++;

          }

         else

         {

           arr[k] = R[j];

           j++;

          }

          k++;

     }

     while (i < n1)

     {

         arr[k] = L[i];

          i++;

          k++;

      }

      while (j < n2)

      {

        arr[k] = R[j];

         j++;

         k++;

      }


 }

}




(d) Write a JAVA program using StringBufferto delete, remove character.


import java.util.Scanner;

import java.lang.*;

class stringbuffer

{

  public static void main(String args[])

  {

     Scanner s=new Scanner(System.in);

     System.out.println("enter a string you like:");

     String str=s.nextLine();

     StringBuffer b=new StringBuffer(str);

     System.out.println("enter the index you want to delete from:");

      int i1=s.nextInt();

     System.out.println("to:");

     int i2=s.nextInt();

     b.delete(i1,i2);

     System.out.println("after deletion the new buffer is:"+b);

  }

}


Exercise - 3 (Class, Objects)


a). Write a JAVA program to implement class mechanism. – Create a class, methods and

invoke them inside main method.

import static java.lang.System.*;


class Student{

int rno=420;

String name="Raju";

String _class="CSE-2";

public void display() {

out.println(name);

out.println(rno);

out.println(_class);

}

}

public class Details {


public static void main(String[] args) {

Student   s=new Student();

s.display();

}


}

b). Write a JAVA program to implement constructor.

import java.util.Scanner;
class Sports_person
{
int height=164;
  int weight=62;
  // constructor method
  public Sports_person()
  {
       Scanner in=new Scanner(System.in);
      System.out.println("Enter Height?");
      height=in.nextInt();
      System.out.println("Enter Weight?");
      weight=in.nextInt();
      System.out.println("Height of the sports person is:"+height+"CM");
      System.out.println("Weight of the sports person is:"+weight+"KG");
  }
}

public class Olimpics {
public static void main(String[] args) {
Sports_person s=new Sports_person();
}

}


Exercise - 4

a). Write a JAVA program to implement constructor overloading.

class Student{

int sno;

String sname;

float fee;

public Student()

{

}

public Student(int sn,String snm,float f)

{

sno=sn;

sname=snm;

fee=f;

}

public void display()

{

System.out.println("Sno   : "+sno);

System.out.println("Sname : "+sname);

System.out.println("Fees  : "+fee);

}

}

public class ConsOvl {

public static void main(String[] args) {

// overloading zero arg constructor

Student s=new Student();

s.display();

//overloading parameterized constructor

Student s1=new Student(100, "Raj",500);

s1.display();

//anonymous object

new Student().display();

}


}

output:

Sno   : 0

Sname : null

Fees  : 0.0

Sno   : 100

Sname : Raj

Fees  : 500.0

Sno   : 0

Sname : null

Fees  : 0.0

b). Write a JAVA program implement method overloading.

package Ovltest;


class Student{

int sno;

String sname;

float fee;

public void getData()

{

}

public void getData(int sn,String snm,float f)

{

sno=sn;

sname=snm;

fee=f;

}

public void display()

{

System.out.println("Sno   : "+sno);

System.out.println("Sname : "+sname);

System.out.println("Fees  : "+fee);

}

}

public class MethodOvl {

public static void main(String[] args) {

Student s=new Student();

s.getData();

s.display();

Student s1=new Student();

s1.getData(101,"babe",500);

s1.display();

}

}

output:

Sno   : 0

Sname : null

Fees  : 0.0

Sno   : 101

Sname : babe

Fees  : 500.0

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();

  }

}

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?


import 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 - 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");

  }

 }


}


Output :

Enter the index of 1st string where you want to retrive the charecter:-1

Enter the index of 2st string where you want to retrive the charecter:2

String index out of range

Output :

Enter the index of 1st string where you want to retrive the charecter:3

Enter the index of 2st string where you want to retrive the charecter:2

Charecter at the index of 3 1st string is: 

Null pointer exception

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 – 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();

  }

 }

}


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();         

     }  

}

Exercise – 11 (Producer & consumer problem)

Java program that implements producer consumer problem. It is an example for multi process synchronization, where producer always produces and consumer always consumes.The consumer consumes only after the producer produces.

class Thread1
{
    int num;
    boolean vs=false;
    synchronized int get()
    {
        if (!vs)
            try
            {
                wait();
            }
            catch (Exception e)
            {
                System.out.println("Excepton occurs at : "+e);
            }
        System.out.println("get" +num);
        try
        {
            Thread.sleep(1000);
        }
        catch (Exception e)
        {
            System.out.println("Excepton occurs at : "+e);
        }
        vs=false;
        notify();
        return num;
    }
    synchronized int put(int num)
    {
        if (vs)
            try
            {
                wait();
            }
            catch (Exception e)
            {
                System.out.println("Excepton occur at : "+e);
            }
        this.num=num;
        vs=true;
        System.out.println("put"+num);
        try
        {
            Thread.sleep(1000);
        }
        catch (Exception e)
        {
            System.out.println("Excepton occur at : "+e);
        }
        notify();
        return num;
    }
}
class Producer implements Runnable
{
    Thread1 t;
    Producer(Thread1 t)
    {
        this.t=t;
        new Thread(this,"Producer").start();
    }
    public void run()
    {
        int x=0;
        int i = 0;
        while (x<10)
        {
            t.put(i++);
            x++;
        }
    }
}
class Consumer implements Runnable
{
    Thread1 t;
    Consumer(Thread1 t)
    {
        this.t=t;
        new Thread(this,"Consumer").start();
    }
    public void run()
    {
        int x=0;
        while (x<10)
        {
            t.get();
            x++;
        }
    }
}
class  ProducerConsumer
{
    public static void main(String[] args)
    {
        Thread1 t=new Thread1();
        new Producer(t);
        new Consumer(t);
    }



b)Case study on thread synchronization

 

Aim: To write a case study on thread Synchronization after solving the above producer consumer problem

 

A case study on thread synchronization after solving producer consumer problem:

 

v We can use wait, notify and notifyAll methods to communicate between threads inJava.

v For example, if we have two threads running in your program e.g.Producer and Consumer then producer thread can communicate to the consumer that it can start consuming now because there are items to consume in thequeue.

v Similarly, a consumer thread can tell the producer that it can also start putting items now because there is some space in the queue, which is created as a result ofconsumption.

v A thread can use wait() method to pause and do nothing depending upon somecondition.

v For example, in the producer-consumer problem, producer thread should wait if the queue is full and consumer thread should wait if the queue isempty.

v If some thread is waiting for some condition to become true, we can use notify and notifyAll methods to inform them that condition is now changed and they can wakeup.

v Both notify() and notifyAll() method sends a notification but notify sends the notification to only one of the waiting thread, no guarantee which thread will receive notification and notifyAll() sends the notification to allthreads.

 

Things to remember:

 

1.  We can use wait() and notify() method to implement inter-thread communicationin Java. Not just one or two threads but multiple threads can communicate to each other by using thesemethods.

2.  Always call wait(), notify() and notifyAll() methods from synchronized method or synchronizedblock otherwise JVM will throwIllegalMonitorStateException.

3.  Always call wait and notify method from a loop and never from if() block, because loop test waiting condition before and after sleeping and handles notification even if waiting for the condition is not changed.

4.  Always call wait in shared object e.g. shared queue in thisexample.

5.  Prefer notifyAll() over notify() method due to reasons given in thisarticle


Exercise – 12 (Packages) 

a). Write a JAVA program illustrate class path 

import java.net.URL;

import java.net.URLClassLoader;

public class App{

public static void main(String[] args)

{

ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();

URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();

for(int i=0; i< urls.length; i++)

{

System.out.println(urls[i].getFile());

}

}

}


b). Write a case study on including in class path in your OS environment of your package.  

COPEING THE PATH OF JAVA:-

First of all go to MYCOMPUTER and go to the drive where the java is installed.In that go to

PROGRAM FILES and then double click on java folder.

In that we have observed there is a folder with name java jdk,double click on the java jdk folder

and then go into the bin folder.

At this time we have to copy the path of the bin folder.

SETTING THE JAVA PATH:-

Inorder to set the path of the java in our system,first of all we need to open CONTROL PANEL

in our system and go to SYSTEM SETTINGS .

In system settings we need to go into the ADVANCED SYSTEM SETTINGS settings.

In advanced system settings we just click on ENVIRONMENT VARIABLES option.

In USER VARIABLES click on NEW button and type the " path" at VARIABLE NAME.

We need to paste the previously copied path of the bin folder at the place of VARIABLE VALUE.

Finally click on OK and then OK,then close the MYCOMPUTR window.Now the java path is set.We are ready to use java facilities in our computer.

c). Write a JAVA program that import and use the defined your package in the previous  Problem

1)

package pack;

public class Addition

{

 private double d1,d2;

 public Addition(double a, double b)

 {

  d1=a;

  d2=b;

 }

 public void sum()

 {

  System.out.println("Sum inside of  class Addition is:"+(d1+d2));

 }

}

Compilation of the program :-  javac -d . Addition.java

                   

2).

import pack.Addition;

class Use

{

 public static void main(String args[])

 {

  Addition obj=new Addition(10,15.5);

  obj.sum();

 }

}

Exercise - 13 (Applet)

a).Write a JAVA program to paint like paint brush in applet.


import java.awt.*;  

import java.awt.event.*;  

import java.applet.*;  

public class MouseDrag extends Applet implements MouseMotionListener

{

 public void init()

 {  

  addMouseMotionListener(this);  

  setBackground(Color.red);  

 }  

 public void mouseDragged(MouseEvent me)

 {  

 Graphics g=getGraphics();  

 g.setColor(Color.white);  

 g.fillOval(me.getX(),me.getY(),10,10);  // (x-position, y-postion, width, height)

 }  

 public void mouseMoved(MouseEvent me)

 {

 }  

}


Applet Code: Applet Code save as .html file.


<html>

<applet code="MouseDrag.class" height=300 width=400>

</applet>

</html>


b) Write a JAVA program to display analog clock using Applet.


import java.applet.*;  

import java.awt.*;  

import java.util.*;  

import java.text.*;  

public class MyClock extends Applet implements Runnable 

{  

 int width, height;  

 Thread t = null;  

 boolean threadSuspended;  

 int hours=0, minutes=0, seconds=0;  

 String timeString = "";  

 public void init() 

 {  

        width = getSize().width;  

        height = getSize().height;  

  setBackground( Color.black );  

    }  

 public void start() 

 {  

  if ( t == null ) 

  {  

   t = new Thread( this );  

   t.setPriority( Thread.MIN_PRIORITY );  

   threadSuspended = false;  

   t.start();  

  }  

  else 

  {  

   if ( threadSuspended ) 

   {  

    threadSuspended = false;  

    synchronized( this ) 

    {  

     notify();  

               }  

           }  

        }  

    }  

    public void stop() 

 {  

        threadSuspended = true;  

    }  

 public void run() 

 {  

        try 

  {  

           while (true) 

   {  


               Calendar cal = Calendar.getInstance();  

               hours = cal.get( Calendar.HOUR_OF_DAY );  

               if ( hours> 12 ) hours -= 12;  

               minutes = cal.get( Calendar.MINUTE );  

               seconds = cal.get( Calendar.SECOND );  


               SimpleDateFormat formatter = new SimpleDateFormat( "hh:mm:ss", Locale.getDefault() );  

               Date date = cal.getTime();  

               timeString = formatter.format( date );  


               // Now the thread checks to see if it should suspend itself  

               if ( threadSuspended ) 

    {  

     synchronized( this ) 

     {  

                      while ( threadSuspended ) 

      {  

       wait();  

                      }  

                   }  

               }  

    repaint();  

    t.sleep( 1000 );  // interval specified in milliseconds  

           }  

        }  

        catch (Exception e) 

  { 

  }

    }  

    void drawHand( double angle, int radius, Graphics g ) 

 {  

        angle -= 0.5 * Math.PI;  

        int x = (int)( radius*Math.cos(angle) );  

        int y = (int)( radius*Math.sin(angle) );  

  g.drawLine( width/2, height/2, width/2 + x, height/2 + y );  

    }  

    void drawWedge( double angle, int radius, Graphics g ) 

 {  

        angle -= 0.5 * Math.PI;  

        int x = (int)( radius*Math.cos(angle) );  

        int y = (int)( radius*Math.sin(angle) );  

        angle += 2*Math.PI/3;  

        int x2 = (int)( 5*Math.cos(angle) );  

        int y2 = (int)( 5*Math.sin(angle) );  

        angle += 2*Math.PI/3;  

        int x3 = (int)( 5*Math.cos(angle) );  

        int y3 = (int)( 5*Math.sin(angle) );  

  g.drawLine( width/2+x2, height/2+y2, width/2 + x, height/2 + y );  

  g.drawLine( width/2+x3, height/2+y3, width/2 + x, height/2 + y );  

  g.drawLine( width/2+x2, height/2+y2, width/2 + x3, height/2 + y3 );  

    }  

    public void paint( Graphics g ) 

 {  

  g.setColor( Color.white );  

  drawWedge( 2*Math.PI * hours / 12, width/5, g );  

  drawWedge( 2*Math.PI * minutes / 60, width/3, g );  

  drawHand( 2*Math.PI * seconds / 60, width/2, g );  

  g.setColor( Color.white );  

  g.drawString( timeString, 10, height-10 );  

    }  

}


Applet Code: Applet Code save as .html file.


<html>

<applet code="MyClock.class" height=300 width=400>

</applet>

</html>


c). Write a JAVA program to create different shapes and fill colors using Applet.


import java.applet.*;

import java.awt.*;

public class  ShapeColor extends Applet

{

   int x=300,y=100,r=50;

 public void paint(Graphics g)

 {

  g.setColor(Color.red);  //Drawing line color is red

  g.drawLine(3,300,200,10);

  g.setColor(Color.magenta);  

  g.drawString("Line",100,100);

  g.drawOval(x-r,y-r,100,100);

  g.setColor(Color.yellow);  //Fill the yellow color in circle

  g.fillOval( x-r,y-r, 100, 100 );

  g.setColor(Color.magenta);

  g.drawString("Circle",275,100);

  g.drawRect(400,50,200,100);

  g.setColor(Color.yellow);  //Fill the yellow color in rectangel

  g.fillRect( 400, 50, 200, 100 );

  g.setColor(Color.magenta);

  g.drawString("Rectangel",450,100);

   }

}


Applet Code: Applet Code save as .html file.


<html>

<applet code="ShapeColor.class" height=300 width=400>

</applet>

</html>


Exercise - 14 (Event Handling)

a).Write a JAVA program that display the x and y position of the cursor movement using

Mouse.


import java.awt.*;


import java.awt.event.*;

import java.applet.Applet;

public class AppletMouse extends Applet implements MouseListener, MouseMotionListener

{

  int x, y;

  String str="";

  public void init()

  {

    addMouseListener(this);

    addMouseMotionListener(this);

  }

                                    // override ML 5 abstract methods

  public void mousePressed(MouseEvent e)

  {

    x = e.getX();

    y = e.getY();

    str = "Mouse Pressed";

    repaint();

  }

  public void mouseReleased(MouseEvent e)

  {

    x = e.getX();

    y = e.getY();

    str = "Mouse Released";

    repaint();

   }

   public void mouseClicked(MouseEvent e)

   {

     x = e.getX();

     y = e.getY();

     str = "Mouse Clicked";

     repaint();

   }

   public void mouseEntered(MouseEvent e)

   {

     x = e.getX();

     y = e.getY();

     str = "Mouse Entered";

     repaint();

   }

   public void mouseExited(MouseEvent e)

   {

     x = e.getX();

     y = e.getY();

     str = "Mouse Exited";

     repaint();

   }

                                    // override two abstract methods of MouseMotionListener

   public void mouseMoved(MouseEvent e)

   {

     x = e.getX();

     y = e.getY();

     str = "Mouse Moved";

     repaint();

   }

   public void mouseDragged(MouseEvent e)

   {

     x = e.getX();

     y = e.getY();

     str = "Mouse dragged";

     repaint();

   }

                                    // called by repaint() method

   public void paint(Graphics g)

   {

     g.setFont(new Font("Monospaced", Font.BOLD, 20));

     g.fillOval(x, y, 10, 10);

     g.drawString(x + "," + y,  x+10, y -10);

     g.drawString(str, x+10, y+20);

     showStatus(str + " at " + x + "," + y);

   }

}


Applet code:Applet code save as .html  file

<html>  

<body>  

<applet code="AppletMouse.class" width="300" height="300">  

</applet>  

</body>  

</html>  


b).Write a JAVA program that identifies key-up key-down event user entering text in a  Applet.



import java.applet.Applet;

import java.awt.*;


public class KeyUpDown1 extends Applet {

   private Font f;

   private String letter;

   private boolean first;


   public void init()

   {

      f = new Font( "Courier", Font.BOLD, 72 );

      first = true;

   }


   public void paint( Graphics g )

   {

      g.setFont( f );


      if ( !first )

         g.drawString( letter, 75, 70 );

   }


   public boolean keyDown( Event e, int key )

   {

      showStatus( "keyDown: the " + ( char ) key +

                  " was pressed." );


      letter = String.valueOf( ( char ) key );

      first = false;

      repaint();


      return true;   // event has been handled

   }


   public boolean keyUp( Event e, int key )

   {

      showStatus( "keyUp: the " + ( char ) key +

                  " was released." );


      return true;   // event has been handled

   }

}



Applet code:Applet code save as .html

<html>  

<body>  

<applet code="KeyUpDown1.class" width="300" height="300">  

</applet>  

</body>  

</html>  






No comments:

Post a Comment