KEMBAR78
PIJ Lab Manual | PDF | Parameter (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
16 views68 pages

PIJ Lab Manual

This document is a laboratory manual for a Java programming course at SVKM's Institute of Technology, detailing experiments and objectives related to object-oriented programming. It includes a structured index of experiments, course objectives, and outcomes, as well as guidelines for students' lab journals. The manual covers various programming concepts such as operators, inheritance, polymorphism, exception handling, and file handling through practical assignments.

Uploaded by

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

PIJ Lab Manual

This document is a laboratory manual for a Java programming course at SVKM's Institute of Technology, detailing experiments and objectives related to object-oriented programming. It includes a structured index of experiments, course objectives, and outcomes, as well as guidelines for students' lab journals. The manual covers various programming concepts such as operators, inheritance, polymorphism, exception handling, and file handling through practical assignments.

Uploaded by

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

LABORATORY

MANUAL
Subject Name: Programming in Java Laboratory

Class: SY (Sem-III)

Course Code: BTITEL309B

Subject In-charge: Dr. Bhushan S. Chaudhari

Department: Information Technology

SVKM's INSTITUTE OF TECHNOLOGY, DHULE


DEPARMENT OF INFORMATION TECHNOLOGY
SESSION 2020-21
2

Index
Experiment Title Page No.
No.
1 Write a Java Program to display a message. 6
2 Write Java Programs to demonstrate: 11
 Operators
 Arithmetic Promotion
 Method Calling
3 Programs on Inheritance and Polymorphism. 25
4 Programs on: 34
 Packaging & Access Modifiers
 Static and Abstract Modifiers.
5 Programs on: 43
 Interfaces,
 Block Initializers,
 Final Modifier,
 Static and Dynamic Binding.
6 Programs on: 52
 File Handling
 Stream Manipulation
7 Programs on Dynamic Polymorphism. 59
8 Programs on Exception Handling. 63

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
3

COURSE STRUCTURE:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
4

COURSE OBJECTIVES:

1. To understand the concept of OOP as well as the purpose and usage principles of inheritance,
polymorphism, encapsulation and method overloading.
2. To understand fundamentals of programming such as variables, conditional and iterative
execution, methods, etc.
3. To identify classes, objects, members of a class and the relationships among them needed for
a specific problem.
4. To understand fundamentals of object-oriented programming in Java, including defining
classes, invoking methods, using class libraries, etc.
5. To create Java application programs using sound OOP practices (e.g., interfaces and APIs) and
proper program structuring (e.g., by using access control identifies, automatic
documentation through comments, error exception handling)
6. To have the ability to write a computer program to solve specified problems.

COURSE OUTCOMES:

At the end of this course Students will be able to:

CO1: To Understand OOP concepts and basics of Java programming.


CO2: To create Java programs using inheritance and polymorphism.
CO3: To Implement error-handling techniques using exception handling and multithreading.
CO4: To differentiate various collections.

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
5

GUIDELINES FOR STUDENT'S LAB JOURNAL

1) The laboratory assignments are to be submitted by student in the form of journal.

2) The Journal consists of prologue, Certificate, table of contents, and handwritten write-up of each
assignment (Title, Objectives, Problem Statement, Outcomes, software & Hardware requirements,
Date of Completion, Assessment grade/marks and assessor's sign, Theory-Concept, circuit diagram,
pin configuration, conclusion/analysis), printouts of the code written using coding standards,
sample test cases etc.

3) Practical Examination will be based on the term work submitted by the student in the form of
Journal

4) Candidate is expected to know the theory involved in the experiment

5) The practical examination should be conducted if the journal of the candidate is completed in all
respects and certified by concerned faculty and head of the department

6) All the assignment mentioned in the syllabus must be conducted

_____________

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
6

Experiment No: 1

Date of Conduction:

Name:

Roll No:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
7

Experiment No. 1

Problem Statement: Write a Java Program to display a message.

Software Required Ubuntu 14.04 or above

Theory:
Java is a high-level programming language originally developed by Sun Microsystems and
released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX.James Gosling initiated the Java language project in June 1991 for use in one of
his many set-top box projects. The language, initially called Oak after an oak tree that stood
outside Gosling's office, also went by the name Green and ended up later being renamed as Java,
from a list of random words

Features of JAVA
 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic

JDK

The Java Development Kit(JDK) is an implementation of either one of the Java SE, Java EEor Java
MEplatforms. The JDK includes a private JVM and a few other resources to finish the
development of a Java Application.

Data Types used in JDK


Each row contains the datatype and size and range of the data type. The list of available data
types in Java is shown in table below:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
8

A First Simple Program


/*
This is a simple Java program.
Call this file "Example.java".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}

For most computer languages, the name of the file that holds the source code to a program is
arbitrary. However, this is not the case with Java. The first thing that you must learn about Java is
that the name you give to a source file is very important. For this example, the name of the
source file should be Example.java.

Compiling the Program


To compile the Example program, execute the compiler, javac, specifying the name of the source
file on the command line, as shown here:

C:\>javac Example.java

The javac compiler creates a file called Example.class that contains the bytecode version of the
program. As discussed earlier, the Java bytecode is the intermediate representation of your
program that contains instructions the Java interpreter will execute. Thus, the output of javac is
not code that can be directly executed. To actually run the program, you must use the Java
interpreter, called java. To do so, pass the class name Example as a command-line argument, as
shown here:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
9

C:\>java Example

When the program is run, the following output is displayed:

This is a simple Java program.

Although Example.java is quite short, it includes several key features which are common to all
Java programs. Let’s closely examine each part of the program.

The program begins with the following lines:

/*
This is a simple Java program.
Call this file "Example.java".
*/

This is a comment.

class Example {
This line uses the keyword class to declare that a new class is being defined. Example is an
identifier that is the name of the class.

The next line in the program is the single-line comment, shown here:

// Your program begins with a call to main().

The next line of code is shown here:


public static void main(String args[]) {

This line begins the main( ) method. As the comment preceding it suggests, this is the line at
which the program will begin executing. All Java applications begin execution by calling main( ).
(This is just like C/C++.)

The public keyword is an access specifier, which allows the programmer to control the visibility of
class members. When a class member is preceded by public, then that member may be accessed
by code outside the class in which it is declared.

In this case, main( ) must be declared as public, since it must be called by code outside of its class
when the program is started. The keyword static allows main( ) to be called without having to
instantiate a particular instance of the class. This is necessary since main( ) is called by the Java
interpreter before any objects are made. The keyword void simply tells the compiler that main( )
does not return a value.

In main( ), there is only one parameter, albeit a complicated one. String args[ ] declares a
parameter named args, which is an array of instances of the class String. (Arrays are collections
of similar objects.) Objects of type String store character strings. In this case, args receives any
command-line arguments present when the program is executed.

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
10

The next line of code is shown here. Notice that it occurs inside main( ).

System.out.println("This is a simple Java program.");

This line outputs the string “This is a simple Java program.” followed by a new line on the screen.

System is a predefined class that provides access to the system, and out is the output stream
that is connected to the console.

Conclusion:
Hence we learned to write, compile and execute simple Java Program.
_________________

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
11

Experiment No: 2

Date of Conduction:

Roll No:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
12

Experiment No. 2

Problem Statement: Write Java Programs to demonstrate:


 Operators
 Arithmetic Promotion
 Method Calling

Theory:
2A) OPERATORS
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:

Example
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);

// arithmetic using doubles


System.out.println("\nFloating Point Arithmetic");
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
13

double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}

Output:

Integer Arithmetic
a = 2
b = 6
c = 1
d = -1
e = 1

Floating Point Arithmetic


da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5

The Modulus Operator

// Demonstrate the % operator.


class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;

System.out.println("x mod 10 = " + x % 10);


System.out.println("y mod 10 = " + y % 10);
}
}

The Bitwise Operators


Java defines several bitwise operators which can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands. They are
summarized in the following table:
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
14

Example
// Demonstrate the bitwise logical operators.
class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;

System.out.println(" a = " + binary[a]);


System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}

Output

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
15

Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:

The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the ?, and it works in Java much like it does in C, C++, and C#. It can
seem somewhat confusing at first, but the ? can be used very effectively once mastered. The ?
has this general form:

expression1 ? expression2 : expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true,
then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation
is that of the expression evaluated. Both expression2 and expression3 are required to return the
same type, which can’t be void.
Here is an example of the way that the ? is employed:

ratio = denom == 0 ? 0 : num / denom;


Example
// Demonstrate ?.
class Ternary {
public static void main(String args[]) {
int i, k;

i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);

i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
16

Output

Absolute value of 10 is 10
Absolute value of -10 is 10

2B) ARITHMETIC PROMOTION

When you assign value of one data type to another, the two types might not be compatible with
each other. If the data types are compatible, then Java will perform the conversion automatically
known as Automatic Type Conversion and if not then they need to be casted or converted
explicitly. For example, assigning an int value to a long variable.

Widening or Automatic Type Conversion

Widening conversion takes place when two data types are automatically converted. This happens
when:

 The two data types are compatible.


 When we assign value of a smaller data type to a bigger data type.

For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

Example
class Test
{
public static void main(String[] args)
{
int i = 100;

// automatic type conversion


long l = i;

// automatic type conversion


float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}

Output:
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
17

Int value 100


Long value 100
Float value 100.0

Narrowing or Explicit Conversion

If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or
narrowing.

This is useful for incompatible data types where automatic conversion cannot be done. Here, target-type
specifies the desired type to convert the specified value to.

//Java program to illustrate explicit type conversion

class Test
{
public static void main(String[] args)
{
double d = 100.04;

//explicit type casting


long l = (long)d;

//explicit type casting


int i = (int)l;
System.out.println("Double value "+d);

//fractional part lost


System.out.println("Long value "+l);

//fractional part lost


System.out.println("Int value "+i);
}
}

Output:

Double value 100.04


Long value 100
Int value 100
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
18

While assigning value to byte type the fractional part is lost and is reduced to modulo 256(range of byte).

Example:

//Java program to illustrate Conversion of int and double to byte


class Test
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("Conversion of int to byte.");

//i%256
b = (byte) i;
System.out.println("i = " + i + " b = " + b);
System.out.println("\nConversion of double to byte.");

//d%256
b = (byte) d;
System.out.println("d = " + d + " b= " + b);
}
}

Output:

Conversion of int to byte.


i = 257 b = 1

Conversion of double to byte.


d = 323.142 b = 67

Type promotion in Expressions

While evaluating expressions, the intermediate value may exceed the range of operands and hence the
expression value will be promoted. Some conditions for type promotion are:

Java automatically promotes each byte, short, or char operand to int when evaluating an expression.
If one operand is a long, float or double the whole expression is promoted to long, float or double
respectively.
//Java program to illustrate Type promotion in Expressions
class Test
{
public static void main(String args[])
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
19

{
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;

// The Expression
double result = (f * b) + (i / c) - (d * s);

//Result after all the promotions are done


System.out.println("result = " + result);
}
}

Output:

Result = 626.7784146484375

Explicit type casting in Expressions

While evaluating expressions, the result is automatically updated to larger data type of the operand. But
if we store that result in any smaller data type it generates compile time error, due to which we need to
type cast the result.

Example:
//Java program to illustrate type casting int to byte
class Test
{
public static void main(String args[])
{
byte b = 50;

//type casting int to byte


b = (byte)(b * 2);
System.out.println(b);
}
}

Output

100

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
20

2C) METHOD CALLING


A Java method is a collection of statements that are grouped together to perform an operation. When you
call the System.out.println() method, for example, the system actually executes several statements in
order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a method with
or without parameters, and apply method abstraction in the program design.
 Creating Method
Considering the following example to explain the syntax of a method −

Syntax
public static int methodName(int a, int b) {
// body
}
Here,
 public static − modifier
 int − return type
 methodName − name of the method
 a, b − formal parameters
 int a, int b − list of parameters
Method definition consists of a method header and a method body. The same is shown in the following
syntax −

Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
The syntax shown above includes −
 modifier − It defines the access type of the method and it is optional to use.
 returnType − Method may return a value.
 nameOfMethod − This is the method name. The method signature consists of the method name and
the parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of parameters of a method.
These are optional, method may contain zero parameters.
 method body − The method body defines what the method does with the statements.

Example
Here is the source code of the above defined method called min(). This method takes two parameters
num1 and num2 and returns the maximum between the two −
/** the snippet returns the minimum between two numbers */

public static int minFunction(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
21

return min;
}

 Method Calling
For using a method, it should be called. There are two ways in which a method is called i.e., method
returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program control gets
transferred to the called method. This called method then returns control to the caller in two conditions,
when −
 the return statement is executed.
 it reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Lets consider an example –
System.out.println("This is tutorialspoint.com!");

The method returning value can be understood by the following example −


int result = sum(6, 9);

Following is the example to demonstrate how to define a method and how to call it –

Example
public class ExampleMinNumber {

public static void main(String[] args) {


int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

Output
Minimum value = 6

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
22

Passing Parameters by Value


While working under calling process, arguments is to be passed. These should be in the same
order as their respective parameters in the method specification. Parameters can be passed by
value or by reference.
Passing Parameters by Value means calling a method with a parameter. Through this, the
argument value is passed to the parameter.

Example
The following program shows an example of passing parameter by value. The values of the
arguments remain the same even after the method invocation.

public class swappingExample {


public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);

// Invoke the swap method


swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}

public static void swapFunction(int a, int b) {


System.out.println("Before swapping(Inside), a = " + a + " b = " + b);

// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}

Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:


After swapping, a = 30 and b is 45

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
23

Method Overloading
When a class has two or more methods by the same name but different parameters, it is known
as method overloading. It is different from overriding. In overriding, a method has the same
method name, type, number of parameters, etc.
Let’s consider the example discussed earlier for finding minimum numbers of integer type. If,
let’s say we want to find the minimum number of double type. Then the concept of overloading
will be introduced to create two or more methods with the same name but different parameters.
The following example explains the same −

Example
public class ExampleOverloading {

public static void main(String[] args) {


int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);

// same function name with different parameters


double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}

// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}

// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
24

}
}
This will produce the following result −

Output
Minimum Value = 6
Minimum Value = 7.3

Conclusion
Hence, the programs related to operators, arithmetic promotion and method calling are executed
successfully.

____________________

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
25

Experiment No: 3

Date of Conduction:

Roll No:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
26

Experiment No. 3

Problem Statement: Programs on Inheritance and Polymorphism.

Theory:
3A) Inheritance
To inherit a class, you simply incorporate the definition of one class into another by using the
extends keyword. To see how, let’s begin with a short example. The following program creates a
superclass called A and a subclass called B. Notice how the keyword extends is used to create a
subclass of A.

Example
// A simple example of inheritance.

// Create a superclass.
class A {
int i, j;

void showij() {
System.out.println("i and j: " + i + " " + j);
}
}

// Create a subclass by extending class A.


class B extends A {
int k;

void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();

// The superclass may be used by itself.


superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
27

/* The subclass has access to all public members of


its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();

System.out.println("Sum of i, j and k in subOb:");


subOb.sum();
}
}

Output
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

The general form of a class declaration that inherits a superclass is shown here:

class subclass-name extends superclass-name {


// body of class
}

You can only specify one superclass for any subclass that you create. Java does not support the
inheritance of multiple superclasses into a single subclass.

Example
// This program uses inheritance to extend Box.
class Box {
double width;
double height;
double depth;

// construct clone of an object


Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}

// constructor used when all dimensions specified

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
28

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}

// constructor used when no dimensions specified


Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

// Here, Box is extened to include weight.


class BoxWeight extends Box {
double weight; // weight of box

// constructor for BoxWeight


BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}

class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;

vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
29

vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}

Output
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076

3B) Polymorphism
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism: A person at the same time can have different characteristic.
Like a man at the same time is a father, a husband, an employee. So the same person possesses
different behavior in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words,
polymorphism allows you to define one interface and have multiple implementations. The word
“poly” means many and “morphs” means forms, so it means many forms.

In Java polymorphism is mainly divided into two types:


 Compile time Polymorphism
 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.

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
30

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.

Example: By using different types of arguments


// Java program for Method overloading

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


static double Multiply(double a, double b)
{
return a * b;
}
}

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

System.out.println(MultiplyFun.Multiply(2, 4));

System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}

Output
8
34.65

Example: By using different numbers of arguments


// Java program for Method overloading

class MultiplyFun {

// Method with 2 parameter

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
31

static int Multiply(int a, int b)


{
return a * b;
}

// Method with the same name but 2 double parameter


static double Multiply(double a, double b)
{
return a * b;
}
}

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

System.out.println(MultiplyFun.Multiply(2, 4));

System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}

Output:
8
42

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.
In java, Only “+” operator can be overloaded:
 To add integers
 To concatenate strings

Example:
// Java program for Operator overloading

class OperatorOVERDDN {

void operator(String str1, String str2)


{

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
32

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);
}
}

class Main {
public static void main(String[] args)
{
OperatorOVERDDN obj = new OperatorOVERDDN();
obj.operator(2, 3);
obj.operator("joe", "now");
}
}

Output:
Sum = 5
Concatinated String - joenow

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.
Example:
// Java program for Method overridding

class Parent {

void Print()
{
System.out.println("parent class");
}
}

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
33

class subclass1 extends Parent {

void Print()
{
System.out.println("subclass1");
}
}

class subclass2 extends Parent {

void Print()
{
System.out.println("subclass2");
}
}

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

Parent a;

a = new subclass1();
a.Print();

a = new subclass2();
a.Print();
}
}

Output:
subclass1
subclass2

CONCLUSION

Thus the program for inheritance and polymorphism are successfully executed.

_________________

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
34

Experiment No: 4

Date of Conduction:

Roll No:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
35

Experiment No. 4

Problem Statement: Write Java Programs on:


 Java Packages & Access Modifiers
 Static and Abstract Modifiers.

Theory:
4A) Java Packages & Access Modifiers
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.

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.

Defining a Package
To create a package is quite easy: simply include a package command as the first statement in a
Java source file. Any classes declared within that file will belong to the specified package.

This is the general form of the package statement:


package pkg;
Here, pkg is the name of the package. For example, the following statement creates a
package called MyPackage.
package MyPackage;

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
36

You can create a hierarchy of packages. To do so, simply separate each package name from the
one above it by use of a period. The general form of a multileveled package statement is shown
here:
package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java development system. For example, a
package declared as
package java.awt.image;

Example
// A simple package
package MyPack;

class Balance {
String name;
double bal;

Balance(String n, double b) {
name = n;
bal = b;
}

void show() {
if(bal<0)
System.out.print("-->> ");
System.out.println(name + ": $" + bal);
}
}

class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];

current[0] = new Balance("K. J. Fielding", 123.23);


current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);

for(int i=0; i<3; i++) current[i].show();


}
}

Output

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
37

Call this file AccountBalance.java, and put it in a directory called MyPack. Next, compile the file. Make
sure that the resulting .class file is also in the MyPack directory. Then try executing the AccountBalance
class, using the following command line:
java MyPack.AccountBalance

Access Protection
Classes and packages are both means of encapsulating and containing the name space and scope
of variables and methods. Packages act as containers for classes and other subordinate packages.
Classes act as containers for data and code. The class is Java’s smallest unit of abstraction.
Because of the interplay between classes and packages, Java addresses four categories of
visibility for class members:
 Subclasses in the same package
 Non-subclasses in the same package
 Subclasses in different packages
 Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories.

Example:
Protection.java
package p1;
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection() {
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
38

System.out.println("n_pub = " + n_pub);


}
}

Derived.java
class Derived extends Protection {
Derived() {
System.out.println("derived constructor");
System.out.println("n = " + n);

// class only
// System.out.println("n_pri = " + n_pri);

System.out.println("n_pro = " + n_pro);


System.out.println("n_pub = " + n_pub);
}
}

SamePackage.java
class SamePackage {
SamePackage() {
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);

// class only
// System.out.println("n_pri = " + p.n_pri);

System.out.println("n_pro = " + p.n_pro);


System.out.println("n_pub = " + p.n_pub);
}
}

Output

4B) Static and Abstract Modifiers

Java provides a number of non-access modifiers to achieve many other functionalities.


 The static modifier for creating class methods and variables.
 The final modifier for finalizing the implementations of classes, methods, and variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
39

 The Static Modifier


 Static Variables
The static keyword is used to create variables that will exist independently of any
instances created for the class. Only one copy of the static variable exists regardless of
the number of instances of the class.
Static variables are also known as class variables. Local variables cannot be declared
static.
 Static Methods
The static keyword is used to create methods that will exist independently of any
instances created for the class.
Static methods do not use any instance variables of any object of the class they are
defined in. Static methods take all the data from parameters and compute something
from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and
the name of the variable or method.

Example
public class InstanceCounter {
private static int numInstances = 0;
protected static int getCount() {
return numInstances;
}

private static void addInstance() {


numInstances++;
}

InstanceCounter() {
InstanceCounter.addInstance();
}

public static void main(String[] arguments) {


System.out.println("Starting with " + InstanceCounter.getCount() + " instances");

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


new InstanceCounter();
}
System.out.println("Created " + InstanceCounter.getCount() + " instances");
}
}

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
40

Output
Started with 0 instances
Created 500 instances

 The Final Modifier

Final Variables
A final variable can be explicitly initialized only once. A reference variable declared final can
never be reassigned to refer to an different object.
However, the data within the object can be changed. So, the state of the object can be changed
but not the reference. With variables, the final modifier often is used with static to make the
constant a class variable.

Example
public class Test {
final int value = 10;

// The following are examples of declaring constants:


public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";

public void changeValue() {


value = 12; // will give an error
}
}

Final Methods
A final method cannot be overridden by any subclasses. As mentioned previously, the final
modifier prevents a method from being modified in a subclass.
The main intention of making a method final would be that the content of the method should
not be changed by any outsider.

Example
You declare methods using the final modifier in the class declaration, as in the following example

public class Test {


public final void changeName() {
// body of method
}
}

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
41

Final Classes
The main purpose of using a class being declared as final is to prevent the class from being
subclassed. If a class is marked as final then no class can inherit any feature from the final class.

Example
public final class Test {
// body of class
}

 The abstract Modifier


Abstract Class
An abstract class can never be instantiated. If a class is declared as abstract then the sole purpose
is for the class to be extended.
A class cannot be both abstract and final (since a final class cannot be extended). If a class
contains abstract methods then the class should be declared abstract. Otherwise, a compile error
will be thrown.
An abstract class may contain both abstract methods as well normal methods.

Example
abstract class Caravan {
private double price;
private String model;
private String year;
public abstract void goFast(); // an abstract method
public abstract void changeColor();
}

Abstract Methods
An abstract method is a method declared without any implementation. The methods body
implementation) is provided by the subclass. Abstract methods can never be final or strict. Any
class that extends an abstract class must implement all the abstract methods of the super class,
unless the subclass is also an abstract class.
If a class contains one or more abstract methods, then the class must be declared abstract. An
abstract class does not need to contain abstract methods.
The abstract method ends with a semicolon. Example: public abstract sample();

Example
public abstract class SuperClass {
abstract void m(); // abstract method
}

class SubClass extends SuperClass {


___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
42

// implements the abstract method


void m() {
.........
}
}

 The Volatile Modifier


The volatile modifier is used to let the JVM know that a thread accessing the variable must
always merge its own private copy of the variable with the master copy in the memory.
Accessing a volatile variable synchronizes all the cached copied of the variables in the main
memory. Volatile can only be applied to instance variables, which are of type object or private. A
volatile object reference can be null.

Example
public class MyRunnable implements Runnable {
private volatile boolean active;

public void run() {


active = true;
while (active) { // line 1
// some code here
}
}

public void stop() {


active = false; // line 2
}
}
Usually, run() is called in one thread (the one you start using the Runnable), and stop() is called
from another thread. If in line 1, the cached value of active is used, the loop may not stop when
you set active to false in line 2. That's when you want to use volatile.

CONCLUSION

Hence the Java program on packages, access modifiers and static modifiers are successfully
executed.

_____________________

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
43

Experiment No: 5

Date of Conduction:

Roll No:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
44

Experiment No. 5

Problem Statement: Write Java Programs on:


• Interfaces,
• Block Initializers,
• Static and Dynamic Binding.

Theory:
5A) Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods.
A class implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods, an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviors
of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need
to be defined in the class.

An interface is similar to a class in the following ways −


 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.

However, an interface is different from a class in several ways, including −


 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.
 Declaring Interfaces

The interface keyword is used to declare an interface. Here is a simple example to declare an
interface −

Example
/* File name : NameOfInterface.java */
import java.lang.*;
// Any number of import statements

public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations\
}
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
45

Interfaces have the following properties −


 An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly public.

Example
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}

Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.

Example
/* File name : MammalInt.java */
public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Output
Mammal eats
Mammal travels

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
46

When overriding methods defined in interfaces, there are several rules to be followed −
 Checked exceptions should not be declared on implementation methods other than the
ones declared by the interface method or subclasses of those declared by the interface
method.
 The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
 An implementation class itself can be abstract and if so, interface methods need not be
implemented.

When implementation interfaces, there are several rules −


 A class can implement more than one interface at a time.
 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend another
class.

The 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.

Extending Multiple Interfaces


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are
not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as −

public interface Hockey extends Sports, Event

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
47

Example
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

Output
Hello
Welcome

Interface inheritance
A class implements an interface, but one interface extends another interface.

Example
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
48

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

Output
Hello
Welcome

5B) Block Initializers

The Initializer Block in Java


Initializer block contains the code that is always executed whenever an instance is created. It is
used to declare/initialize the common part of various constructors of a class. We can note that
the contents of initializer block are executed whenever any constructor is invoked (before the
constructor’s contents)

Example
import java.io.*;
public class GFG
{
// Initializer block starts..
{
// This code is executed before every constructor.
System.out.println("Common part of constructors invoked !!");
}
// Initializer block ends

public GFG()
{
System.out.println("Default Constructor invoked");
}
public GFG(int x)
{
System.out.println("Parametrized constructor invoked");
}
public static void main(String arr[])
{
GFG obj1, obj2;
obj1 = new GFG();
obj2 = new GFG(0);
}
}

Output
Common part of constructors invoked!!
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
49

Default Constructor invoked


Common part of constructors invoked!!
Parametrized constructor invoked

Static blocks in Java


Unlike C++, Java supports a special block, called static block (also called static clause) which can
be used for static initializations of a class. This code inside static block is executed only once: the
first time you make an object of that class or the first time you access a static member of that
class (even if you never make an object of that class).

Example
// filename: Main.java
class Test {
static int i;
int j;

// start of static block


static {
i = 10;
System.out.println("static block called ");
}
// end of static block
}

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

// Although we don't have an object of Test, static block is


// called because i is being accessed in following statement.
System.out.println(Test.i);
}
}

Output
static block called
10

5C) Static and Dynamic Binding.


Static Binding: The binding which can be resolved at compile time by compiler is known as static
or early binding. Binding of all the static, private and final methods is done at compile-time.
Static binding is better performance wise (no extra overhead is required). Compiler knows that
all such methods cannot be overridden and will always be accessed by object of local class.
Hence compiler doesn’t have any difficulty to determine object of class (local class for sure).
That’s the reason binding for such methods is static

Example

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
50

/* As you can see, in both cases print method of superclass is called. Lets see how this happens

 We have created one object of subclass and one object of superclass with the reference of
the superclass.
 Since the print method of superclass is static, compiler knows that it will not be overridden
in subclasses and hence compiler knows during compile time which print method to call
and hence no ambiguity. */

public class NewClass {


public static class superclass {
static void print()
{
System.out.println("print in superclass.");
}
}
public static class subclass extends superclass {
static void print()
{
System.out.println("print in subclass.");
}
}

public static void main(String[] args)


{
superclass A = new superclass();
superclass B = new subclass();
A.print();
B.print();
}
}

Output
print in superclass.
print in superclass.

Dynamic Binding: In Dynamic binding compiler doesn’t decide the method to be called.
Overriding is a perfect example of dynamic binding. In overriding both parent and child classes
have same method.

Example
/*
Let’s break down the code and understand it thoroughly.
 Methods are not static in this code.
 During compilation, the compiler has no idea as to which print has to be called since
compiler goes only by referencing variable not by type of object and therefore the
binding would be delayed to runtime and therefore the corresponding version of print
will be called based on type on object.

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
51

*/
public class NewClass {
public static class superclass {
void print()
{
System.out.println("print in superclass.");
}
}

public static class subclass extends superclass {


@Override
void print()
{
System.out.println("print in subclass.");
}
}

public static void main(String[] args)


{
superclass A = new superclass();
superclass B = new subclass();
A.print();
B.print();
}
}

Output
print in superclass.
print in subclass.

CONCLUSION

Hence we learned Java programs on interfaces, block initializers, Static and Dynamic binding.

_____________

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
52

Experiment No: 6

Date of Conduction:

Roll No:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
53

Experiment No. 6

Problem Statement: Write Java programs on:


 File Handling
 Stream Manipulation

Theory:
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream in
the java.io package supports many data such as primitives, object, localized characters, etc.

Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
 InPutStream − The InputStream is used to read data from a source.
 OutPutStream − The OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an
input file into an output file −

Example
import java.io.*;
public class CopyFile {

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


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
54

if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Output
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file
and do the following −

$javac CopyFile.java
$java CopyFile

Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. If you are
aware of C or C++ programming languages, then you must be aware of three standard devices
STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard streams −
 Standard Input − This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
 Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented as
System.out.
 Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented as
System.err.

Example
/* Following is a simple program, which creates InputStreamReader to read standard input
stream until the user types a "q" */
import java.io.*;
public class ReadConsole {

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


InputStreamReader cin = null;

try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
55

System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}

Output
Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown in
the following program. This program continues to read and output the same character until we
press 'q'.

$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q

Reading and Writing Files


As described earlier, a stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
56

FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword
new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.

Sr.No. Method & Description


public void close() throws IOException{}
1 This method closes the file output stream. Releases any system resources associated with
the file. Throws an IOException.
protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this
2
file output stream is called when there are no more references to this stream. Throws an
IOException.
3 public int read(int r)throws IOException{}
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
57

This method reads the specified byte of data from the InputStream. Returns an int.
Returns the next byte of data and -1 will be returned if it's the end of the file.
public int read(byte[] r) throws IOException{}
4 This method reads r.length bytes from the input stream into an array. Returns the total
number of bytes read. If it is the end of the file, -1 will be returned.
public int available() throws IOException{}
5
Gives the number of bytes that can be read from this file input stream. Returns an int.

FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the
file −
OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.

Sr.No. Method & Description


public void close() throws IOException{}
1 This method closes the file output stream. Releases any system resources associated with
the file. Throws an IOException.
protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method of this
2
file output stream is called when there are no more references to this stream. Throws an
IOException.
public void write(int w)throws IOException{}
3
This methods writes the specified byte to the output stream.
public void write(byte[] w)
4
Writes w.length bytes from the mentioned byte array to the OutputStream.

Example
import java.io.*;
public class fileStreamTest {

public static void main(String args[]) {

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
58

try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();

InputStream is = new FileInputStream("test.txt");


int size = is.available();

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


System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}

Output

The above code would create file test.txt and would write given numbers in binary format. Same
would be the output on the stdout screen.

CONCLUSION

Thus the programs on file handling and stream manipulation are successfully executed.

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
59

Experiment No: 7

Date of Conduction:

Roll No:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
60

Experiment No. 7

Problem Statement: Programs on Dynamic Polymorphism.

Theory:
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within a subclass, it will always refer to
the version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden.

Example
// Method overriding.
class A {
int i, j;

A(int a, int b) {
i = a;
j = b;
}

// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A {
int k;

B(int a, int b, int c) {


super(a, b);
k = c;
}

// display k -- this overrides show() in A


void show() {
System.out.println("k: " + k);
}
}

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);

subOb.show(); // this calls show() in B


}
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
61

Output

k: 3

Dynamic Method Dispatch


Method overriding forms the basis for one of Java’s most powerful concepts: dynamic method
dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time. Dynamic method dispatch is important because
this is how Java implements run-time polymorphism.

Example
// Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}

class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}

class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}

class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A

r = a; // r refers to an A object
r.callme(); // calls A's version of callme

r = b; // r refers to a B object
r.callme(); // calls B's version of callme

r = c; // r refers to a C object

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
62

r.callme(); // calls C's version of callme


}
}

Output

Inside A’s callme method


Inside B’s callme method
Inside C’s callme method

Conclusion
Thus, the program for dynamic polymorphism is successfully executed.

______________

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
63

Experiment No: 8

Date of Conduction:

Roll No:

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
64

Experiment No. 8

Problem Statement: Write Java programs on Exception Handling.

Theory:
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
Based on these, we have three categories of Exceptions. You need to understand them to know
how exception handling works in Java.
 Checked exceptions − A checked exception is an exception that is checked (notified) by
the compiler at compilation-time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored, the programmer should take care of (handle) these
exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception.

Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs. Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of memory. Normally, programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.

Exceptions Methods
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
65

Following is the list of important methods available in the Throwable class.


Sr.No. Method & Description

public String getMessage()


1 Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.

2 public Throwable getCause()


Returns the cause of the exception as represented by a Throwable object.

3 public String toString()


Returns the name of the class concatenated with the result of getMessage().
public void printStackTrace()
4 Prints the result of toString() along with the stack trace to System.err, the error
output stream.
public StackTraceElement [] getStackTrace()
5 Returns an array containing each element on the stack trace. The element at index
0 represents the top of the call stack, and the last element in the array represents
the method at the bottom of the call stack.
public Throwable fillInStackTrace()
6 Fills the stack trace of this Throwable object with the current stack trace, adding to
any previous information in the stack trace.

Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}

The code which is prone to exceptions is placed in the try block. When an exception occurs, that
exception occurred is handled by catch block associated with it. Every try block should be immediately
followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs
in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.

Example
Live Demo
// File Name : ExcepTest.java
import java.io.*;
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
66

public class ExcepTest {

public static void main(String args[]) {


try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}

The Throws/Throw Keywords


If a method does not handle a checked exception, the method must declare it using the throws keyword.
The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using
the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.

Syntax
import java.io.*;
public class className {

public void deposit(double amount) throws RemoteException {


// Method implementation
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
67

throw new RemoteException();


}
// Remainder of class definition
}

A method can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it
throws a RemoteException and an InsufficientFundsException −

Syntax
import java.io.*;
public class className {

public void withdraw(double amount) throws RemoteException,


InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}

The Finally Block


The finally block follows a try block or a catch block. A finally block of code always executes, irrespective
of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter
what happens in the protected code.

Example
public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}

Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
68

First element value: 6


The finally statement is executed

Note the following −


 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.

Conclusion
Hence, java programs on exception handling are successfully executed.

_____________

___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule

You might also like