Java Programming Preparation

 Unit-3

1) Classify exceptions in Java into checked and unchecked exceptions and give examples for each.

An exception is an abnormal condition that arises in a code at run time. In other words, an exception is a runtime error.  

 


Checked exceptions: A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions.1. ClassNotFoundException: This exception is thrown when the JVM tries to load a class, which is not present in the classpath.    Class.forName("oracle.jdbc.driver.OracleDriver"); 2.IOException: This exception is thrown when the input-output operation in a program fails or is interrupted during the program’s execution.3. FileNotFoundException: This exception is thrown when the program tries to access a file that does not exist or does not open. This error occurs mainly in file handling programs. 

import java.io.*;

class FilenotFoundDemo {  public static void main(String args[]){  File file=new File("E://file.txt");  FileReader fr = new FileReader(file); } } 

Unchecked exceptions: An Unchecked exception is an exception that occurs at the time of execution, these are also called as Runtime Exceptions.1.ArithmeticException: This exception occurs when a program encounters an error in arithmetic operations such as divide by zero

class Test{ public static void main(String[] args) { System.out.println(120/0); }} 

2.ArrayIndexOutOfBoundsException: This exception is thrown when an array is accessed using an illegal index. The index used is either more than the size of the array or is a negative index. Java doesn’t support negative indexing

class Test{ public static void main(String[] args) { int[] a = {10,20,30}; System.out.println(a[10]); }} 

3. NullPointerException: This exception is raised when a null object is referred to in a program. NullPointerException is the most important and common exception in Java.

class Test{ public static void main(String[] args) { String s = null; System.out.println(s.length()); }} 

 

2. Explain Exception Handling mechanism with any of following exceptions.

i. ArithmeticException

ii. ii. ArrayOutOfBoundsException

iii. iii. Null pointer exceptions (with 5 keywords)

Exception handling is the mechanism to handle run time errors, so that the normal flow of application can be maintained.

Exception Handling is managed by using 5 Keywords. 1. try      2. catch     3. throw      4. throws     5. finally  

import java.util.*;

class ExcepDemo {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);

        try {

            args[0] = sc.next(); // num1

            args[1] = sc.next(); // num2

          

 int num1 = Integer.parseInt(arr[0]);

            int num2 = Integer.parseInt(arr[1]);

           

 if (num2 == 0)

                throw new ArithmeticException("Division by zero");

 

            int res = num1 / num2;

            System.out.println("Result: " + res);

 

            System.out.println(arr[2]); // invalid index

        }

        catch (NumberFormatException e) {

            System.out.println("Invalid number format");

        }

        catch (ArithmeticException e) {

            System.out.println("Cannot divide by zero");

        }

        catch (ArrayIndexOutOfBoundsException e) {

            System.out.println("Array index error");

        }

        finally {

            System.out.println("Finally executed");

        }

    }

}

 

3. Demonstrate how can we create own exception with an example program.

class NegativeAgeException extends Exception  {  

                 NegativeAgeException(String s)

                      {  

                           super(s);  

                        }   

public  String toString()

{

return "Age Exception";

}

           }  

 

class ExcepDemo2

     {  

   static void validate(int age) throws NegativeAgeException

   {  

        if(age<0)  

           throw new NegativeAgeException("  not valid  "+age);  

        else  

            System.out.println("  welcome to the world  " +age);  

     }  

  public static void main(String args[])

{  

          try{  

               validate(23);  

validate(-12);

validate(25);  // Not Executed

              }

                    catch(Exception m)

                        {

System.out.println(e);

                         }  

                     finally {

 System.out.println("Finally block executed");

 }

                   System.out.println("rest of the code...");  

                }            }  

 

4. What is the difference between throw and throws keywords?

 

                                                              Unit-4

1. With a neat sketch, explain the life cycle of thread in Java.

A thread in Java is a lightweight process requiring fewer resources.A thread is the smallest unit of execution within a process.


 
i. New:  The thread is in new state when the instance of thread class is created but before the calling of start() method.

ii. Runnable: The thread is in runnable state after the invocation start() method, but the thread scheduler has not selected it to be the running thread. Any number of threads exists in this state.

iii. Running: The thread is in running state when the thread scheduler selects a thread for execution. 

iv. Waiting/blocked/sleeping: this is the state when the thread is still alive but is not eligible currently to run.

v. Terminated: A thread is in terminated or dead state when its run() method exits. 

2. What is Priority? Explain thread priorities in detail with program.

(0R) Multi threading creating 2 threads n execute concurrently.

class NewThread extends Thread { 

NewThread(String name) { super (name);  } 

public void run()

System.out.println("Hello -->"+ getName() + "->"+getPriority() );

 }}  

public class PriorityDemo {  

public static void main(String args[])  {   

Thread t = Thread.currentThread(); 

System.out.println("The main thread priority is: " +t.getPriority()); 

NewThread t1 = new NewThread("One"); 

NewThread t2 = new NewThread("Two"); 

NewThread t3 = new NewThread("Three");

t1.setPriority(Thread.MIN_PRIORITY);

t2.setPriority(Thread.MAX_PRIORITY); 

t3.setPriority(5); 

t1.start(); t2.start(); t3.start(); 

}}  

3. What is thread synchronization and its forms? Explain with an example.

class Table {

    synchronized void printMethod(int n) {

        

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

            System.out.println(n * i);

System.out.println (“Java is object oriented”);

            try { Thread.sleep(300); } catch (Exception e) {}

        }

    }

 

        void printBlock(int n) {

        synchronized (this) {

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

                System.out.println(n * i);

                try { Thread.sleep(300); } catch (Exception e) {}

            }

        }

    }

}

 

class MyThread extends Thread {

    Table t;

    int num;

 

    MyThread(Table t, int num) {

        this.t = t;

        this.num = num;

    }

 

    public void run() {

        t.printMethod(num); // synchronized method

        t.printBlock(num);  // synchronized block

    }

}

 

public class SyncDemo {

    public static void main(String[] args) {

 

        Table t = new Table();

 

        MyThread t1 = new MyThread(t, 5);

        MyThread t2 = new MyThread(t, 6);

 

        t1.start();

        t2.start();

    }

}

 

4. Explain inter thread communication with example program.

Interthread communication is a mechanism in which a thread is paused running in its critical section (synchronized block) and another thread is allowed to enter into the same section. Eg: Producer-Consumer Problem.  

Java Provides Interthread communication by using three methods of Object class. wait() :Makes the current thread wait until another thread notifies it.notify() :Wakes up a single waiting thread.notifyAll() :Wakes up all waiting threads. 

//Producer-Consumer problem ---> Inter Thread Communication.

class Buffer{

int item; 

boolean produced = false;  

synchronized void produce(int x) { 

if(produced) { 

try{  wait(); 

catch(InterruptedException ie) { 


System.out.println("Exception Caught"); 

} }

item =x; 

System.out.println("Producer - Produced-->" +item); 

produced =true; notify(); 

} 

 synchronized int consume(){

if(!produced) {

try{  wait();  }  

catch(InterruptedException ie) {         

System.out.println("Exception Caught " +ie);

} } 

System.out.println("Consumer - Consumed " +item);

produced = false; 

notify(); 

return item;  

}}  

class Producer extends Thread{

Buffer b;  Producer( Buffer b) {

this.b = b; start(); 

} 

public void run() { 

 b.produce(10); b.produce(20);

b.produce(30); b.produce(40);  b.produce(50);  

}}  

class Consumer extends Thread{ 

Buffer b;  

Consumer(Buffer b)  {  

this.b = b;

start();

} 

public void run()  {  

b.consume();  b.consume();  b.consume();  b.consume(); 

}}

public class PCDemo{ 

public static void main(String args[]) { 

Buffer b = new Buffer(); 

 Producer p = new Producer(b); 

Consumer c = new Consumer(b); 

}}

 

                                                                         Unit-5

1) Define ArrayList. Demonstrate ArrayList with Userdefined(Employee)

Objects.

import java.util.*;  

class Employee

{  

           int eid;  

           String ename;  

double sal;  

 

public Employee(int x, String y, double z)

  {  

                 eid=x;

                 ename=y;

                 sal = z;

               }  

       }  

 

public class EmpArrayList{  

            public static void main(String[] args){  

           ArrayList<Employee>  list =new ArrayList<Employee>();  

     //Creating Employees

Employ e1=new Employee(101,"A.Harsha",75000.50);

          Employee e2=new Employee(102,"B.Varsha",85000.50);

          Employee e3=new Employee(103,"C.Sirisha",95000.50);   Employee e4=new Employee(104,"D.Sandeep",195000.50);   

//Adding Employees to list  

list.add(e1);  

list.add(e2);  

list.add(e3);  

list.add(e4);  

//Displaying Number of Employees

System.out.println("\n The number of employees is ->" +list.size());

//Displaying Details of Employees

 System.out.println("\n The employess data is \n");

 for(Employee e:list)

{  

System.out.println(e.eid+":"+e.ename+":"+e.sal);

System.out.println();

          }  

//Deleting an Employee

list.remove(2);

System.out.println("\n After removing number of employees are ->" + list.size());

              //Displaying Details of Employees

System.out.println("\n The employess data after removing is \n");

 for(Employee e:list)

 {  

System.out.println(e.eid+":"+e.ename+":"+e.sal);

 System.out.println();

  }   

       }  

}  

a) Use HashSet methods to perform operations on collection of data.

 

import java.util.*;  

class HashDemo

 {  

  public static void main(String args[])

{  

//Creating HashSet

           HashSet<String> set=new HashSet<String>();  

 

  //Adding Elements to HashSet - ignores duplicates

set.add("hyderabad");

set.add("hyderabad");

           set.add("bangalore");    

           set.add("chennai");   

           set.add("kolkata");  

 set.add("kolkata");  

           set.add("pune");  

           Iterator<String> i=set.iterator();  

           while(i.hasNext())  

           {  

             System.out.println(i.next());  

           }  

//Removing specific element from HashSet  

           set.remove("hyderabad");  

 //Displaying set

System.out.println("\n The list after remove ->" +set);

//adding another set

 HashSet<String> set1=new HashSet<String>();  

           set1.add("Panjab");  

           set1.add("Delhi");  

           set.addAll(set1);  

System.out.println("\n Updated List is ->"+set);  

  //removing new set from list

   set.removeAll(set1);

System.out.println("\n Updated List is ->"+set);  

  //Removing all the elements available in the set  

           set.clear();  

System.out.println("\n After clear the set is ->"+set);  

 

}  

}  

 

Explain the Collection Framework hierarchy in Java

Collections in java is a framework that provides an architecture to store and manipulate, the group of objects. 



Methods of Collection Interface: 

public boolean add(Object element)- It is used to insert an element in this collection.public boolean addAll(Collection c)- It is used to insert the specified collection elements in the invoking collection.

public boolean remove(Object element)- It is used to delete an element from the collection.public boolean removeAll(Collection c)- It is used to delete all the elements of the specified collection from the invoking collection.

public int size()- It returns the total number of elements in the collection.

Public void clear()- It removes the total number of elements from the collection. 

Write a java program on I/O operations on files. (Reading, writing and copying)

import java.io.*; 

class BStream { 

public static void main(String[] args) throws IOException { 

FileInputStream srcstrm = null; 

FileOutputStream trgstrm  = null; 

try { 

srcstrm = new FileInputStream("sourcefile.txt"); 

trgstrm  = new FileOutputStream("targetfile.txt");

int temp;

while (( temp = srcstrm .read()) != -1)

trgstrm.write((byte)temp);

finally {

if (srcstrm != null) 

srcstrm .close();

if (trgstrm  != null) 

trgstrm  .close();

} } } 

 Define StringTokenizer. Explain the purpose of StringTokenizer in the program and how it works.

The java.util.StringTokenizer class : 

It allows you to break a String into tokens. 

import java.util.*;

class StrTknzr{ 

public static void main(String[] args) { 

StringTokenizer str = new StringTokenizer( "My Name is Khanishk"); 

StringTokenizer temp = new StringTokenizer(""); 

int count = str.countTokens(); 

System.out.println(count); 

System.out.println("My Name is Khanishk: "+str.hasMoreTokens()); System.out.println("(Empty String) : "+temp.hasMoreTokens()); 

System.out.println("\nTraversing the String:"); 

while(str.hasMoreTokens()){ 

System.out.println(str.nextElement()); 

} } } 




 


Unit-2

1) Inheritance example program/ Types

Inheritance in java is a mechanism in which one object acquires the properties and behaviors of another object. 


 


2. Dynamic Method Dispatch/Method Overriding/ abstract class/ super keyword

In a class hierarchy, when a method in a subclass has the same  name and type signature as a method in its super class, then the method in subclass is said to override the method in super class.”

abstract class Shape

{

    double base;

                   double hgt;

          Shape(double b , double h)

{

  base = b;

 hgt = h;

            }

         abstract double shapeArea();

         public void display()

{

       System.out.println("dimenstions are " + base  + " ," +hgt);

 }     

}

 

class Triangle extends Shape

{

   Triangle(double b , double h)

            {

               super(b,h);

}

double shapeArea()

{

  return(0.5*base*hgt);

            }

 }

 

class Rectangl extends Shape

{

   Rectangl (double b , double h)

                           {

               super(b,h);

}

 

double shapeArea()

                 {

return(base*hgt);

                                }

}

 

class AreaDemo{

  public static void main(String args[]) {

                Shape t = new Triangle(34.5,89.75);  //upcasting

   t.display();

   System.out.println("The area of triangle is "+t.shapeArea());

   Shape r = new Rectangl(34.5 , 75);  //upcasting

   r.display();

System.out.println("The area of Rectangle is "+r.shapeArea());

 

             }

}

3.User defined packages

Package is a collection of classes, interfaces and subpackages.

package Measure;

public class Converter

{

public float mmtocm(float mm)

{

float cm=(mm/10);

return cm;

}

public float cmtom(float cm)

{

float m=(cm/100);

return m;

}

public float mtokm(float m)

{

float km=(m/1000);

return km;

}

}

 

import Measure.Converter;

public class NeedConverter

{

public static void main(String args[])

{

Converter c=new Converter();

System.out.println(" mm to cm is  "+c.mmtocm(100));

System.out.println(" cm to m is  "+c.cmtom(1000));

System.out.println(" m to km is  "+c.mtokm(3000));

}

}

 

Comments

Popular posts from this blog

Java Programming Syllabus

Unit-I (Introduction to Java)