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:
import java.io.*;
class FilenotFoundDemo {
Unchecked exceptions:
class Test
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{
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{
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.
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.
i. New: The thread is in new state when the instance of thread class is created but before the calling of start() method.
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)
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");
}
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.
Java Provides Interthread communication by using three methods of Object class.
//Producer-Consumer problem ---> Inter Thread Communication.
class Buffer
boolean produced = false;
synchronized void produce(int x)
if(produced)
try{
System.out.println("Exception Caught");
}
System.out.println("Producer - Produced-->" +item);
produced =true;
}
synchronized int consume()
catch(InterruptedException ie)
System.out.println("Exception Caught " +ie);
System.out.println("Consumer - Consumed " +item);
notify();
return item;
}
class Producer extends Thread
}
public void run()
b.produce(10);
}
class Consumer extends Thread
Buffer b;
Consumer(Buffer b)
this.b = b;
public void run()
b.consume();
}
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:
Write a java program on I/O operations on files. (Reading, writing and copying)
import java.io.*;
class BStream {
} } }
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.*;
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("\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
Post a Comment