Friday, 6 September 2019


JAVA PRACTICALS



  1. WRITE  A JAVA  PROGRAM TO  FIND THE SUM  OF ANY NUMBER OF  INTEGERS ENTERED AS  COMMAND LINE ARGUMENT.

class Program1
{
       public static void main(String args[])
      {
              int n,a,sum=0;
              n = Integer.parseInt(args[0]);
              a = Integer.parseInt(args[1]);
              sum = a + n;
              System.out.println("Sum of given numbers ="+sum);
      }
}          


       

    
        
}          


























  1. WRITE  A JAVA  PROGRAM TO  FIND FACTORIAL  OF A NUMBER.
im; import java.util.Scanner
{ class Program2
        public static void main(String args[])
        {
              int num,fact = 1;
              Scanner obj = new Scanner(System.in);
              System.out.println("Enter any number");
              num = obj.nextInt();
              for(int i=1;i<=num;i++)
              {
                   fact = fact * i;
              }
              System.out.println(fact);
         }
}
























  1. To learn the use of single dimensional array by defining the array dynamically.
class Program3
{
    public static void main (String[] args)
    {        
     int[] arr;
     arr = new int[5];
     arr[0] = 10;
     arr[1] = 20;
     arr[2] = 30;
     arr[3] = 40;
     arr[4] = 50;
     for (int i = 0; i < arr.length; i++)
         System.out.println("Element at index " + i +
                                      " : "+ arr[i]);         
    }
}



























  1. TO LEARN THE USE OF TWO DIMENSIONAL ARRAY

class Program4
{
    public static void main(String args[])
    {
        // declaring and initializing 2D array
        int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

        // printing 2D array
        for (int i=0; i< 3 ; i++)
        {
            for (int j=0; j < 3 ; j++)
                System.out.print(arr[i][j] + " ");

            System.out.println();
        }
    }
}





















  1. WRITE  A JAVA  PROGRAM TO  CONVERT A DECIMAL  NUMBER INTO BINARY NUMBER.
import java.util.Scanner;
class Program5
{
        public static void main(String args[])
        {
                 String s = " ";
                 int r, num;
                 System.out.println("Enter the number with decimal as base");
                 Scanner obj = new Scanner(System.in);
                 num = obj.nextInt();
                 while(num>0)
                 {
                       r = num%2;
                       num = num/2;
                       s = r+s;             
                 }
                 System.out.println("Corresponding number in binary is"+s);
        }
}     


















  1. WRITE  A JAVA  PROGRAM TO  CHECK IF THE  ENTERED NUMBER IS  PRIME OR NOT.
import java.util.Scanner;
class Program6
{
       public static void main(String args[])
       {
               int num,flag=0;
               Scanner obj = new Scanner(System.in);
               System.out.println("Enter a number");
               num = obj.nextInt();
               for(int i = 1; i<=num;i++)
               {
                       if(num%i==0)
                       {
                            flag++;
                       }
               }
               if(flag == 2)
               {
                      System.out.println("The number is prime");
               }
               else
               {
                      System.out.println("The number is not prime");
               }
        }
}      








  1. WRITE  A JAVA  PROGRAM TO  FIND THE SUM  OF ANY NUMBER OF  INTEGERS INTERACTIVELY  ENTERING EVERY NUMBER FROM  THE KEYBOARD WHEREAS THE TOTAL  NUMBER OF INTEGERS IS GIVEN AS THE  COMMAND LINE ARGUMENT.
import java.util.Scanner;
class Program7
{
       public static void main(String args[])
       {
                int a,n,sum=0;
                Scanner obj = new Scanner(System.in);
                n = Integer.parseInt(args[0]);
                System.out.println("Number of integers to be added = "+n);
                for(int i=0;i<n;i++)
                {
                       a = obj.nextInt();
                       sum = sum + a;
                }
                System.out.println("Sum of given numbers is :"+sum);
        }
}












  1. Write a program that show working of different functions of String and StringBufferclasss like setCharAt(, setLength(), append(), insert(), concat()and equals().

public class StringBuffer2 

            public static void main (String args[]) 
            { 
                        StringBuffer p= new StringBuffer("God is Great"); 
                        char k[] = new char[20]; 
                        char q; 
                        p.getChars(7,11,k,0); 
                        System.out.println("Original string is "+p); 
                        p.delete(4,6); 
                        System.out.println("string after deleting a word "+p); 
                        p.insert(4,"is"); 
                        System.out.println("string after inserting a word "+p); 
                        p.deleteCharAt(4); 
                        System.out.println("string after deleting a character"+p); 
                        p.replace(4,5,"always"); 
                        System.out.println("string after replacing a word is "+p); 
                        q=p.charAt(0); 
                        System.out.println("the first character of string is "+q); 
            } 












  1. Write a program to show the working of this pointer.
class Program9
{
  int distance,speed,time;
  void compute()
  {
     this.distance=this.speed * this.time;
      System.out.println("Distance is:"+ distance);
   }
   Program9(int s,int t)
   {
       speed=s;
       time=t;
    }
    public static void main(String args[])
    {
       Program9 obj = new Program9(5,10)  ;
      obj.compute();
     }
}









  1. Write the program to show creation of reference and also clone.
class Program10
{
    int distance,speed,time;
    Program10(int s , int t)
    {
           speed=s;
           time=t;
     }
    void compute()
    { this.distance = this.speed * this.time;
         System.out.println("Distance is:" + distance );
    }
   void clone(Program10 obj1)
   { speed = obj1.speed;
        time = obj1.time;
   }
  public static void main(String args[])
  { Program10 obj = new Program10(5,10);
      Program10 obj2 = obj;
      Program10 obj3 = new Program10(1,2);
       obj3.clone(obj);
      obj2.compute();
      obj3.compute();
  }
}


  1. Write a program to show that during function overloading, if no matching argument is found, then java will apply automatic type conversion.
class OverloadTest
{
     void area(double a, double b)
     {System.out.println("Inside area function with double parameters: " + a*b); }
     void area(int a)
     { System.out.println("Inside area function with double and int parameter."); }
}
class Program11
{
     public static void main(String[] args)
     {       
        OverloadTest t1 = new OverloadTest();
         t1.area(8,8);
      }
}








  1. Write a program to show the difference between public and private access specifiers. The program should also show that primitive data types are passed by value and objects are passed by reference and to learn use of final keyword.
final class test
{ //final class implies this class cannot be inherited   
    private int a; //only accessible inside the class by the class methods   
    public int b; //accessible outside the class too   
    final int c = 20; //final varible implies its value cannot change during run-time.   
    test(int a, int b)
    {       
        this.a = a;   this.b = b;
        a--; //decrementing the value of a and b that was passed to this function, this has no effect on the values of i and j
         b--;
    }
   test(test ob)
   {
      a = ob.a;  b = ob.b;
      ob.a--; //decrementing a and b of passed object, this reflects in the object
      ob.b--;
   }
   void showab()
  {
       System.out.println("a: " + a + " b: " + b);
  }
}
class Program12
{
    public static void main(String[] args)
    {
        test ob1 = new test(1,21);    //ob1.a = 12; //not accessible outside class
        ob1.b = 20; //ok
       //ob1.c = 200; //error, c is final
        //to show primitive data types are passed by value
        int i = 10;    int j = 20;
        System.out.println("Values of i and j before passing them to a function: " + i + " " + j);
        test ob2 = new test(i,j);
        System.out.println("Values of i and j after passing them to a function and modifying the contents of passed values: " + i + " " +j);           //objects are passed by reference
        System.out.println("ob2 before passing");
        ob2.showab();
        test ob3 = new test(ob2);
        System.out.println("ob2 after passing");
        ob2.showab();
     }
}




   






  1. Write a program to show the use of static functions and to pass variable length arguments in a function.
class StaticDemo
{
 public static void printMsg()
 {
      System.out.println("Hello from static method.");
  }
  void printMessage(int ... v)
 {
    for(int x : v)
           System.out.print(x + " ");
    System.out.println();
 }
}
class Program13
{
   public static void main(String[] args)
   {
        StaticDemo.printMsg(); //static method can be called without creating an object of the class
        StaticDemo s1 = new StaticDemo();
        s1.printMessage(1,2,3);
        s1.printMessage(10,20,30);
   }
}



  1. Write a program to demonstrate the concept of boxing and autoboxing.
import java.io.*;
class Program14
{
   public static void main (String[] args)
   {
       // creating an Integer Object
       // with value 10.
       Integer i = new Integer(10);
       // unboxing the Object
       int i1 = i;
       System.out.println("Value of i: " + i);
       System.out.println("Value of i1: " + i1);
       //Autoboxing of char
       Character gfg = 'a';
       // Auto-unboxing of Character
       char ch = gfg;
       System.out.println("Value of ch: " + ch);
       System.out.println("Value of gfg: " + gfg);
   }
}







  1. Create a multi-file program where in one file a string message is taken as input from the user and the function to display the message on the screen is given in another file.
package prog15;
public class Display
{   
   public static void display(String msg)
   {
          System.out.println(msg);
   }
}
import java.util.Scanner;
import prog15.Display;
public class Program15
{
  public static void main(String[] args)
  {
        Scanner obj = new Scanner(System.in);
        System.out.println("Enter a message");
        String message = obj.next();
        Display.display(message);
  }
}




  1. Write a program to create a multilevel package and also creates a reusable class to generate Fibonacci series, where the function to generate Fibonacci series is given in a different file belonging to the same package.
package fibpkg.Question16;
class FibFunc
{
     public static void create(int num)
     {
            int t1 = 0, t2 = 1, t3 = 1;
            System.out.print(t1 + "," + t2 + ",");
            for(int i=0;i<num-2;i++)
            {
                  t3 = t1 + t2;
                  t1 = t2;
                  t2 = t3;
                  System.out.print(t3 + ",");
            }
            System.out.println();
       }
}
package fibpkg.Question16;
import java.util.Scanner;
public class Fibonacci
{
         public static void displayFib()
         {
               System.out.print("Enter the number of terms to be displayed: ");
               Scanner obj = new Scanner(System.in);
               int num = obj.nextInt();
               FibFunc.create(num);
         }

}
package fibpkg;
import fibpkg.Question16.*;
class createFib
{
     public static void main(String[] args)
     {
            Fibonacci.displayFib();
     }
}














  1. Write a program “DivideByZero” that takes two numbers a and b as input, computes a/b, and invokes Arithmetic Exception to generate a message when the denominator is zero.
public class MainClass
{
     public static void main(String args[]) {
     int urAns, urDiv;
    try
   {
      urDiv = 0;
      urAns = 25 / urDiv;
      System.out.println("Do you really think this will print out? No! It won't!");
    }
    catch (ArithmeticException e)
   {
      System.out.println("Division by zero not Possible!");
    }
    System.out.println("This will print out after Exception Handling");
 }
}








  1. Write a program to show the use of nested try statements that emphasizes the sequence of checking for catch handler statements.
class Program18
{  
public static void main(String args[])
     {   try
              {
                  int a = args.length;   
                  int b = 42/a;
                  System.out.println("a = "+a);
                  try
                  {
                     if(a == 1)
                           a = a/(a-a);
                    if(a == 2)
                    {
                            int c[] = {1};
                            c[42] = 99;
                       }
               }
               catch( ArrayIndexOutOfBoundsException e)
               {
                        System.out.println("Array index out-of-bounds : " + e);
               }
           }
           catch( ArithmeticException e)
           {
                System.out.println("Divide by 0 :" + e);

           }
      }
}
class InvalidAgeException extends Exception{  
InvalidAgeException(String s){  
 super(s);  
}  
}  





















  1. Write a program to create your own exception types to handle situation specific to your application.
class Program19{  
 
  static void validate(int age)throws InvalidAgeException{  
    if(age<18)  
     throw new InvalidAgeException("not valid");  
    else
     System.out.println("welcome to vote");  
  }
    
  public static void main(String args[]){  
     try{
     validate(13);  
     }catch(Exception m){System.out.println("Exception occured: "+m);}  
 
     System.out.println("rest of the code...");  
 }
}










  1. Write a program to demonstrate priorities among multiple threads.
import java.lang.*;
class Program20 extends Thread
{
   public void run()
   {
       System.out.println("Inside run method");
   }
    public static void main(String[]args)
   {
       Program21 t1 = new ThreadDemo();        Program21 t2 = new ThreadDemo();
       Program21 t3 = new ThreadDemo();
        System.out.println("t1 thread priority : " + t1.getPriority()); // Default 5
       System.out.println("t2 thread priority : " + t2.getPriority()); // Default 5
       System.out.println("t3 thread priority : " +  t3.getPriority()); // Default 5
        t1.setPriority(2);        t2.setPriority(5); t3.setPriority(8);
        System.out.println("t1 thread priority : " + t1.getPriority());  //2
       System.out.println("t2 thread priority : " +  t2.getPriority()); //5
       System.out.println("t3 thread priority : " +  t3.getPriority());//8
       System.out.print(Thread.currentThread().getName());
       System.out.println("Main thread priority : "  + Thread.currentThread().getPriority());
        Thread.currentThread().setPriority(10);
       System.out.println("Main thread priority : " + Thread.currentThread().getPriority());
   }
}



  1. Write a program to demonstrate different mouse handling events.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Program21 extends Applet
implements MouseListener,MouseMotionListener
{
    int X=0,Y=20;
    String msg="MouseEvents";
    public void init()
    {
        addMouseListener(this);
        addMouseMotionListener(this);
        setBackground(Color.black);
        setForeground(Color.red);
    }
    public void mouseEntered(MouseEvent m)
    {
        setBackground(Color.magenta);
        showStatus("Mouse Entered");
        repaint();
    }
    public void mouseExited(MouseEvent m)
    {
        setBackground(Color.black);
        showStatus("Mouse Exited");
        repaint();
    }
    public void mousePressed(MouseEvent m)
    {
        X=10;
        Y=20;
        msg="NEC";
        setBackground(Color.green);
        repaint();
    }
    public void mouseReleased(MouseEvent m)
    {
        X=10;
        Y=20;
        msg="Engineering";
        setBackground(Color.blue);
        repaint();
    }
    public void mouseMoved(MouseEvent m)
    {
        X=m.getX();
        Y=m.getY();
        msg="College";
        setBackground(Color.white);
        showStatus("Mouse Moved");
        repaint();
    }
    public void mouseDragged(MouseEvent m)
    {
        msg="CSE";
        setBackground(Color.yellow);
        showStatus("Mouse Moved"+m.getX()+" "+m.getY());
        repaint();
    }
    public void mouseClicked(MouseEvent m)
    {
        msg="Students";
        setBackground(Color.pink);
        showStatus("Mouse Clicked");
        repaint();
    }
    public void paint(Graphics g)
    {
        g.drawString(msg,X,Y);
    }
}
HTML Code:
<html>
<p> This file launches the 'A' applet: A.class! </p>  
<applet code="Program21.class" height=200 width=320>
No Java?!
</applet>
</html>




  1. Write a program that creates a Banner and then creates a thread to scrolls the message in the banner from left to right across the applet’s window.
import java.awt.*;
import java.applet.*;
public class Program22 extends Applet implements Runnable {
  String str = "This is a simple Banner ";
  Thread t ;   boolean b;
  public void init() {
     setBackground(Color.gray);
     setForeground(Color.yellow);
  }
  public void start() {
     t = new Thread(this);
     b = false;
     t.start();
  }
  public void run () {
     char ch;
     for( ; ; ) {
     try {
        repaint();
        Thread.sleep(250);
        ch = str.charAt(0);
        str = str.substring(1, str.length());
        str = str + ch;
     }
     catch(InterruptedException e) {}
     }
  }

  public void paint(Graphics g) {
     g.drawRect(1,1,300,150);
     g.setColor(Color.yellow);
     g.fillRect(1,1,300,150);
     g.setColor(Color.red);
     g.drawString(str, 1, 150);
  }
}
HTML Code:
<html>
<p> This file launches the 'A' applet: A.class! </p>  
<applet code="Program22.class" height=200 width=320>
No Java?!
</applet>
</html>












  1. Write a program to demonstrate different keyboard handling events.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Key" width=300 height=400>
</applet>
*/
public class Program23 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 keyPressed(KeyEvent k)
    {
        showStatus("KeyDown");
        int key=k.getKeyCode();
        switch(key)
        {
            case KeyEvent.VK_UP:
                showStatus("Move to Up");
                break;
            case KeyEvent.VK_DOWN:
                showStatus("Move to Down");
                break;
            case KeyEvent.VK_LEFT:
                showStatus("Move to Left");
                break;
            case KeyEvent.VK_RIGHT:
                showStatus("Move to Right");
                break;
        }
        repaint();
    }
    public void keyReleased(KeyEvent k)
    {
        showStatus("Key Up");
    }
    public void keyTyped(KeyEvent k)
    {
        msg+=k.getKeyChar();
        repaint();
    }
    public void paint(Graphics g)
    {
        g.drawString(msg,X,Y);
    }
}
HTML Code:
<html>
<p> This file launches the 'A' applet: A.class! </p>  
<applet code="Program23.class" height=200 width=320>
No Java?!
</applet>
</html>












JAVA PRACTICALS WRITE  A JAVA  PROGRAM TO  FIND THE SUM  OF ANY NUMBER OF  INTEGERS ENTERED AS  COMMAND LINE ARGUMENT....