0% found this document useful (0 votes)
37 views

Java Lab Manual - Final

This document discusses data types and variables in Java, including primitive and non-primitive types, and also covers decision control structures such as if, if-else, if-else-if ladder, and nested if statements; it provides examples of programs using an if statement to check age, an if-else statement to check for a leap year, and if-else-if ladder and nested if statements for a grading system.

Uploaded by

mrout0333
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Java Lab Manual - Final

This document discusses data types and variables in Java, including primitive and non-primitive types, and also covers decision control structures such as if, if-else, if-else-if ladder, and nested if statements; it provides examples of programs using an if statement to check age, an if-else statement to check for a leap year, and if-else-if ladder and nested if statements for a grading system.

Uploaded by

mrout0333
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Gandhi Institute of Excellent Technocrats

Ghangapatna, Bhubaneswar-752054
Odisha
Approved by AICTE, New Delhi|Affiliated to BPUT, Odisha

LAB MANUAL
G
Course: B.Tech
I Branch: Computer Science and Engineering

Semester: 3rd Semester


E Subject: Object Oriented Programming Using Java

T Sub. Code: ROP3B201

Prepared By: Tarini Prasad Pattanaik


LABORATORY MANUAL
ON
OBJECT ORIENTED PROGRAMMING
USING JAVA

Name: ………………………………………
Registration No: .………………………….
Roll No: …………………………………….
Branch: …………………………………….

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


Gandhi Institute of Excellent Technocrats
Bhubaneswar
(Approved by AICTE, New Delhi & Affiliated to BPUT, Odisha )
CONTENTS
EXPT. NO. NAME OF THE EXPERIMENT PAGE NO.

1. Introduction, Compiling & executing a java program. 4

2. Data types & variables, decision control structures: if, 6


nested if etc.

3. Loop control structures: do, while, for etc. 9

4. Classes and objects. 11

5. Data abstraction & data hiding, inheritance, 15


polymorphism.

6. Threads, exception handlings and applet programs 20

7. Interfaces and inner classes, wrapper classes, generics 25

ROP3B201: Object Oriented Programming Using Java Page 3


EXPERIMENT - 1
Name Of The Experiment:
Introduction, Compiling & executing a java program.
Aim of The Experiment:
To study about Introduction, Compiling & executing a java program.
Software Requirement:
Windows 7
Notepad
JDK 8
Hardware Requirement:
Intel Processor
500 GB HDD
2 GB RAM
Theory:

Java is a programming language developed by James Gosling with other team members 1995 for Sun
Microsystems. Java is a high level, robust, object-oriented and secure programming language

JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist.
It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run
those programs which are written in other languages and compiled to Java bytecode.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is
a set of software tools which are used for developing Java applications. It is used to provide the runtime
environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM
uses at runtime.

Installation of Java Software:

This Java Development Kit(JDK) allows to code and run Java programs. It's possible that we can install multiple
JDK versions on the same PC.
1. Download latest Java JDK for your version(32 or 64 bit) of java for Windows
2. Once the download is complete, run the exe for install JDK
Once installation is complete set Environment Variables in Java, Path and Classpath

Environment Variable:
Environment variables basically are strings that contain information such as drive, path, or file name. It points
to the directory where the Java Development Kit (JDK) is installed on your computer.

PATH Setting:

ROP3B201: Object Oriented Programming Using Java Page 4


The PATH variable gives the location of executables like javac, java etc. It is possible to run a program without
specifying the PATH but we will need to give full path of executable like C:\Program Files\Java\jdk1.8.0_131\bin\javac
A.java instead of simple javac A.java

Steps for set PATH & CLASSPATH:


1. Right Click on the My Computer and Select the properties
2. Click on advanced system settings
3. Click on Environment Variables
4. Click on new Button of User variables
5. Type PATH in the Variable name.
6. Copy the path of bin folder which is installed in JDK folder.
7. Paste Path of bin folder in Variable value and click on OK Button.
Note: In case you already have a PATH variable created in your PC, edit the PATH variable to
PATH = <JDK installation directory>\bin;%PATH%;
Here, %PATH% appends the existing path variable to our new value

We can follow a similar process to set CLASSPATH


Note: In case java installation does not work after installation, change classpath to-
CLASSPATH = <JDK installation directory>\lib\tools.jar;

Creation and Running of first Java Program:

1. Open Notepad from Start menu by selecting Programs > Accessories > Notepad.
2. Create a Source Code for Program
 Declare a class with name A.
 Declare the main method public static void main(String args[]){
 Now Type the System.out.println("Hello World"); which displays the text Hello World.

class A{
public static void main(String args[]){
System.out.println("Hello World");
}
}

3. Save the file by using classname.java make sure to select file type as all files while saving the file in our
working folder
4. To Compile the java program open command prompt & write javac A.java
5. To execute the java program write java A

Control flow diagram :

Source Code( .java)  (compiler)  Byte Code( . class)  Load into JVM ( class Loader)  JVM Machine code

Conclusion:

From the above experiment we can know the creation compilation and execution of java program.

ROP3B201: Object Oriented Programming Using Java Page 5


EXPERIMENT - 2
Name Of The Experiment:
Data types & variables, decision control structures: if, nested if.
Aim of The Experiment:
To study about Data types & variables, decision control structures: if, nested if.
Software Requirement:
Windows 7
Notepad
JDK 8
Hardware Requirement:
Intel Processor
500 GB HDD
2 GB RAM
Theory:
Data Type
Data types specify the different sizes and values that can be stored in the variable. There are two types of data types
in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Variables:
A variable is a container which holds the value while the java program is executed. A variable is assigned with
a datatype.
Variable is a name of memory location. There are three types of variables in java:
1. Local
2. instance
3. static.
Dicision Control:
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in java.
1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if statement

Program to demonstrate If statement:


public class Exp2 {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}

ROP3B201: Object Oriented Programming Using Java Page 6


}
Output: Age is greater than 18

Program to check a leap year for demonstrate If-else statement:


public class LeapYearExp {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
}
Output: LEAP YEAR

Program to demonstrate the use of If else-if ladder


Program of grading system for fail, D grade, C grade, B grade, A grade and A+

public class Exp2 {


public static void main(String[] args) {
int marks=65;

if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){

ROP3B201: Object Oriented Programming Using Java Page 7


System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output: C grade

Program to demonstrate the use of Nested If Statement

public class Exp2 {


public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Output: You are eligible to donate blood

Conclusion:
From the above experiment we can know about the Data types, variables, decision control structures: if, nested
if.

ROP3B201: Object Oriented Programming Using Java Page 8


EXPERIMENT - 3
Name Of The Experiment:
Loop control structures: do, while, for etc.
Aim of The Experiment:
To study about Loop control structures: do, while, for etc.
Software Requirement:
Windows 7
Notepad
JDK 8
Hardware Requirement:
Intel Processor
500 GB HDD
2 GB RAM
Theory:
In programming languages, loops are used to execute a set of instructions/functions repeatedly when some
conditions become true. There are three types of loops in java.
1. for loop
2. while loop
3. do-while loop
For Loop:
In for loop We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize
the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It must return boolean value either true or false. It is an
optional condition.
3. Statement: The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional condition.

Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
While Loop:
The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed,
it is recommended to use while loop.
Syntax: while(condition){
//code to be executed
}
Do-while Loop:
The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.

Syntax: do{
//code to be executed

ROP3B201: Object Oriented Programming Using Java Page 9


}while(condition);
Program to print 1 table to demonstrate the use of For Loop
public class ForExp3 {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.print(i);
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10

Program to print 1 to 10 to demonstrate the use of while Loop


public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.print(i);
i++;
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10
Program to print 1 to 10 to demonstrate the use of do-while Loop
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.print(i);
i++;
}while(i<=10);
}
}
Output: 1 2 3 4 5 6 7 8 9 10

Conclusion:
From the above experiment we can know about the Loop control structures: do, while, for.

ROP3B201: Object Oriented Programming Using Java Page 10


EXPERIMENT - 4
Name Of The Experiment:
Classes and objects.
Aim of The Experiment:
To study about Classes and objects.
Software Requirement:
Windows 7
Notepad
JDK 8
Hardware Requirement:
Intel Processor
500 GB HDD
2 GB RAM
Theory:
Class: A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
1. Fields
2. Methods
3. Constructors
4. Blocks
5. Nested class and interface
Object: An object is an instance of a class. In Java it is the physical as well as a logical entity.
An object has three characteristics:
1. State: represents the data (value) of an object.
2. Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
3. Identity: An object identity is typically implemented via a unique ID.
There are 3 ways to initialize object in Java.
1. By reference variable
2. By method
3. By constructor

Program to demonstrate how to define a class and fields


class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}

ROP3B201: Object Oriented Programming Using Java Page 11


}
Output: 0
Null
Program to demonstrate how to create an object and initialize it with reference

class Student{
int id;
String name;
}
class Student2{
public static void main(String args[]){
Student s1=new Student();
s1.id=331;
s1.name="Tarini";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Output: 331 Tarini

Program to demonstrate how to create an object and initialize it with method

class Student{
int rollno;
String name;
void insertData(int r, String n){
rollno=r;
name=n;
}
void displayInfo(){
System.out.println(rollno+" "+name);
}
}
class Student3{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();

ROP3B201: Object Oriented Programming Using Java Page 12


s1.insertData(331,"Kalia");
s2.insertData(332,"Tapu");
s1.displayInfo();
s2.displayInfo();
}
}
Output: 331 Kalia
332 Tapu
Program to demonstrate how to create an object and initialize it with Constructor

class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){
System.out.println(id+" "+name+" "+salary);
}
}
public class Emp {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(331,"Kalia",45000);
e2.insert(332,"Tapu",25000);
e3.insert(333,"Tapan",55000);
e1.display();
e2.display();
e3.display();
}
}
Output: 331 Kalia 45000.0
332 Tapu 25000.0

ROP3B201: Object Oriented Programming Using Java Page 13


333 Tapan 55000.0

Conclusion:
From the above experiment we can know about the class and object creation and initialisation.

ROP3B201: Object Oriented Programming Using Java Page 14


EXPERIMENT - 5
Name Of The Experiment:
Data abstraction & data hiding, inheritance, polymorphism.
Aim of The Experiment:
To study about Data abstraction & data hiding, inheritance, polymorphism.
Software Requirement:
Windows 7
Notepad
JDK 8
Hardware Requirement:
Intel Processor
500 GB HDD
2 GB RAM
Theory:
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism,
and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together
as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only
through the methods of their current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
i. Declare the variables of a class as private.
ii. Provide public setter and getter methods to modify and view the variables values.

Program to demonstrate the encapsulation feature of a OOP


File Name: EncapEx.java
public class EncapEx {
private String name;
private String idNum;
private int age;
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}
}

ROP3B201: Object Oriented Programming Using Java Page 15


Compile the above class : javac EncapEx.java
java EncapEx
File name : Encap.java //( main function)
public class Encap {
public static void main(String args[]) {
EncapEx encap = new EncapEx();
encap.setName("Tapu");
encap.setAge(331);
encap.setIdNum("331f");
System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
}
}
Output: Tapu Age : 331

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With
the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose
properties are inherited is known as superclass (base class, parent class).
extends Keyword - extends is the keyword used to inherit the properties of a class.

Program to demonstrate the inheritance feature of a OOP

File Name: Calculation.java


class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

File Name: Calculation.java


public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);

ROP3B201: Object Oriented Programming Using Java Page 16


demo.multiplication(a, b);
}
}

Compile the above class : javac My_Calculation.java


java My_Calculation
Output:
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

Polymorphism:
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in
OOP occurs when a parent class reference is used to refer to a child class object.
In Java polymorphism is mainly divided into two types:
1. Compile time Polymorphism
2. Runtime Polymorphism
1. Compile time polymorphism: It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.

 Method Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by change
in number of arguments or/and change in type of arguments.
 Operator Overloading: Java also provide option to overload operators. For example, we can
make the operator („+‟) for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator „+‟ when placed between
integer operands, adds them and when placed between string operands, concatenates them.

2. Runtime polymorphism: It is also known as Dynamic Method Dispatch. It is a process in which a


function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved
by Method Overriding.
 Method overriding, on the other hand, occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.

Program to demonstrate the Method Overloading in Polymorphism


// Method Overloading using different type
File Name: MultiplyFun.java
class MultiplyFun {
// Method with 2 parameter
static int Multiply(int a, int b) {
return a * b;
}
// Method with the same name but 2 double parameter
ROP3B201: Object Oriented Programming Using Java Page 17
static double Multiply(double a, double b) {
return a * b;
}
}

File Name: Main1.java


class Main1 {
public static void main(String[] args){
System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}
Compile the above class : javac Main1.java
java Main1
Output: 8
34.65

Program to demonstrate the Operator Overloading in Polymorphism


File Name: OperatorOver.java
class OperatorOver {

void operator(String str1, String str2) {


String s = str1 + str2;
System.out.println("Concatinated String - " + s);
}
void operator(int a, int b) {
int c = a + b;
System.out.println("Sum = " + c);
}
}

File Name: Main1.java


class Main1{
public static void main(String[] args){
OperatorOver obj = new OperatorOver();
obj.operator(2, 3);
obj.operator("Wel", "come");
}
}
Compile the above class : javac Main1.java
java Main1
Output: Sum = 5
Concatinated String – Welcome
ROP3B201: Object Oriented Programming Using Java Page 18
Program to demonstrate the Method Overriding in Polymorphism
File Name: Parent.java
class Parent {
void Print(){
System.out.println("parent class");
}
}
class subclass1 extends Parent {
void Print(){
System.out.println("subclass1");
}
}
class subclass2 extends Parent{
void Print(){
System.out.println("subclass2");
}
}
File Name: TestPolymorphism.java
class TestPolymorphism {
public static void main(String[] args){

Parent a;
a = new subclass1();
a.Print();
a = new subclass2();
a.Print();
}
}
Compile the above class : javac TestPolymorphism.java
java TestPolymorphism
Output: subclass1
subclass2

Conclusion:
From the above experiment we can know about the Encapsulation, Inheritance & Polymorphism.

ROP3B201: Object Oriented Programming Using Java Page 19


EXPERIMENT - 6
Name Of The Experiment:
Threads, exception handling and applet programs.
Aim of The Experiment:
To study about Threads, exception handling and applet programs.
Software Requirement:
Windows 7
Notepad
JDK 8
Hardware Requirement:
Intel Processor
500 GB HDD
2 GB RAM
Theory:

Thread:
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a
shared memory area.
Multithreading in java is a process of executing multiple threads simultaneously.We use multithreading than
multiprocessing because threads use a shared memory area. They don't allocate separate memory area so
saves memory, and context-switching between the threads takes less time than process.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations
at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
a. New:
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method
b. Runnable:
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
c. Running:
The thread is in running state if the thread scheduler has selected it.
d. Non-Runnable (Blocked):
This is the state when the thread is still alive, but is currently not eligible to run.
e. Terminated:
A thread is in terminated or dead state when its run() method exits.
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread class
extends Object class and implements Runnable interface.

ROP3B201: Object Oriented Programming Using Java Page 20


Commonly used Constructors of Thread class:
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.

Program to demonstrate the threading using Thread class


Java Thread Example by extending Thread class
File Name: Multi.java
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Compile the above class : javac Multi.java
java Multi
Output: thread is running...

Program to demonstrate the threading implementing Runnable interface


Java Thread Example by implementing Runnable interface
File Name: Multi1.java
class Multi1 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi1 m1=new Multi1();
Thread t1 =new Thread(m1);
t1.start();
}
}
Compile the above class : javac Multi1.java
java Multi1
Output: thread is running...

ROP3B201: Object Oriented Programming Using Java Page 21


Exception Handling:
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so
that normal flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the
unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1. Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-
time.
2. Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
Java Exception Keywords
1. try : The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.
2. catch : The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
3. finally : The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.
4. throw : The "throw" keyword is used to throw an exception.
5. throws : The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.

Program to demonstrate the Exception Handling Program


File Name: TryCatchExample.java
public class TryCatchExample {
public static void main(String[] args) {
try {
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e){
System.out.println(e);
}

ROP3B201: Object Oriented Programming Using Java Page 22


}
}
Compile the above class : javac TryCatchExample.java
java TryCatchExample
Output: java.lang.ArithmeticException: / by zero

APPLET:
Applet is a Java program that can be embedded into a web page. It runs inside the web browser and works at
client side. Applet is embedded in a HTML page using the APPLET or OBJECT tag and hosted on a web
server.
Applets are used to make the web site more dynamic and entertaining.
Life cycle of an applet :
When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can
be used for drawing oval, rectangle, arc etc.

How to run an applet:


1. An applet can be executed by using browser (By html file).

In this case we have to define an html page with <applet code > ……… </applet>. This tag will link
the applet program and the size of its window. When this html file is opened using browser then the applet is
executed.
2. By appletViewer tool ( for Testing purpose)

ROP3B201: Object Oriented Programming Using Java Page 23


Program to demonstrate the applet
File Name: First.java
import java.awt.*;
import java.applet.*;
public class First extends Applet{
public void paint(Graphics g){
g.drawString(“Welcome to applet”,150,150);
}
}
/* <applet code= “First.class” width=”300” height=”300”>
</applet>
*/
Compile the above applet : Write in command prompt
C:\> javac First.java
C:]> appletviewer First.java
Output: Welcome to applet

Conclusion:
From the above experiment we can know about the Threads, exception handlings and applet programs.

ROP3B201: Object Oriented Programming Using Java Page 24


EXPERIMENT - 7
Name Of The Experiment:
Interfaces and inner classes, wrapper classes, generics.
Aim of The Experiment:
To study about Interfaces and inner classes, wrapper classes, generics.
Software Requirement:
Windows 7
Notepad
JDK 8
Hardware Requirement:
Intel Processor
500 GB HDD
2 GB RAM
Theory:
Interface:
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the
Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
There are mainly three reasons to use interface. They are given below.
1. By interface, we can support the functionality of multiple inheritance.
2. It can be used to achieve loose coupling.
3. Interfaces are used to implement abstraction.

So the question arises why use interfaces when we have abstract classes?

The reason is, abstract classes may contain non-final variables, whereas variables in interface are final,
public and static.

Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}

Program to demonstrate the working of interface


File Name: testClass.java
import java.io.*;
interface interf { // A simple interface
final int a = 331; // public, static and final
void display(); // public and abstract
}
class testClass implements interf{ // A class that implements interface.
public void display(){
System.out.println("Welcome");
}

ROP3B201: Object Oriented Programming Using Java Page 25


public static void main (String[] args){
testClass t = new testClass();
t.display();
System.out.println(a);
}
}
Compile the above code : javac testClass.java
java testClass
Output: Welcome
331

Inner Class:
Inner class or nested class is a class which is declared inside the class or interface. We use inner
classes to logically group classes and interfaces in one place so that it can be more readable and
maintainable.
Additionally, it can access all the members of outer class including private data members and methods.

Advantage of java inner classes


There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (data
members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group
classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
Syntax:
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Program to demonstrate the inner class
File Name: Myclass.java
class Outer_Demo{
int num;
private class Inner_Demo{ // inner class
public void print() {
System.out.println("Welcome to GIET");
}
}
void display_Inner(){
Inner_Demo inner = new Inner_Demo();
inner.print();

ROP3B201: Object Oriented Programming Using Java Page 26


}
}

public class Myclass {


public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner();
}
}

Compile the above code : javac Myclass.java


java Myclass
Output: Welcome to GIET

Wrapper Class:
The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into
primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and
vice-versa unboxing.

Need of Wrapper Classes

1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments
passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.

Autoboxing and Unboxing

Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is
known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class
to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to
long, Double to double etc.

Program to demonstrate the Wrapper Class


File Name: Test.java

ROP3B201: Object Oriented Programming Using Java Page 27


public class Test {
public static void main(String args[]) {
Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to a int
System.out.println(x);
}
}
Compile the above code : javac Test.java
java Test
Output: 15

Generics in Java:
Generics in Java is similar to templates in C++. The Java Generics programming is introduced in
J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store
other objects.
2) Type casting is not required: There is no need to typecast the object.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
Program to demonstrate the Generic
File Name: GenericMethodTest.java
public class GenericMethodTest {
// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}

public static void main(String args[]) {


// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");


printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");

ROP3B201: Object Oriented Programming Using Java Page 28


printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");


printArray(charArray); // pass a Character array
}
}

Compile the above code : javac GenericMethodTest.java


java GenericMethodTest
Output:

Array integerArray contains:


12345
Array doubleArray contains:
1.1 2.2 3.3 4.4
Array characterArray contains:
HELLO

Conclusion:
From the above experiment we can know about the Interfaces and inner classes, wrapper classes, generics.

ROP3B201: Object Oriented Programming Using Java Page 29

You might also like