PIJ Lab Manual
PIJ Lab Manual
MANUAL
Subject Name: Programming in Java Laboratory
Class: SY (Sem-III)
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:
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
5
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
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
_____________
___________________________________________________________________________________________________
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
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.
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
8
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.
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
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.
/*
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:
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( ).
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
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);
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
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;
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:
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:
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
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 conversion takes place when two data types are automatically converted. This happens
when:
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;
Output:
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
17
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.
class Test
{
public static void main(String[] args)
{
double d = 100.04;
Output:
While assigning value to byte type the fractional part is lost and is reduced to modulo 256(range of byte).
Example:
//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:
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);
Output:
Result = 626.7784146484375
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;
Output
100
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
20
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 */
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!");
Following is the example to demonstrate how to define a method and how to call it –
Example
public class ExampleMinNumber {
return min;
}
}
Output
Minimum value = 6
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
22
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.
// 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
___________________________________________________________________________________________________
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 {
// 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
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);
}
}
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();
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
27
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:
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;
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
28
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.
___________________________________________________________________________________________________
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.
class MultiplyFun {
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
class MultiplyFun {
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
31
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 {
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
32
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
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
void Print()
{
System.out.println("subclass1");
}
}
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
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.
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.
___________________________________________________________________________________________________
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];
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
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);
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);
Output
Example
public class InstanceCounter {
private static int numInstances = 0;
protected static int getCount() {
return numInstances;
}
InstanceCounter() {
InstanceCounter.addInstance();
}
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
40
Output
Started with 0 instances
Created 500 instances
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;
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
−
___________________________________________________________________________________________________
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
}
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
}
Example
public class MyRunnable implements Runnable {
private volatile boolean active;
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
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.
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
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 {
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.
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
For example, if the Hockey interface extended both Sports and Event, it would be declared as −
___________________________________________________________________________________________________
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");}
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
Output
Hello
Welcome
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
Example
// filename: Main.java
class Test {
static int i;
int j;
class Main {
public static void main(String args[]) {
Output
static block called
10
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. */
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.");
}
}
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
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 {
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 {
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
___________________________________________________________________________________________________
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.
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.
Example
import java.io.*;
public class fileStreamTest {
___________________________________________________________________________________________________
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();
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
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;
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
Output
k: 3
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
Output
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
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
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
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Syntax
import java.io.*;
public class className {
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 {
Example
public class ExcepTest {
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule
68
Conclusion
Hence, java programs on exception handling are successfully executed.
_____________
___________________________________________________________________________________________________
SVKM’s Institute of Technology, Dhule