JAVA LAB SOLUTIONS

JAVA PROGRAMMING LAB
Syllabus

Exercise - 1:
  1. Write a JAVA program to display default value of all primitive data type of JAVA.
  2. public class Demoex1 {
    static Boolean val1;
    static double val2;
    static float val3;
    static int val4;
    static long val5;
    static String val6;
    public static void main (String [] args) {
    System.out.println("Default values:");
    System.out.println("Val1 = " + val1);
    System.out.println("Val2 = " + val2);
    System.out.println("Val3 = " + val3);
    System.out.println("Val4 = " + val4);
    System.out.println("Val5 = " + val5);
    System.out.println("Val6 = " + val6);
    }
    }
    
  3. 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.
  4. import java. util.*;
    class Quadratic_qua
    {
    public static void main (String [] args)
    {
    int a, b, c;
    double r1, r2, D;
    Scanner s = new Scanner(System.in);
    System.out.println("Given quadratic equation:ax^2 + bx + c");
    System.out.print("Enter a:");
    a = s.nextInt();
    System.out.print("Enter b:");
    b = s.nextInt();
    System.out.print("Enter c:");
    c = s.nextInt();
    D = b * b - 4 * a * c;
    if (D > 0)
    {
    System.out.println("Roots are real and unequal");
    r1 = (- b + Math.sqrt(D))/(2*a);
    r2 = (-b - Math.sqrt(D))/(2*a);
    System.out.println("First root is:"+r1);
    System.out.println("Second root is:"+r2);
    }
    else if (D == 0)
    {
    System.out.println("Roots are real and equal");
    r1 = (-b+Math.sqrt(D))/(2*a);
    System.out.println("Root:"+r1);
    }
    else
    {
    System.out.println("Roots are imaginary");
    }
    }
    }
    
  5. 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.
  6. import java.util.*;
    class Bikerace
    {
    public static void main (String[] args)
    {
    float B1,B2,B3,B4,B5,average;
    Scanner s = new Scanner(System.in);
    System.out.println("Enter speed of first racer:");
    B1 = s.nextFloat();
    System.out.println("Enter speed of second racer:");
    B2 = s.nextFloat();
    System.out.println("Enter speed of third racer:");
    B3 = s.nextFloat();
    System.out.println("Enter speed of fourth racer:");
    B4 = s.nextFloat();
    System.out.println("Enter speed of fifth racer:");
    B5 = s.nextFloat();
    average=(B1+B2+B3+B4+B5)/5;
    if(B5>average)
    System.out.println("Fifth racer is qualify racer:");
    if(B4>average)
    System.out.println("Fourth racer is qualify racer:");
    if(B3>average)
    System.out.println("Third racer is qualify racer:");
    if(B2>average)
    System.out.println("Second racer is qualify racer:");
    if(B1>average)
    System.out.println("First racer is qualify racer:");
    }
    }
    


Exercise - 2:
  1. Write a JAVA program to search for an element in a given list of elements using binary search mechanism.
  2. import java.io.*;
    import java.util.Scanner;
    class BinarySearchExample {
    	int binarySearch2a(int arr[], int x)
    	{
    		int l = 0, r = arr.length - 1;
    		while (l <= r) {
    			int m = l + (r - l) / 2;
    
    			// Check if x is present at mid
    			if (arr[m] == x)
    				return m;
    
    			// If x greater, ignore left half
    			if (arr[m] < x)
    				l = m + 1;
    
    			// If x is smaller, ignore right half
    			else
    				r = m - 1;
    		}
    		return -1;
    	}
    
    	public static void main(String args[])
    	{
    		BinarySearchExample ob = new BinarySearchExample();
    		int arr[ ]=new int[5];
    		Scanner s = new Scanner(System.in);
    		System.out.println("Enter elements in sorted order:");
    		for (int i = 0; i < 5; i++)
    		arr[i] = s.nextInt();
    		System.out.println("Enter the search value:");
    		int x = s.nextInt();
    		int result = ob.binarySearch2a(arr, x);
    		if (result == -1)
    			System.out.println("Element is not present in array");
    		else
    			System.out.println("Element is present at "+ "index " + result);
    	}
    }
    
    
  3. Write a JAVA program to sort for an element in a given list of elements using bubble sort.
  4. import java.util.Scanner;
    class Sort{
    void Bubsorting(int a[],int n)
    {
    int temp,i,j;
    for(i=0;i<n;i++)
    {
    for(j=0;j<n-1;j++)
    {
    if(a[j]>a[j+1])
    {
    temp=a[j];
    a[j]=a[j+1];
    a[j+1]=temp;
    }
    }
    }
    System.out.println("The sorted elements are:");
    for(i=0;i<n;i++)
    System.out.print("\t"+a[i]);
    }
    }
    
    
    class bubblesort2b{
    public static void main(String args[]){
    int n, i,j, temp;
    int a[]=new int[20];
    Scanner s = new Scanner(System.in);
    System.out.println("Enter total number of elements:");
    n = s.nextInt();
    System.out.println("Enter elements:");
    for (i = 0; i < n; i++)
    a[i] = s.nextInt();
    Sort s1=new Sort();
    s1.Bubsorting(a,n);
    }
    }
    
  5. Write a JAVA program to sort for an element in a given list of elements using merge sort.
  6. import java.util.Scanner;
    import java.io.IOException;
    public class Mergesort2c
    {
    public static void sort(int[] a, int low, int high)
    {
    int N = high - low;
    if (N <= 1)
    return;
    int mid = low + N/2;
    sort(a, low, mid);
    sort(a, mid, high);
    int[] temp = new int[N];
    int i = low, j = mid;
    for (int k = 0; k < N; k++)
    {
    if (i == mid)
    temp[k] = a[j++];
    else if (j == high)
    temp[k] = a[i++];
    else if (a[j]<a[i])
    temp[k] = a[j++];
    else
    temp[k] = a[i++];
    }
    for (int k = 0; k < N; k++)
    a[low + k] = temp[k];
    }
    
    public static void main(String args[])
    {
    Scanner s= new Scanner(System.in);
    int n, i;
    System.out.println("Enter number of integer elements");
    n = s.nextInt();
    int arr[] = new int[ n ];
    System.out.println("\nEnter "+ n +" integer elements");
    for (i = 0; i < n; i++)
    arr[i] = s.nextInt();
    sort(arr, 0, n);
    System.out.println("\nElements after sorting ");
    for (i = 0; i < n; i++)
    System.out.print(arr[i]+" ");
    System.out.println();
    }
    }
    
  7. Write a JAVA program using StringBuffer to delete, remove character.
  8. class stringbuffer2d{
    public static void main(String[] args){
    StringBuffer sb1 = new StringBuffer("Hello World");
    sb1.delete(0,6);
    System.out.println(sb1);
    StringBuffer sb2 = new StringBuffer("Some Content");
    System.out.println(sb2);
    sb2.delete(0, sb2.length());
    System.out.println(sb2);
    StringBuffer sb3 = new StringBuffer("Hello World");
    sb3.deleteCharAt(0);
    System.out.println(sb3);
    }
    }
    


Exercise -3:
  1. Write a JAVA program to implement class mechanism. Create a class, methods and invoke them inside main method.
  2. import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    public class Example3a
    {
    int a,b,res;
    BufferedReader br=new BufferedReader(new BufferedReader(new InputStreamReader(System.in)));
    
    public void readNumber()throws IOException
    {
    System.out.println("enter a value:");
    a=Integer.parseInt(br.readLine());
    System.out.println("enter b value:");
    b=Integer.parseInt(br.readLine());
    }
    
    public void calculate()
    {
    res=a+b;
    }
    
    public void display()
    {
    System.out.println("the result is:"+res);
    }
    
    public static void main(String args[])throws IOException
    {
    Example3a e=new Example3a();
    e.readNumber();
    e.calculate();
    e.display();
    }
    }
    
  3. Write a JAVA program to implement constructor.
  4. public class VolumeCube
    {
    int cube;
    static double PIE=3.14;
    VolumeCube(int a)
    {
    cube=a*a*a;
    }
    public void displayVolume()
    {
    System.out.println("the volume of the cube is"+cube);
    }
    public static void main(String args[]){
    VolumeCube v=new VolumeCube(2);
    v.displayVolume();
    }
    }
    


Exercise -4:
  1. Write a JAVA program to implement constructor overloading.
  2.   
    import java.io.IOException;
    public class Volume4a
    {
    static double PIE=3.14;
    
    Volume4a(double r,int h)
    {
    double cone=(PIE*r*r*h)/3;
    System.out.println("the volume of cone is "+cone);
    }
    
    Volume4a(double l,double b,double h)
    {
    double cuboid=l*b*h;
    System.out.println("the volume of double cuboid is "+cuboid);
    }
    
    public static void main(String args[])throws IOException
    {
    Volume4a v1=new Volume4a(2.5,3);
    Volume4a v2=new Volume4a(2.2,3.3,4.4);
    }
    }
    
  3. Write a JAVA program implement method overloading.
  4.  
    class Adder{      
    int add(int a,int b){return a+b;}     
    double add(double a, double b){return a+b; }     
    }   
    
    class Example{      
    public static void main(String[] args){          
    Adder A=new Adder();    
    System.out.println(A.add(5,109));      
    System.out.println(A.add(7.7,9.2));     
     }
     } 
    


Exercise -5:
  1. Write a JAVA program to implement Single Inheritance.
  2.   
    import java.util.*;
    class Data{
       protected int a,b;
       public void readData(){
           Scanner sc=new Scanner(System.in);
           System.out.println("Enter a value");
           a=sc.nextInt();
           System.out.println("Enter b value");
           b=sc.nextInt();
       }
    }
    class Sum extends Data{
        public int c;
      public void Add(){
          c=a+b;
          System.out.println("Sum of 2 no's is"+c);
      }
    }
    public class singleInherit
    {
    	public static void main(String[] args) {
    		Sum s=new Sum();
    		s.readData();
    		s.Add();
    	}
    }
    
  3. Write a JAVA program to implement multi level Inheritance
  4. import java.util.*;
    class A{
       public int c;
       public void Add(int a,int b){
           c=a+b;
          System.out.println("Sum of 2 no's is"+c); 
       }
    }
    class B extends A{
      public void Diff(int a,int b){
          c=a-b;
          System.out.println("Difference of 2 no's is"+c);
      }
    }
    
    class C extends B{
      public void Mul(int a,int b){
          c=a*b;
          System.out.println("Multiplication of 2 no's is"+c);
      }
    }
    public class Main
    {
    	public static void main(String[] args) {
    	   Scanner sc=new Scanner(System.in);
           System.out.println("Enter a value");
           int a=sc.nextInt();
           System.out.println("Enter b value");
           int b=sc.nextInt();
    		C s=new C();
    		s.Diff(a,b);
    		s.Add(a,b);
    		s.Mul(a,b);
    	}
    }
    
  5. Write a java program for abstract class to find areas of different shapes
  6. import java.util.*;
    abstract class Areas
    {
    abstract void computeArea();
    }
    
    class areaCircle extends Areas
    {
    public double circle,r,pi=3.14;
    areaCircle(double radius)
    {
    this.r=radius;
    }
    public void computeArea()
    {
    circle=pi*r*r;
    System.out.print("the area of circle is : "+circle);
    }
    }
    
    class areaTria extends Areas
    {
    public double Traingle,b,h;
    areaTria(double breadth,double height)
    {
    this.b=breadth;
    this.h=height;
    }
    public void computeArea()
    {
    Traingle=0.5*b*h;
    System.out.print("the area of Traingle is : "+Traingle);
    }
    }
    
    public class areaDemo1
    {
    public static void main(String args[])
    {
    Scanner sc = new Scanner(System.in);
    int ch;
    Double s,l,b,h,r;
    while(true)
    {
    System.out.print("\n1 : Area of Triangle");
    System.out.print("\n2 : Area of circle");
    System.out.print("\n3 : Exit");
    System.out.print("\nenter your choice");
    ch=sc.nextInt();
    switch(ch)
    {
    case 1:
    System.out.print("\nEnter breath,height of Triangle");
    b=sc.nextDouble();
    h=sc.nextDouble();
    areaTria ac=new areaTria(b,h);
    ac.computeArea();
    break;
    case 2:
    System.out.print("\nEnter radius of circle");
    r=sc.nextDouble();
    areaCircle aci=new areaCircle(r);
    aci.computeArea();
    break;
    case 3:
    System.exit(0);
    break;
    default:
    System.out.println("enter correct choice");
    }
    }
    }
    }
    


Exercise -6:
  1. Write a JAVA program give example for super keyword.
  2. class A{      
    void print(){
    System.out.println("A class printing...");
    }      
    }      
    class B extends A{
    
    void print(){
    System.out.println("B class printing...");
    }         
    
    void work(){      
    super.print();      
    print();       
    }      
    }
    
    class TestSuper1{      
    public static void main(String args[]){      
    B d=new B();      
    d.work();      
    }} 
    
    
  3. Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
  4. interface FirstInterface {
      public void myMethod();}
    
    interface SecondInterface {
      public void myOtherMethod();}
    
    class DemoClass implements FirstInterface, SecondInterface {
      public void myMethod() {
        System.out.println("Some text..");
      }
      public void myOtherMethod() {
        System.out.println("Some other text...");
      }
    }
    class Main {
      public static void main(String[] args) {
        DemoClass myObj = new DemoClass();
        myObj.myMethod();
        myObj.myOtherMethod();
      }}
    
    


Exercise -7:
  1. Write a JAVA program that describes exception handling mechanism
  2. public class ExceptionHandling
    {
    public static void main(String arg[])
    {
    try
    {
    for(int i = -10;i<10;i++)
    {
    double d=100/i;
    System.out.println(d);
    }
    }
    catch(ArithmeticException ae)
    {
    System.out.println("Arithmetic Exception is raised.");
    }
    finally
    {
    System.out.println("This is Finally block");
    }
    }
    }
    
  3. Write a JAVA program Illustrating Multiple catch clauses
  4. import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    class MultipleCatch
    {
    public static void main(String arg[])throws IOException
    {
    int a[]=new int[5];
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter element into array");
    for(int i=0;i<5;i++)
    {
    a[i]=Integer.parseInt(br.readLine());
    }
    try
    {
    for(int i=0;i<6;i++)
    {
    System.out.println("element:"+a[i]);
    }
    }
    catch(ArithmeticException ae)
    {
    System.out.println("Arithmetic Exception is called.");
    }
    catch(ArrayIndexOutOfBoundsException aioob)
    {
    System.out.println("ArrayIndexOutOfBounds Exception is called.");
    }
    finally
    {
    System.out.println("This is Finally block");
    }
    }
    }
    


    Exercise -8:
    1. Write a JAVA program that implements Runtime polymorphism.
    2. class Animal
      {
      public void move()
      {
      System.out.println("Animals can move");
      }
      }
      class Dog extends Animal
      {
      public void move()
      {
      System.out.println("Dogs can walk and run");
      }
      }
      public class TestDog
      {
      public static void main(String args[])
      {
      Animal a = new Animal();
      Animal b = new Dog();
      a.move();
      b.move();
      }
      }
      
    3. Write a Case study on run time polymorphism, inheritance that implements in above problem
    4. The Above code defines two classes: Animal and Dog. The Animal class is the base class, while the Dog class is a subclass that extends the functionality of the Animal class. This establishes a hierarchical relationship, illustrating the concept of inheritance.
      
      The move method in both the Animal and Dog classes demonstrates polymorphism. In Java, polymorphism allows a single method name to be used for methods that have the same name but belong to different classes. This is achieved through method overriding, where a subclass provides a specific implementation of a method defined in its superclass.
      Animal a = new Animal();
      Animal b = new Dog();
      a.move();
      b.move();
      
      In the above code, a is an instance of the Animal class, and b is an instance of the Dog class. At compile-time, the compiler recognizes the type of the reference variable (Animal), but at runtime, the actual object type (Dog) determines which version of the move method is called. This is known as runtime polymorphism or dynamic method dispatch.
      


    Exercise -9:
    1. Write a JAVA program for creation of Illustrating throw.
    2. 
      public class Main {
        static void checkAge(int age) { 
          if (age < 18) {
            throw new ArithmeticException("You must be at least 18 years old."); 
          } else {
            System.out.println("You are old enough!"); 
          }
       } 
       public static void main(String[] args) { 
         checkAge(15); 
       } 
      }
      
      
    3. Write a JAVA program for creation of Illustrating finally
    4.   class MyException extends Exception
      {
      public MyException(String s)
      {
      super(s);
      }
      }
      public class UserDefinedExceptionDemo
      {
      public static void main(String args[])
      {
      try
      {
      throw new MyException("Dhanekula");
      }
      catch (MyException ex)
      {
      System.out.println("Caught the exception1");
      System.out.println(ex.getMessage());
      }
      finally
      {
      System.out.println("Caught the exception2");
      }
      }
      }
        
    5. Write a JAVA program for creation of Java Built-in Exceptions
    6.   public class ExceptionHandling
      {
      public static void main(String arg[])
      {
      try
      {
      for(int i = -2;i<5;i++)
      {
      System.out.println(100/i);
      }
      }
      catch(ArithmeticException ae)
      {
      System.out.println("Arithmetic Exception is raised.");
      }
      finally
      {
      System.out.println("This is Finally block");
      }
      }
      }
        
    7. Write a JAVA program for creation of User Defined Exception
    8. 
      class MyException extends Exception
      {
      public MyException(String s)
      {
      super(s);
      }
      }
      public class UserDefinedExceptionDemo
      {
      public static void main(String args[])
      {
      try
      {
      throw new MyException("Dhanekula");
      }
      catch (MyException ex)
      {
      System.out.println("Caught the exception1");
      System.out.println(ex.getMessage());
      }
      }
      }
      


    Exercise -10:
    1. 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)
    2. class ThreadDemo1 implements Runnable
      {
      public void run()
      {
      System.out.println("good morning");
      }
      }
      class ThreadDemo2 implements Runnable
      {
      public void run()
      {
      System.out.println("hello");
      }
      }
      class ThreadDemo implements Runnable
      {
      public void run()
      {
      System.out.println("welcome");
      }
      public static void main(String args[])
      {
      ThreadDemo1 td1=new ThreadDemo1();
      ThreadDemo2 td2=new ThreadDemo2();
      ThreadDemo td3=new ThreadDemo();
      Thread t1=new Thread(td1);
      Thread t2=new Thread(td2);
      Thread t3=new Thread(td3);
      try{
      t1.start();
      t1.sleep(1000);
      t2.start();
      t2.sleep(2000);
      t3.start();
      t3.sleep(3000);
      }
      catch(InterruptedException ie)
      {
      System.out.println("not possible");
      }
      }
      }
      
    3. Write a program illustrating isAlive and join ()
    4. class TestDaemon extends Thread{
      public void run(){
      System.out.println("Name: "+Thread.currentThread().getName());
      System.out.println("Daemon: "+Thread.currentThread().isDaemon());
      }
      public static void main(String[] args){
      TestDaemon t1=new TestDaemon();
      TestDaemon t2=new TestDaemon();
      t1.setDaemon(true);
      t1.start();
      try{
      t1.join();	//Waiting for t1 to finish
      }
      catch(InterruptedException ie){}
      System.out.println(t1.isAlive());
      t2.start();
      }
      }
      
    5. Write a Program illustrating Daemon Threads
    6. public class TestDaemon1 extends Thread{  
       public void run(){  
        if(Thread.currentThread().isDaemon()){
         System.out.println("daemon thread work");  
        }  
        else{   System.out.println("user thread work");   }   }  
       public static void main(String[] args){  
        TestDaemon1 t1=new TestDaemon1();
        TestDaemon1 t2=new TestDaemon1();  
        t1.setDaemon(true);//now t1 is daemon thread  
        t1.start();//starting threads  
        t2.start();  
       }  }  
      


    Exercise -11:
    1. Write a JAVA program Producer Consumer Problem
    2. import java.util.LinkedList;
      public class PCThreadExample
      {
      public static class PC
      {
      LinkedList ll = new LinkedList<>();
      int capacity = 10;
      public void produce() throws InterruptedException
      {
      int values = 0;
      while(true)
      {
      synchronized (this)
      {
      while(ll.size() == capacity)
      {
      System.out.println("Producer going to wait");
      wait();
      }
      System.out.println("Producer Produced ---->"+values);
      ll.add(values);
      notify();
      values++;
      Thread.sleep(1000);
      }
      }
      }
      public void consume() throws InterruptedException
      {
      while (true)
      {
      synchronized (this)
      {
      while (ll.size()==0)
      {
      System.out.println("consumer going to wait");
      wait();
      }
      int val = ll.removeFirst();
      System.out.println("Consumer consumed ---->"+ val);
      notify();
      Thread.sleep(1000);
      }
      }
      }
      }
      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();
      }
      }
      });
      t2.start();
      t1.start();
      t1.join();
      t2.join();
      }
      }
      


    Exercise -12:
    1. Write a JAVA program illustrate class path.
    2.   
      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()); 
      }
       } }
      
    3. Write a case study on including in class path in your os environment of your package.
    4.  
      The differences between path and classpath are given by.
      
      1. The PATH is an environment variable used to locate "java" or "javac" command, to run java program and compile java source file. The CLASSPATH is an environment variable used to set path for java classes.
      
      2. In order to set PATH in Java, we need to include bin directory in PATH environment while in order to set CLASSPATH we need to include all directories where we have put either our class file or JAR file, which is required by our Java application.
      
      3. PATH environment variable is used by operating system while CLASSPATH is used by Java ClassLoaders to load class files.
      4. Path refers to the system while classpath refers to the Developing Environment.
      By default the java run time system uses the current working directory.
      > Normally to execute a java program in any directory we have to set the path by as follows
      set path= C:\Program Files\java\jdk1.7.0_10\bin:
      
       Settings Environmental Variables
      
    5. Write a JAVA program that import and use the defined your package in the previous Problem
    6.  
      package p1;
      import java.io.BufferedReader;
      import java.io.InputStreamReader;
      import java.io.IOException;
      public class Addition
      {
      //Add two Integers and print the output
      public void addNumbers() throws IOException
      {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Enter first Number: ");
      float firstNumber = Float.parseFloat(br.readLine());
      System.out.print("Enter second Number: ");
      float secondNumber = Float.parseFloat(br.readLine());
      float result = firstNumber + secondNumber;
      System.out.println("the sum of "+firstNumber+" and "+secondNumber+" is "+result+".");
      }
      }
      
      
      import p1.Addition;
      import java.io.IOException;
      public class PackageAddition extends Addition
      {
      public static void main(String a[]) throws IOException
      {
      PackageAddition a1 = new PackageAddition();
      a1.addNumbers();
      }
      }
      


    Exercise -13:
    1. Write a JAVA program to paint like paint brush in applet.
    2. import java.awt.Graphics;
      import java.awt.Font;
      import java.awt.Color;
      import javax.swing.JApplet;
      import java.awt.event.MouseEvent;
      import java.awt.event.MouseMotionListener;
      public class PaintApplication extends JApplet implements MouseMotionListener
      {
      int x=-10,y=-10;
      String msg="";
      public PaintApplication()
      {
      addMouseMotionListener(this);
      }
      public void mouseDragged(MouseEvent e)
      {
      x=e.getX();
      y=e.getY();
      repaint();
      }
      public void mouseMoved(MouseEvent e)
      {
      }
      public void paint(Graphics g)
      {
      Color c = new Color(255,0,0);
      g.setColor(c);
      g.fillOval(x,y,25,10);
      }
      }
      /*<applet code="PaintApplication.class" height="400" width="600">
      </applet> */
      
    3. Write a JAVA program to create different shapes and fill colors using Applet.
    4.     import java.applet.Applet;  
          import java.awt.*;  
            
          public class GraphicsDemo extends Applet{  
            
          public void paint(Graphics g){  
          g.setColor(Color.red);  
          g.drawString("Welcome",50, 50);  
          g.drawLine(20,30,20,300);  
          g.drawRect(70,100,30,30);  
          g.fillRect(170,100,30,30);  
          g.drawOval(70,200,30,30);  
            
          g.setColor(Color.pink);  
          g.fillOval(170,200,30,30);  
          g.drawArc(90,150,30,30,30,270);  
          g.fillArc(270,150,30,30,0,180);  
            
          }  
          }  
         /* <applet code="GraphicsDemo.class" width="300" height="300">   
      </applet> 
      
    5. Write a JAVA program to create different shapes and fill colors using Applet.
    6. 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.gray );  
            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="MyClock.class" width="300" height="300"> 
      </applet> 
      */
      


    Exercise -14:
    1. Write a JAVA program that display the x and y position of the cursor movement using Mouse.
    2. import java.awt.Graphics;
      import java.awt.Font;
      import java.applet.Applet;
      import java.awt.event.MouseEvent;
      import java.awt.event.MouseMotionListener;
      public class MouseMotionXY extends Applet implements MouseMotionListener
      {
      int x=0,y=0;
      String msg="";
      public MouseMotionXY()
      {
      addMouseMotionListener(this);
      }
      public void mouseDragged(MouseEvent e)
      {
      x=e.getX();
      y=e.getY();
      msg="Mouse Beign Dragged at X:"+x+" Y:"+y;
      }
      public void mouseMoved(MouseEvent e)
      {
      x=e.getX();
      y=e.getY();
      msg="Mouse Beign Moved at X:"+x+" Y:"+y;
      repaint();
      }
      public void paint(Graphics g)
      {
      Font f = new Font("arial",Font.BOLD,15);
      g.setFont(f);
      g.drawString(msg,x,y);
      }
      }
      /*<applet code="MouseMotionXY.class" height="400" width="600"> </applet>*/
      
    3. Write a JAVA program that display the x and y position of the cursor movement using Mouse.
    4. import java.awt.Graphics;
      import java.awt.Color;
      import java.awt.event.KeyListener;
      import java.awt.event.KeyEvent;
      import java.applet.Applet;
      public class Key extends Applet implements KeyListener
      {
      int X=20,Y=30;
      String msg="KeyEvents--->";
      public void init()
      {
      addKeyListener(this);
      requestFocus();
      setBackground(Color.green);
      setForeground(Color.blue);
      }
      public void paint(Graphics g)
      {
      g.drawString(msg,X,Y);
      }
      public void keyReleased(KeyEvent k)
      {
      showStatus("Key Up");
      }
      public void keyPressed(KeyEvent k)
      {
      showStatus("KeyDown");
      int key=k.getKeyCode();
      switch(key)
      {
      case KeyEvent.VK_UP:
      Y=Y-10;
      showStatus("Move to Up");
      break;
      case KeyEvent.VK_DOWN:
      Y=Y+10;
      showStatus("Move to Down");
      break;
      case KeyEvent.VK_LEFT:
      X=X-10;
      showStatus("Move to Left");
      break;
      case KeyEvent.VK_RIGHT:
      X=X+10;
      showStatus("Move to Right");
      break;
      }
      repaint();
      }
      public void keyTyped(KeyEvent k)
      {
      msg+=k.getKeyChar();
      repaint();
      }
      }
      /*
      <applet code="Key" width=300 height=400>
      </applet>
      */
      

5 comments:

  1. Online Java course
    Java course
    https://www.truxgo.net/blogs/323541/890985/java-course-what-you-need-to-know-about-java-training-program

    ReplyDelete
  2. Python is one of the most popular and versatile programming languages in the world, known for its simplicity and readability. APTRON Solution Noida offers comprehensive Python training courses suitable for beginners and experienced developers alike. Whether you are just starting your programming journey or want to expand your skill set, our training will meet your needs. At APTRON Solution Noida, we take a hands-on approach to Python Training in Noida. Our experienced instructors will guide you through the fundamentals and advanced concepts of Python, ensuring that you not only understand the language but can also apply it effectively in real-world scenarios. You'll work on projects, participate in coding exercises, and gain practical experience that sets you apart in the job market.

    ReplyDelete
  3. Great post! I found your insights really valuable and informative. Your explanation was clear and helped me understand the topic better.
    Best Advanced Java Online Training
    Best Java Training in Hyderabad
    Advanced Java Course

    ReplyDelete