0% found this document useful (0 votes)
19 views82 pages

OOPM Lab Manual

Uploaded by

deltagaming56432
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views82 pages

OOPM Lab Manual

Uploaded by

deltagaming56432
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 82

Computer Engineering /SSJCET, Asangaon

EXPERIMENT NO: 1

Aim: Program on accepting input through keyboard.

Learning Objectives:
2.1 Intellectual Skills:
Understand the how use the class and object in java programming.
Understand the various keys used in java programming.
2.2Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
3.1HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus


Theory:
Prior Concepts:
What is Java?

Java is a programming language and a platform.

Platform Any hardware or software environment in which a program runs, known


as a platform. Since Java has its own Runtime Environment (JRE) and API, it is
called platform.

How to set path in Java

The path is required to be set for using tools such as javac, java etc.

If you are saving the java source file inside the jdk/bin directory, path is not
required to be set because all the tools will be available in the current directory.

But If you are having your java file outside the jdk/bin folder, it is necessary to set
path of JDK.
OOPM JAVA /CSL 304 / Sem- III Page 1
Computer Engineering /SSJCET, Asangaon

There are 2 ways to set java path:

1. temporary
2. permanent
1) How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:

 Open command prompt


 copy the path of jdk/bin directory
 write in command prompt: set path=copied path
2) How to set Permanent Path of JDK in Windows

For setting the permanent path of JDK, you need to follow these steps:

 Go to MyComputer properties -> advanced tab -> environment variables ->


new tab of user variable -> write path in variable name -> write path of bin
folder in variable value -> ok -> ok -> ok

Features of Java

There is given many features of java. They are also known as java buzzwords. The
Java Features given below are simple and easy to understand.

1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10.High Performance
11.Multithreaded
12.Distributed
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that
OOPM JAVA /CSL 304 / Sem- III Page 2
Computer Engineering /SSJCET, Asangaon

provides runtime environment in which java bytecode can be executed.


JVMs are available for many hardware and software platforms. JVM, JRE and JDK
are platform dependent because configuration of each OS differs. But, Java is
platform independent.
The JVM performs following main tasks:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime
environment.It is the implementation of JVM.It physically exists.It contains set of
libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun
Micro Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.

BASIC JAVA PROGRAM:-

class Simple{

public static void main(String args[]){

System.out.println("Hello Java");

}
Java Program:

PROGRAM:-
//import Scanner as we require it.
import java.util.Scanner;

OOPM JAVA /CSL 304 / Sem- III Page 3


Computer Engineering /SSJCET, Asangaon

// the name of our class its public


public class SimpleInterest {
//void main
public static void main (String[] args)
{
//declare float
float a,y,r,si,t;
//define scanner
Scanner input = new Scanner(System.in);

//print message and take input.


System.out.println("Enter Amount:");
a = input.nextFloat();

System.out.println("Enter Years");
y = input.nextInt();

System.out.println("Enter Rate of interest");


r = input.nextFloat();

//<span class="IL_AD" id="IL_AD1">calculate</span>


si=a*y*r/100;
t=a+si;

//print the output


System.out.println("Simple interest = "+si);
System.out.println("Total = " + t);
}
}

Procedure for doing the experiment:

Step
Details of the step
no.
1.
Compile the Java program using javac compiler.

2. Run the java Program using JVM(Interpreter).

OOPM JAVA /CSL 304 / Sem- III Page 4


Computer Engineering /SSJCET, Asangaon

Result:
Enter Amount:
1000
Enter Years
2
Enter Rate of interest
3
Simple interest = 60.0
Total = 1060.0

Conclusion:
Here we understand the basic java program, how we use class in java and how make
the object here.

Questions:
1. Write java program for find the Armstrong number from 2 numbers
2. Write java program to show first 10 prime numbers.
3. Understand the class and Object.

10.0 Student Activity:


(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.

11.0 Related Links:


www.javatpoint.com

www.tutorialspoint.com

www.stackoverflow.com --
If error occurs in program then this site helps you to solve error in your program

EXPERIMENT NO: 2

Aim : Programs on Basic programming constructs like branching and looping.

OOPM JAVA /CSL 304 / Sem- III Page 5


Computer Engineering /SSJCET, Asangaon

THEORY :

Branching statements are used to change the flow of execution from one section of a
program to another. Branching statements are typically utilized within control
statements. Java includes three types of branching statements: continue, break, and
return. When a given condition is met, we can depart from a control statement
using branching statements.

In Java, the continue and break statements are two key branching statements that are
used in conjunction with the control statements. The break statement ends or breaks
the loop and moves control outside of it. The continue command skips the current
execution and returns control to the loop's beginning. The return statement returns a
value from a method and does so openly.

The break Statement

The break statement is used to abruptly exit a loop or switch statement.

In a for, while, or do-while loop: It ends the loop's execution instantly, enabling the
program to proceed with the code after the loop.

In a switch statement, it quits the switch block, preventing further case blocks from
being executed.

OOPM JAVA /CSL 304 / Sem- III Page 6


Computer Engineering /SSJCET, Asangaon

Syntax
while (true) {
// Code here
if (condition) {
break; // Exit the loop
}
}

The continue Statement

The continue statement is used to skip the current loop iteration and go to the next.

It is commonly used within loops such as for, while, or do-while.

When this happens, it skips the remaining code in the current iteration and moves on
to the next.

Syntax

control-flow-statement;
continue;

for (int i = 0; condition; increment) {


if (condition) {
continue; // Skip this iteration and go to the next one
}
// Code here
}

The return Statement

OOPM JAVA /CSL 304 / Sem- III Page 7


Computer Engineering /SSJCET, Asangaon

The return statement is used to quit a method and, if desired, return a value to the
caller.

It defines the value that the method should return (if the method has a return type).

It also causes the function to quit instantly, bypassing any code that comes after the
method's return statement.

Syntax

return value;
public int add(int a, int b) {
return a + b; // Return the result and exit the method
}

Example1:

BranchingStatements.java

public class BranchingStatements {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int num : numbers) {
if (num == 5) {
break; // Exit the loop when num is 5 }
System.out.println(num);
}
}
}

Output:

OOPM JAVA /CSL 304 / Sem- III Page 8


Computer Engineering /SSJCET, Asangaon

1
2
3
4

Loops in Java
Loops are a block of code that executes itself until the specified condition becomes
false. In this section, we will look in detail at the types of loops used in Java
programming.

Types of Loops in Java


There are three types of "Loops" in Java.
1. for loop
2. while loop
3. do while loop

1. For loop in Java


 For loop primarily depends on the three major sections index of the control
statement which are the "declaration", "conditions" and "update" statements.
 This particular loop statement generates iteration over a "collection of
values". That can be the same value or can be different.
 For loop is generally used when the user knows the exact number of
iterations.
 There are various types of "For loop" which are "Empty For Loop", "Infinite
For Loop", and "For each loop".

OOPM JAVA /CSL 304 / Sem- III Page 9


Computer Engineering /SSJCET, Asangaon

For loop flowchart explanation

 Initialization condition: Here, the variable in use is initialized. It is the


beginning of a for loop. An already declared variable can be used or a
variable can be declared, local to loop only.
 Test Condition: It is used for testing the exit condition for a loop. It must
return a boolean value. For loop is an entry-controlled loop as the condition is
checked before the execution of the loop statements.
 Statement execution: Once the condition is evaluated to be true, the
statements in the loop body are executed.
 Update Statement: It is used for updating or incrementing/decrementing the
variable for the next iteration.
 Loop termination: When the condition becomes false, the loop terminates
marking the end of the for loop.

Java For loop Syntax

for (initialization; termination condition; increment/decrement)


{
//Set of statements to be executed repeatedly
}

OOPM JAVA /CSL 304 / Sem- III Page 10


Computer Engineering /SSJCET, Asangaon

While loop in Java

 While Loop is also an iteration statement that can iterate over various types of
values.
 After accepting the condition While loop evaluates it to a "boolean value".
 Execute a particular statement or a block of the statement until it generates
"false".
 While loop is used when the user is not aware of the exact iteration number.
 There are various types of while loops; those are "Empty While Loop", and
"Infinite While Loops".

While loop flowchart explanation

 Test Condition: It is used for testing the exit condition for a loop. It must
return a boolean value. While loop is an entry-controlled loop as the condition
is checked before the execution of the loop statements.
 Statement execution: Once the condition is evaluated to be true, the
statements in the loop body are executed. Normally the statements contain an
update value for the variable being processed for the next iteration.
 Loop termination: When the condition becomes false, the loop terminates
marking the end of the while loop.

OOPM JAVA /CSL 304 / Sem- III Page 11


Computer Engineering /SSJCET, Asangaon

Java While loop Syntax

//initialization
while (condition)
{
//Execute a set of statements
//increment
}

Do…while loops in Java

 Do while loop works the same as while loop but it only generates the
expression only after the execution of the code block has been done. The
concept of Abstraction in Java can be applied to understand the Do-While
loop better
 This statement first executes the statement under "do" after that it checks the
condition of "while".
 This statement executes at least once even though the statement generates a
"false" value.
 Do while loop is an "exit control loop".
 There is only one type of “Do while loop” which is called "Infinite Do While
Loop".

OOPM JAVA /CSL 304 / Sem- III Page 12


Computer Engineering /SSJCET, Asangaon

Do...While loop flowchart explanation

 Statement execution: The loop starts with the execution of the statement(s).
There is no checking of any condition for the first time.
 Test Condition: After the statements execution step, the condition is checked
for true or false value. If it is evaluated to be true, the next iteration of the
loop starts.
 Loop termination: When the condition becomes false, the loop terminates
marking the end of the do...while loop.

Java Do-While loop Syntax

do
{
//statements to be iterated
}
while(conditions)

Example : Java program to find the sum of positive numbers

// Java program to find the sum of positive numbers


import java.util.Scanner;

class Main {
public static void main(String[] args) {

int sum = 0;

// create an object of Scanner class


Scanner input = new Scanner(System.in);

OOPM JAVA /CSL 304 / Sem- III Page 13


Computer Engineering /SSJCET, Asangaon

// take integer input from the user


System.out.println("Enter a number");
int number = input.nextInt();
// while loop continues
// until entered number is positive
while (number >= 0) {
// add only positive numbers
sum += number;

System.out.println("Enter a number");
number = input.nextInt();
}
System.out.println("Sum = " + sum);
input.close();
}
}

Output

Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39

CONCLUSION : Thus we have performed practical on branching and looping


statements in Java.

OOPM JAVA /CSL 304 / Sem- III Page 14


Computer Engineering /SSJCET, Asangaon

EXPERIMENT NO: 3

Aim : Programs on class and objects

Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
Understand the order by java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.

Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

SOFTWARE REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus

Theory:
Prior Concept:

Object in Java

An entity that has state and behavior is known as an object e.g. chair, bike, marker,
pen, table, car etc. It can be physical or logical (tengible and intengible). The
example of integible object is banking system.

OOPM JAVA /CSL 304 / Sem- III Page 15


Computer Engineering /SSJCET, Asangaon

An object has three characteristics:

 state: represents data (value) of an object.


 behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. But,it is used internally by the
JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects
are created
Class
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.

A class in java can contain:

 data member
 method
 constructor
 block
 class and interface
Syntax to declare a class:

1. class <class_name>{
2. data member;
3. method;
4. }

static keyword

The static keyword is used in java mainly for memory management. We may apply
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.

The static can be:

OOPM JAVA /CSL 304 / Sem- III Page 16


Computer Engineering /SSJCET, Asangaon

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

Java Program:
/* Palindrome Program In JAVA
*/
import java.util.Scanner;
class Palindrome{
public static void main(String args[]){
System.out.print("Enter Number: ");
Scanner read = new Scanner(System.in);
int num = read.nextInt();
int n = num;
//reversing number
int rev=0,rmd;
while(num > 0)
{
rmd = num % 10;
rev = rev * 10 + rmd;
num = num / 10;
}
if(rev == n)
System.out.println(n+" is a Palindrome Number!");
else
System.out.println(n+" is not a Palindrome Number!");
}}

Procedure for doing the experiment:

1. 2.
Compile the Java program using javac compiler.

2. Run the java Program using JVM(Interpreter).

OOPM JAVA /CSL 304 / Sem- III Page 17


Computer Engineering /SSJCET, Asangaon

Result:

Conclusion:
Here understand the how java scanner class used with the help of package, and how
set the data to the objects in java program.

Questions:

OOPM JAVA /CSL 304 / Sem- III Page 18


Computer Engineering /SSJCET, Asangaon

1. Write java program for check number is palindrome or not.


2. Write java program to check the Armstrong number.
3. Understand the how use scanner class from package.

10.0 Student Activity:


(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com

www.tutorialspoint.com

www.stackoverflow.com -- If error occurs in program then this site helps you to


solve error in your program

OOPM JAVA /CSL 304 / Sem- III Page 19


Computer Engineering /SSJCET, Asangaon

EXPERIMENT NO: 4

Aim : Program on 2D array, strings functions

Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.

Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

SOFTWARE REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus

Theory:
Prior Concept:

Java Array

Normally, array is a collection of similar type of elements that have contiguous


memory location.

Java array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed set of elements
in a java array.

Array in java is index based, first element of the array is stored at 0 index.

OOPM JAVA /CSL 304 / Sem- III Page 20


Computer Engineering /SSJCET, Asangaon

Advantage of Java Array

 Code Optimization: It makes the code optimized, we can retrieve or sort the
data easily.
 Random access: We can get any data located at any index position.

Disadvantage of Java Array

 Size Limit: We can store only fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used
in java.



Different Ways To Declare And Initialize 2-D Array in Java

An array with more than one dimension is known as a multi-dimensional array.


The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We
can say that any higher dimensional array is basically an array of arrays. A very
common example of a 2D Array is Chess Board. A chessboard is a grid containing
64 1×1 square boxes. You can similarly visualize a 2D array. In a 2D array, every
element is associated with a row number and column number. Accessing any
element of the 2D array is similar to accessing the record of an Excel File using
both row number and column number. 2D arrays are useful while implementing a
Tic-Tac-Toe game, Chess, or even storing the image pixels.

OOPM JAVA /CSL 304 / Sem- III Page 21


Computer Engineering /SSJCET, Asangaon

There are two types of array.

 Single Dimensional Array


 Multidimensional Array
Single Dimensional Array in java
Syntax to Declare an Array in java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in java

1. arrayRefVar=new datatype[size];

Declaring 2-D array in Java:

Any 2-dimensional array can be declared as follows:


Syntax: data_type array_name[][]; (OR) data_type[][] array_name;

 data_type: Since Java is a statically-typed language (i.e. it expects its variables


to be declared before they can be assigned values). So, specifying the datatype
decides the type of elements it will accept. e.g. to store integer values only, the
data type will be declared as int.
 array_name: It is the name that is given to the 2-D array. e.g. subjects,
students, fruits, department, etc.

OOPM JAVA /CSL 304 / Sem- III Page 22


Computer Engineering /SSJCET, Asangaon

import java.io.*;

class GFG {

public static void main(String[] args)

int rows = 80, columns = 5;

int[][] marks = new int[rows][columns];

// initializing the array elements using for loop

for (int i = 0; i < rows; i++) {

for (int j = 0; j < columns; j++) {

marks[i][j] = i + j;

// printing the first three rows of marks array

System.out.println("First three rows are: ");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < columns; j++) {

OOPM JAVA /CSL 304 / Sem- III Page 23


Computer Engineering /SSJCET, Asangaon

System.out.printf(marks[i][j] + " ");

System.out.println();

Output

First three rows are:


01234
12345
23456

Java String

In Java, string is basically an object that represents sequence of char values.


An array of characters works same as Java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);

is same as:

String s="javatpoint";

OOPM JAVA /CSL 304 / Sem- III Page 24


Computer Engineering /SSJCET, Asangaon

Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.

The java.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

Java String Example

StringExample.java

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

Output:

java
strings
example

Conclusion:
Here understand the concept about the working of array and string in java.
Questions:

1. Write java program for add data into the arraylist.


2. Write java program for remove data from arraylist.

OOPM JAVA /CSL 304 / Sem- III Page 25


Computer Engineering /SSJCET, Asangaon

Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.

Related Links:
www.javatpoint.com

www.tutorialspoint.com

www.stackoverflow.com -- If error occurs in program then this site helps you to


solve error in your program

OOPM JAVA /CSL 304 / Sem- III Page 26


Computer Engineering /SSJCET, Asangaon

EXPERIMENT NO: 5

Aim of the Experiment: Program on method and constructor overloading.

Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.

Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

SOFTWARE REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus

Theory:
Prior Concept:

Method Overloading in Java

If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs. So,
we perform method overloading to figure out the program quickly.

Advantage of method overloading?


OOPM JAVA /CSL 304 / Sem- III Page 27
Computer Engineering /SSJCET, Asangaon

Method overloading increases the readability of the program.


Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In java, Method Overloading is not possible by changing the return type of the
method.

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding. In other words, If subclass provides the specific
implementation of the method that has been provided by one of its parent class, it is
known as Method Overriding.
Advantage of Java Method Overriding

 Method Overriding is used to provide specific implementation of a method


that is already provided by its super class.
 Method Overriding is used for Runtime Polymorphism
Rules for Method Overriding

1. method must have same name as in the parent class


2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Java Program:
Example of Method Overloading by changing the no. of arguments

1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9. }
10. }
OOPM JAVA /CSL 304 / Sem- III Page 28
Computer Engineering /SSJCET, Asangaon

Method Overriding program:


1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10.}

Procedure for doing the experiment:

1 Compile the Java program using javac compiler.

2. Run the java Program using JVM(Interpreter).

Result:

Method overloading output: 30


40

Method Overriding output: Bike is running safely

OOPM JAVA /CSL 304 / Sem- III Page 29


Computer Engineering /SSJCET, Asangaon

Constructor overloading in Java

In Java, we can overload constructors like methods. The constructor overloading


can be defined as the concept of having more than one constructor with different
parameters so that every constructor can perform a different task.

Consider the following Java program, in which we have used different constructors
in the class.

Example
public class Student {
//instance variables of the class
int id;
String name;

Student(){
System.out.println("this a default constructor");
}

Student(int i, String n){


id = i;
name = n;
}

public static void main(String[] args) {


//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

System.out.println("\nParameterized Constructor values: \n");


Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}

OOPM JAVA /CSL 304 / Sem- III Page 30


Computer Engineering /SSJCET, Asangaon

Output:

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

Student Id : 10
Student Name : David

In the above example, the Student class constructor is overloaded with two different
constructors, I.e., default and parameterized.

Conclusion:
Here understand the concept method overloading and method overloading.

Questions:
1.Write java program method overloading.
2. Write java program method overriding.

Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com

www.tutorialspoint.com

OOPM JAVA /CSL 304 / Sem- III Page 31


Computer Engineering /SSJCET, Asangaon

www.stackoverflow.com -- If error occurs in program then this site helps you to


solve error in your program

EXPERIMENT NO: 6

OOPM JAVA /CSL 304 / Sem- III Page 32


Computer Engineering /SSJCET, Asangaon

Aim: Program on String Buffer and Vectors

Learning Objectives:
Intellectual Skills:
Understand the different methods and functions in java program.
Motor Skills:
Ability to learn how develops the Java program in details.
Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

SOFTWARE REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus

Theory:
Prior Concept:

VECTOR:-

Vector implements a dynamic array. It is similar to ArrayList, but with two


differences:

 Vector is synchronized.

 Vector contains many legacy methods that are not part of the collections
framework.

Vector proves to be very useful if you don't know the size of the array in advance or
you just need one that can change sizes over the lifetime of a program.

The Vector class supports four constructors. The first form creates a default vector,
which has an initial size of 10:
Vector( )

The second form creates a vector whose initial capacity is specified by size:
OOPM JAVA /CSL 304 / Sem- III Page 33
Computer Engineering /SSJCET, Asangaon

Vector(int size)

The third form creates a vector whose initial capacity is specified by size and whose
increment is specified by incr. The increment specifies the number of elements to
allocate each time that a vector is resized upward:
Vector(int size, int incr)

The fourth form creates a vector that contains the elements of collection c:
Vector(Collection c)

Java Program:
import java.util.*;
class TestVector1{

public static void main(String args[]){

Vector<String> v=new Vector<String>();//creating vector

v.add("umesh");//method of Collection v.addElement("irfan");//method of


Vector v.addElement("kumar");

//traversing elements using Enumeration

Enumeration e=v.elements(); while(e.hasMoreElements()){

System.out.println(e.nextElement());
}
}

Procedure for doing the experiment:

1 Compile the Java program using javac compiler.

2. Run the java Program using JVM(Interpreter).

OOPM JAVA /CSL 304 / Sem- III Page 34


Computer Engineering /SSJCET, Asangaon

Result:

Output: umesh,
Irfan, kumar

StringBuffer Class

StringBuffer is a class in Java that represents a mutable sequence of characters. It


provides an alternative to the immutable String class, allowing you to modify the
contents of a string without creating a new object every time.

Here are some important features and methods of the StringBuffer class:
 StringBuffer objects are mutable, meaning that you can change the contents of
the buffer without creating a new object.
 The initial capacity of a StringBuffer can be specified when it is created, or it
can be set later with the ensureCapacity() method.
 The append() method is used to add characters, strings, or other objects to the
end of the buffer.
 The insert() method is used to insert characters, strings, or other objects at a
specified position in the buffer.
 The delete() method is used to remove characters from the buffer.
 The reverse() method is used to reverse the order of the characters in the buffer.
Here is an example of using StringBuffer to concatenate strings:

public class StringBufferExample {

OOPM JAVA /CSL 304 / Sem- III Page 35


Computer Engineering /SSJCET, Asangaon

public static void main(String[] args)


{
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" ");
sb.append("world");
String message = sb.toString();
System.out.println(message);
}
}

Output
Hello world

Conclusion:
Here understand the concept vector with the practically did program in vector.

Questions:
1. Write java program to add data into vector dataset.
2. Write java program to remove data into vector dataset.
Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.
Related Links:
www.javatpoint.com

www.tutorialspoint.com

www.stackoverflow.com -- If error occurs in program then this site helps you to


solve error in your program

OOPM JAVA /CSL 304 / Sem- III Page 36


Computer Engineering /SSJCET, Asangaon

EXPERIMENT NO: 7

Aim : Program on types of inheritance

Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.

Apparatus:
REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus

Theory:
Prior Concept:

Inheritance in Java

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

The idea behind inheritance in java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as Parent-Child


relationship.

OOPM JAVA /CSL 304 / Sem- III Page 37


Computer Engineering /SSJCET, Asangaon

Why use Inheritance?

 For Method Overriding (So Runtime Polymorphism).


 For Code Reusability.
Syntax of Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical. In java programming, multiple and hybrid
inheritance is supported through interface only. We will learn about interfaces
later.

OOPM JAVA /CSL 304 / Sem- III Page 38


Computer Engineering /SSJCET, Asangaon

Single Inheritance

When a class inherits another class, it is known as a single inheritance. In the


example given below, Dog class inherits the Animal class, so there is the single
inheritance.

File: TestInheritance.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

OOPM JAVA /CSL 304 / Sem- III Page 39


Computer Engineering /SSJCET, Asangaon

Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you


can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

OOPM JAVA /CSL 304 / Sem- III Page 40


Computer Engineering /SSJCET, Asangaon

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical


inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.

File: TestInheritance3.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...

8.0 Conclusion:
Here understand the concept about the inheritance, polymorphism, encapsulation,
and abstraction in java.

9.0 Questions:
OOPM JAVA /CSL 304 / Sem- III Page 41
Computer Engineering /SSJCET, Asangaon

1. Write java program for show the inheritance.


2. Write java program for show the polymorphism.
3. Write java program for show the abstraction.
4. Write java program for show the encapsulation.

10.0 Student Activity:


(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com

www.tutorialspoint.com

www.stackoverflow.com -- If error occurs in program then this site helps you to


solve error in your program

EXPERIMENT NO: 8

OOPM JAVA /CSL 304 / Sem- III Page 42


Computer Engineering /SSJCET, Asangaon

Aim: Program on Multiple Inheritance (Interface)

Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.

Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

SOFTWARE REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus


Theory:
Prior Concept:

Interface in Java

An interface in java is a blueprint of a class. It has static constants and abstract


methods only.

The interface in java is a mechanism to achieve fully abstraction. There can be


only abstract methods in the java interface not method body. It is used to achieve
fully abstraction and multiple inheritances in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.

 It is used to achieve fully abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.

OOPM JAVA /CSL 304 / Sem- III Page 43


Computer Engineering /SSJCET, Asangaon

The java compiler adds public and abstract keywords before the interface method
and public, static and final keywords before data members.

In other words, Interface fields are public, static and final bydefault, and methods
are public and abstract.

Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface.

OOPM JAVA /CSL 304 / Sem- III Page 44


Computer Engineering /SSJCET, Asangaon

Java Program:
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print()
{System.out.println("Hello");}
6.
7. public static void main(String args[]
){ A6 obj = new A6();
8. obj.print(); } }

Procedure for doing the experiment:

1 Compile the Java program using javac compiler.

3. Run the java Program using JVM(Interpreter).

Result:

Output: Hello

Conclusion:
Here understand the concept of Interface and how we use interface in java program.

OOPM JAVA /CSL 304 / Sem- III Page 45


Computer Engineering /SSJCET, Asangaon

Questions:
1. Write java program to using interface methods create class and derived
that methods.

Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com

www.tutorialspoint.com

www.stackoverflow.com -- If error occurs in program then this site helps you to


solve error in your program

EXPERIMENT NO: 9
Aim : Program on Multithreading

Learning Objectives:

OOPM JAVA /CSL 304 / Sem- III Page 46


Computer Engineering /SSJCET, Asangaon

2.1 Intellectual Skills:


Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.

Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

SOFTWARE REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus

Theory:
Prior Concept:

Multithreading in Java

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common


memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.


Advantage of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.

2) You can perform many operations together so it saves time.

OOPM JAVA /CSL 304 / Sem- III Page 47


Computer Engineering /SSJCET, Asangaon

3) Threads are independent so it doesn't affect other threads if exception occur in a


single thread.
What is Thread in java

A thread is a lightweight sub process, a 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 shares a common memory area.

OOPM JAVA /CSL 304 / Sem- III Page 48


Computer Engineering /SSJCET, Asangaon

As shown in the above figure, thread is executed inside the process. There
is context-switching between the threads. There can be multiple
processes inside the OS and one process can have multiple threads. Life
cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in
thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state.

But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are
as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.

OOPM JAVA /CSL 304 / Sem- III Page 49


Computer Engineering /SSJCET, Asangaon

2) 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.
3) Running

The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated

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

How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.
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.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:

 A new thread starts(with new callstack).


 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method will run.

OOPM JAVA /CSL 304 / Sem- III Page 50


Computer Engineering /SSJCET, Asangaon

1)By extending Thread class:

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }
Output:thread is running...
Who makes your class object as thread object?
Thread class constructor allocates a new thread object.When you create object of
Multi class,your class constructor is invoked(provided by Compiler) fromwhere
Thread class constructor is invoked(by super() as first statement).So your Multi class
object is thread object now.
2)By implementing the Runnable interface:

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11.}
Output:thread is running...

Java Program:
Multithreading Program

class RunnableDemo implements


Runnable {
private Thread t;

OOPM JAVA /CSL 304 / Sem- III Page 51


Computer Engineering /SSJCET, Asangaon

private String threadName;


RunnableDemo( String name){
threadName = name;
System.out.println("Creating " +
threadName );
}
public void run() {
System.out.println("Running " +
threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " +
threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " +
threadName + " interrupted.");
}
System.out.println("Thread " +
threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " +
threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

public class TestThread {


public static void main(String args[]) {

OOPM JAVA /CSL 304 / Sem- III Page 52


Computer Engineering /SSJCET, Asangaon

RunnableDemo R1 = new
RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new
RunnableDemo( "Thread-2");
R2.start();
} }

Procedure for doing the experiment:

1 Compile the Java program using javac compiler.

4. Run the java Program using JVM(Interpreter).


Result:

Output:Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
OOPM JAVA /CSL 304 / Sem- III Page 53
Computer Engineering /SSJCET, Asangaon

Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Conclusion:
Here understand the concept of thread and multithreading in java programming .

Questions:
1. Write java program to create thread using Runnable interface and
second extends thread class.

Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com

www.tutorialspoint.com

www.stackoverflow.com -- If error occurs in program then this site helps you to


solve error in your program

EXPERIMENT NO: 10

OOPM JAVA /CSL 304 / Sem- III Page 54


Computer Engineering /SSJCET, Asangaon

Aim : Program on Packages.

Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.
2.2Motor Skills:
Ability to learn how develops the Java program in details.

Apparatus:
REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus

4.0 Theory:
Prior Concept:

Java Package

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package. There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.Here, we will have the detailed learning of creating and using
user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

OOPM JAVA /CSL 304 / Sem- III Page 55


Computer Engineering /SSJCET, Asangaon

Simple example of java package

The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. } }

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

OOPM JAVA /CSL 304 / Sem- III Page 56


Computer Engineering /SSJCET, Asangaon

The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows)
etc. If you want to keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package

ARRAYLIST:-

The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed.

Standard Java arrays are of a fixed length. After arrays are created, they cannot
grow or shrink, which means that you must know in advance how many elements an
array will hold.

Array lists are created with an initial size. When this size is exceeded, the collection
is automatically enlarged. When objects are removed, the array may be shrunk.

The ArrayList class supports three constructors. The first constructor builds an
empty array list.
ArrayList( )

The following constructor builds an array list that is initialized with the elements of
the collection c.
ArrayList(Collection c)

The following constructor builds an array list that has the specified initial capacity.
The capacity is the size of the underlying array that is used to store the elements.

The capacity grows automatically as elements are added to an array list.


ArrayList(int capacity)

LINKEDLIST:-

The LinkedList class extends AbstractSequentialList and implements the List


interface. It provides a linked-list data structure.

OOPM JAVA /CSL 304 / Sem- III Page 57


Computer Engineering /SSJCET, Asangaon

The LinkedList class supports two constructors. The first constructor builds an
empty linked list:
LinkedList( )

The following constructor builds a linked list that is initialized with the elements of
the collection c.
LinkedList(Collection c)

5.0 Java Program:


ArrayList Program

import java.util.*;

public class ArrayListDemo {


public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: "
+ al.size());

// add elements to the array list


al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after
additions: " + al.size());

// display the array list


System.out.println("Contents of al: " +
al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after
deletions: " + al.size());
System.out.println("Contents of al: " +
OOPM JAVA /CSL 304 / Sem- III Page 58
Computer Engineering /SSJCET, Asangaon

al);
}}

LinkedList program:

import java.util.*;

public class LinkedListDemo {

public static void main(String args[]) {


// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents
of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after
deletion: "
+ ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting
first and last: " + ll);

// get and set a value


Object val = ll.get(2);
ll.set(2, (String) val + " Changed");

OOPM JAVA /CSL 304 / Sem- III Page 59


Computer Engineering /SSJCET, Asangaon

System.out.println("ll after change: " +


ll); }}

Procedure for doing the experiment:

1 Compile the Java program using javac compiler.

5. Run the java Program using JVM(Interpreter).

Result:

ArrayList Output: Initial size of al: 0


Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

LinkedList Output: Original contents of ll: [A, A2, F, B, D, E, C, Z]


Contents of ll after deletion: [A, A2, D, E, C, Z]
ll after deleting first and last: [A2, D, E, C]
ll after change: [A2, D, E Changed, C]

OOPM JAVA /CSL 304 / Sem- III Page 60


Computer Engineering /SSJCET, Asangaon

Conclusion:
Here understand the concept of packages, ArrayList, LinkedList creation.

Questions:

1. Write java program to create package and using that package create a
program to add data into Arraylist and LinkedList program.

Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com

www.tutorialspoint.com

www.stackoverflow.com -- If error occurs in program then this site helps you to


solve error in your program

EXPERIMENT NO: 11

Aim of the Experiment: Program on Exception handling

Learning Objectives:
2.1 Intellectual Skills:
OOPM JAVA /CSL 304 / Sem- III Page 61
Computer Engineering /SSJCET, Asangaon

Understand the different methods and functions in java program.


2.2Motor Skills:
Ability to learn how develops the Java program in details.

Apparatus:
HARDWARE REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

SOFTWARE REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus

Theory:
Prior Concept:

Exception Handling in Java

The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.

In this page, we will learn about java exception, its type and the difference between
checked and unchecked exceptions.
What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
What is exception handling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFound, IO, SQL, Remote etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that is
why we use exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
OOPM JAVA /CSL 304 / Sem- III Page 62
Computer Engineering /SSJCET, Asangaon

5. statement 5;//exception occurs


6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.statement 10;
Hierarchy of Exception classes

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says 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 that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile-time.

OOPM JAVA /CSL 304 / Sem- III Page 63


Computer Engineering /SSJCET, Asangaon

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked
at runtime.
3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.
Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as
follows:
1) Scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs

If we have null value in any variable, performing any operation by the variable
occurs an NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) Scenario where NumberFormatException occurs

The wrong formatting of any value, may occur NumberFormatException. Suppose I


have a string variable that have characters, converting this variable into digit will
occur NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

OOPM JAVA /CSL 304 / Sem- III Page 64


Computer Engineering /SSJCET, Asangaon

4) Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException
Five keywords used in Exception handling:
1. try
2. catch
3. finally
4. throw
5. throws
try block
Enclose the code that might throw an exception in try block. It must be used within
the method and must be followed by either catch or finally block.
Syntax of try with catch block

1. try{
2. ...
3. }catch(Exception_class_Name reference){}
Syntax of try with finally block

1. try{
2. ...
3. }finally{}
catch block
Catch block is used to handle the Exception. It must be used after the try block.
Problem without exception handling

1. public class Testtrycatch1{


2. public static void main(String args[]){
3. int data=50/0;
4.
5. System.out.println("rest of the code...");
6. }

OOPM JAVA /CSL 304 / Sem- III Page 65


Computer Engineering /SSJCET, Asangaon

7. }
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
Solution by exception handling

1. public class Testtrycatch2{


2. public static void main(String args[]){
3. try{
4. int data=50/0;
5.
6. }catch(ArithmeticException e){System.out.println(e);}
7.
8. System.out.println("rest of the code...");
9. }
10.}

Output:Exception in thread main java.lang.ArithmeticException:/ by zero rest of


the code...
Java Program:
Program for multiple catch block

1. public class TestMultipleCatchBloc


k{
2. public static void main(String args[
]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e)
{System.out.println("task1 is compl
eted");}
8. catch(ArrayIndexOutOfBoundsEx
ception e){System.out.println("task
2 completed");}
9. catch(Exception e)
{System.out.println("common task c
ompleted");}
10.
11. System.out.println("rest of the cod

OOPM JAVA /CSL 304 / Sem- III Page 66


Computer Engineering /SSJCET, Asangaon

e..."); } }

Procedure for doing the experiment:

1. Compile the Java program using javac compiler.

2. Run the java Program using JVM(Interpreter).

Result:

Output: task1 completed


rest of the code...

Conclusion:
Here understand the concept of exception and how exception handle in java
program using try, catch, throw, throws and finally keyword.

Questions:
1. Write java program to handle the exception.
2. Write java program where used multiple catch block.

Student Activity:
(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)

OOPM JAVA /CSL 304 / Sem- III Page 67


Computer Engineering /SSJCET, Asangaon

 Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com

www.tutorialspoint.com

www.stackoverflow.com -- If error occurs in program then this site helps you to


solve error in your program

EXPERIMENT NO: 12

Aim: Program on user defined exception

Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their own exceptions.

OOPM JAVA /CSL 304 / Sem- III Page 68


Computer Engineering /SSJCET, Asangaon

User-Defined Exceptions

Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, the user can also create exceptions which are called ‘user-
defined Exceptions’.
The following steps are followed for the creation of a user-defined Exception.
 The user should create an exception class as a subclass of the Exception class.
Since all the exceptions are subclasses of the Exception class, the user should
also make his class a subclass of it. This is done as:

class MyException extends Exception

 We can write a default constructor in his own exception class.

MyException(){}

 We can also create a parameterized constructor with a string as a parameter.


We can use this to store exception details. We can call the
superclass(Exception) constructor from this and send the string there.

MyException(String str)
{
super(str);

OOPM JAVA /CSL 304 / Sem- III Page 69


Computer Engineering /SSJCET, Asangaon

 To raise an exception of a user-defined type, we need to create an object to his


exception class and throw it using the throw clause, as:

MyException me = new MyException(“Exception details”);


throw me;

 The following program illustrates how to create your own exception class
MyException.
 Details of account numbers, customer names, and balance amounts are taken in
the form of three arrays.
 In main() method, the details are displayed using a for-loop. At this time, a
check is done if in any account the balance amount is less than the minimum
balance amount to be apt in the account.
 If it is so, then MyException is raised and a message is displayed “Balance
amount is

Example

// Java program to demonstrate user defined exception

// This program throws an exception whenever balance

// amount is below Rs 1000

class MyException extends Exception

//store account information

private static int accno[] = {1001, 1002, 1003, 1004};

private static String name[] =

OOPM JAVA /CSL 304 / Sem- III Page 70


Computer Engineering /SSJCET, Asangaon

{"Nish", "Shubh", "Sush", "Abhi", "Akash"};

private static double bal[] =

{10000.00, 12000.00, 5600.0, 999.00, 1100.55};

// default constructor

MyException() { }

// parameterized constructor

MyException(String str) { super(str); }

// write main()

public static void main(String[] args)

try {

// display the heading for the table

System.out.println("ACCNO" + "\t" + "CUSTOMER" +

"\t" + "BALANCE");

// display the actual account information

for (int i = 0; i < 5 ; i++)

System.out.println(accno[i] + "\t" + name[i] +

OOPM JAVA /CSL 304 / Sem- III Page 71


Computer Engineering /SSJCET, Asangaon

"\t" + bal[i]);

// display own exception if balance < 1000

if (bal[i] < 1000)

MyException me =

new MyException("Balance is less than 1000");

throw me;

} //end of try

catch (MyException e) {

e.printStackTrace();

} }

Runtime Error
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
Output:

ACCNO CUSTOMER BALANCE

OOPM JAVA /CSL 304 / Sem- III Page 72


Computer Engineering /SSJCET, Asangaon

1001 Nish 10000.0


1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0

Conclusion: Thus we have performed practical on user defined exception.

EXPERIMENT NO: 13

Aim : To study about applet and life cycle of applet.

Learning Objectives:
2.1 Intellectual Skills:
Understand the different methods and functions in java program.

OOPM JAVA /CSL 304 / Sem- III Page 73


Computer Engineering /SSJCET, Asangaon

2.2Motor Skills:
Ability to learn how develops the Java program in details.

Apparatus:
REQUIREMENTS:
INTEL PENTIUM 915 GV
80GB HDD

512MB DDR

SOFTWARE REQUIREMENTS:

JDK 1.5 to 1.7, NotePad, Or Editplus

Theory:
Prior Concept:
Applet :

An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java
application, including the following:

 An applet is a Java class that extends the java.applet.Applet class.

 A main() method is not invoked on an applet, and an applet class will not
define main().

 Applets are designed to be embedded within an HTML page.

 When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.

 A JVM is required to view an applet. The JVM can be either a plug-in of the
Web browser or a separate runtime environment.

 The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.

OOPM JAVA /CSL 304 / Sem- III Page 74


Computer Engineering /SSJCET, Asangaon

 Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the
applet to a child playing in a sandbox with various rules that must be
followed.

 Other classes that the applet needs can be downloaded in a single Java
Archive (JAR) file.

Life Cycle of an Applet:

Four methods in the Applet class give you the framework on which you build any
serious applet:

 init: This method is intended for whatever initialization is needed for your
applet. It is called after the param tags inside the applet tag have been
processed.

 start: This method is automatically called after the browser calls the init
method. It is also called whenever the user returns to the page containing the
applet after having gone off to other pages.

 stop: This method is automatically called when the user moves off the page
on which the applet sits. It can, therefore, be called repeatedly in the same
applet.

 destroy: This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not
normally leave resources behind after a user leaves the page that contains the
applet.

 paint: Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt.

The Applet CLASS:

Every applet is an extension of the java.applet.Applet class. The base Applet class
provides methods that a derived Applet class may call to obtain information and
services from the browser context.

OOPM JAVA /CSL 304 / Sem- III Page 75


Computer Engineering /SSJCET, Asangaon

These include methods that do the following:

 Get applet parameters

 Get the network location of the HTML file that contains the applet

 Get the network location of the applet class directory

 Print a status message in the browser

 Fetch an image

 Fetch an audio clip

 Play an audio clip

 Resize the applet

Additionally, the Applet class provides an interface by which the viewer or browser
obtains information about the applet and controls the applet's execution. The viewer
may:

 request information about the author, version and copyright of the applet

 request a description of the parameters the applet recognizes

OOPM JAVA /CSL 304 / Sem- III Page 76


Computer Engineering /SSJCET, Asangaon

 initialize the applet

 destroy the applet

 start the applet's execution

 stop the applet's execution

The "Hello, World" applet is complete as it stands. The only method overridden is
the paint method.
5.0 Java Program:
A "Hello, World" Applet:

The following is a simple applet named


HelloWorldApplet.java:
import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends


Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}}

Invoking an Applet:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class"
width="320" height="120">
If your browser was Java-enabled, a
"Hello, World"
message would appear here.
</applet><hr></html>
<applet
codebase="http://amrood.com/applets"
code="HelloWorldApplet.class"
width="320" height="120">

OOPM JAVA /CSL 304 / Sem- III Page 77


Computer Engineering /SSJCET, Asangaon

If an applet resides in a package other than


the default, the holding package must be
specified in the code attribute using the
period character (.) to separate
package/class components. For example:
<applet
code="mypackage.subpackage.TestApplet.
class"
width="320" height="120">
Procedure for doing the experiment:

1. Compile the Java program using javac compiler.


2. Run the java Program using JVM(Interpreter).

Result:

Conclusion:
Here understand the concept of what is applet and applet life cycle, and how
implement applet program using html file.
Questions:
Write program to show “Hello World” using applet program.
Write program where circle, triangle, rectangle, arc show using Applet
program.

10.0 Student Activity:

OOPM JAVA /CSL 304 / Sem- III Page 78


Computer Engineering /SSJCET, Asangaon

(Teacher shall form group of 4-5 students. Each group shall perform one allotted
activity-Teacher shall guide and supervise.)
 Define and list down all the requirements as per the case study by using any
java program.
11.0 Related Links:
www.javatpoint.com
www.tutorialspoint.com
www.stackoverflow.com -- If error occurs in program then this site helps you to
solve error in your program

EXPERIMENT NO: 14

Aim : Program on Graphics class

Graphics is an abstract class provided by Java AWT which is used to draw or paint
on the components. It consists of various fields which hold information like
components to be painted, font, color, XOR mode, etc., and methods that allow
drawing various shapes on the GUI components. Graphics is an abstract class and
thus cannot be initialized directly. Objects of its child classes can be obtained in
the following two ways.
Inside paint() or update() method
It is passed as an argument to paint and update methods and therefore can be
accessed inside these methods. paint() and update() methods are present in the
Component class and thus can be overridden for the component to be painted.
void paint(Graphics g)
void update(Graphics g)

Displaying Graphics in Applet

java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:

1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle
with the specified width and height.

OOPM JAVA /CSL 304 / Sem- III Page 79


Computer Engineering /SSJCET, Asangaon

3. public abstract void fillRect(int x, int y, int width, int height): is used to
fill rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used
to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to
fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to
draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical arc.
10.public abstract void setColor(Color c): is used to set the graphics current
color to the specified color.
11.public abstract void setFont(Font font): is used to set the graphics current
font to the specified font.

Example of Graphics in applet:

import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
OOPM JAVA /CSL 304 / Sem- III Page 80
Computer Engineering /SSJCET, Asangaon

g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}

myapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Conclusion: Thus we studied Graphics class methods and example.

OOPM JAVA /CSL 304 / Sem- III Page 81


Computer Engineering /SSJCET, Asangaon

EXPERIMENT : 15

Aim :To perform mini project in group

OOPM JAVA /CSL 304 / Sem- III Page 82

You might also like