5-8 PRACTICALS of Java
5-8 PRACTICALS of Java
Objective
Consider we have a Class of Cars under which Santro Xing, Alto and Wagon R represents
individual Objects. In this context each Car Object will have its own, Model, Year of
Manufacture, Colour, Top Speed, etc. which form Properties of the Car class and the associated
actions i.e., object functions like Create(), Sold(), display() form the Methods of Car Class.
Source code:
class Vehicle
{
String regno;
int model;
Vehicle(String r, int m)
{
regno=r;
model=m;
}
void display()
{
System.out.println("Registration no: "+regno);
System.out.println("Model no: "+model);
}
}
class VehicleDemo
{
public static void main(String arg[])
{
Twowheeler t1;
Threewheeler th1;
Fourwheeler f1;
t1=new Twowheeler("TN74 12345", 1,2);
th1=new Threewheeler("TN74 54321", 4,3);
f1=new Fourwheeler("TN34 45677",5,4);
t1.display();
th1.display();
f1.display();
}
}
}
Output:
Objective
WAP to handle the exception using try and multiple catch block.
Source Code
MultipleCatchBlock1.java
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception
occurs rest of the code
EXPERIMENT-7
Objective
Source Code
class NestTry
{
public static void main(String args[])
{
try
{
int a =
args.length; int b
= 42 / a;
System.out.println("a = " +
a); try
{ // nested try block
if(a==1) a = a/(a-a); // division by zero
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);
}
}
}
Output:
Objective
interface MyInterface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
*/
public void method1();
public void method2();
}
class Demo implements MyInterface
{
/* This class must have to implement both the abstract methods
* else you will get compilation error
*/
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new
Demo(); obj.method1();
}
}
Output:
implementation of method1
EXPERIMENT-9
Objective
Source Code
@Override
public void run() {
System.out.println("Thread has ended");
}
Output:
Hi