You are on page 1of 46

LAB MANUAL

Audit Course:
Java Programming

SY BTECH (2022-

23)

Course Champion
– Mr. S.A. Khandekar
Mrs. Sneha Pokharkar
Vision & Mission of MIT Academy of Engineering
&
Vision, Mission, PEOs, PO & PSO of E&TC Engg.
Vision & Mission of MIT Academy of Engineering
Vision
To develop MITAOE into a new-age learning center with an excellent ambiance for
academics and research conjugated with a vibrant environment for honing the extra and
curricular skills of all its stakeholders, to enable them to solve real-world problems and
bring a positive change in the society.

Mission

To leave no stone unturned in our endeavor to ensure that every alumnus looks back at us
and says MITAOE has not merely taught me, it has educated me.

Vision & Mission of E&TC Engineering


Vision
To develop the students towards an exemplary career in Telecommunication and its cognate
disciplines, possessing a sound social awareness, sense of responsibility, and moral ethos.
Mission

 To develop the Department into a well-established education hub in the domain of


Electronics & Telecommunication engineering.

 To provide students with a multi-faceted learning environment complemented by


adequate engineering practice and research, preparing them to solve real-life
engineering problems.

 To facilitate inclusive growth of all its student community and enabling them to be
leaders of tomorrow.

Program Educational Objectives (PEOs)


The graduates of BTECH in Electronics & Telecommunication Engineering, four
years after completion of their degrees, are expected:
PEO 1. To achieve a high level of technical competence in the electronics and
telecommunication domain or any other associated areas, be it an Engineering Practice or
Research.
PEO 2. To address real-world complex engineering problems by formulating solutions
and designs that are technically sound, economically viable, practically feasible, and
environmentally sustainable.
PEO 3. To aim towards career enhancement by pursuing lifelong learning and evolve
as a leader in professional and personal life.
Program Outcomes (POs)
After successfully completing the BTECH program students will be able to -

PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO 2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO 3 Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO 4 Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO 5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
PO 6 The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO 7 Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO 8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO 9 Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO 10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
PO 11 Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO 12 Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
Program Specific Outcomes (PSOs)
After successfully completing the BTECH E&TC Engg. program students will be able to –
PSO 1 Analyze and simulate diverse problems in the field of communication.
PSO 2 Design and analyze a system with applications in signal and image processing.
PSO 3 Build, test and evaluate an embedded system with real time constraints.
PSO 4 Design and implement a system towards automatic control in varied engineering
problems.
Format No.: MITAOE/ACAD/INST/3 Rev. No. 01 Rev. Date: 01/6/2018

COURSE OBJECTIVES &


COURSE OUTCOMES
Alandi (D), Pune - 412105 ACADEMIC YEAR 2022-23
SEM / TRI IV
SCHOOL OF ELECTRICAL ENGG.
CLASS SY BTECH
COURSE Java Programming Division / Block A,B,C
,
Course Objectives

CEO.1 To familiarize basic concepts of object oriented programming with Java.

CEO.2 To implement classes and objects of Java.

To emphasize on inheritance and package, IO package and GUI


CEO.3

CEO.4 To cognize exception handling in Java.

Course Outcomes (COs) BT Level

CO.1 Describe the principles of object oriented programming . L2

CO.2 Apply the concepts of classes, methods & inheritance to write Java L3
program.
Implement package , exception handling in Java.
CO.3 L3

(BT Levels: L1 - Remembering, L2 - Understanding, L3 - Applying, L4 - Analyzing, L5 - Evaluating and L6 - Creating)


Sr. PAGE
TITLE DATE SIGN.
NO NO.
9 17/02/23
1 Creation of classes and its instances in Java
13 28/02/23
2. Different types of functions in Java
17 09/03/23
3. Constructor and destructor in Java
22 21/03/23
4. Function overloading in Java
26 30/03/23
5. Interfaces in Java

32 10/04/23
Exception handling mechanism in Java
6.

Packages in Java 37 21/04/23


7.
41 09/05/23
8. Interfaces In Java

This is to certify that, Mr. Atharv Mahesh Musale Roll No. 250 of SY B.Tech. (ETX/ENTC) has
completed the term work in the subject of Java Programming in the School of Electrical Engineering
of MIT Academy of Engineering,Alandi (D), Pune- 412105 during the academic year 2022-2023.
Rubrics for Assessment

Descriptors Unsatisfactory Competent Excellent


Marks 2 3 5
Code Program is difficult Program can be Program is
Practice to read. Code read and is in a well-organized,
contains lines that logical order. makes good use of
do not work or are whitespace and
out of order. comments.
Variables, methods
, classes have
helpful names.
Code Supported output screen Output screen Code is supported
by output snapshot missing. present but not in by the appropriate
readable form. output screen
snapshot.
Programming in Java

MIT Academy of Engineering, Alandi, Pune 412105


Department of Electronics & Telecommunication Engineering

Class : SY BTECH Subject – Java Programming

Name Of Student : Atharv Mahesh Musale

Roll No. : 250

Academic Year :2022-2023

Experiment No. : 1

Date : 17/02/2023

Title : Creation Of Classes and objects


Title: To study classes, objects and methods in java.

Description of the Experiment:

Write a program in Java which would involve creating a simple java program. Create class, have
data and method. Have a main class, create object and call the methods.

Objective :

The objective of this assignment is to learn classes, objects and methods in java.
Theory:

● Object - Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors -wagging, barking, eating. An object is an instance of a class.
● Class - A class can be defined as a template/blue print that describes the
behaviors/states that object of its type support.

Objects in Java:

Let us now look deep into what are objects. If we consider the real-world we can find many objects
around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.

If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging,
running

If you compare the software object with a real world object, they have very similar characteristics.

Software objects also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods.

So in software development, methods operate on the internal state of an object and the object-to-
object communication is done via methods.

Classes in Java:

A class is a blue print from which individual objects are created.

public class
Dog{ String
breed; int age;
S. Y. E&TC Programming in JAVA

String color;

void barking(){
}

void hungry(){
}

void sleeping(){
}
}

A class can contain any of the following variable types.

● Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
● Instance variables: Instance variables are variables within a class but outside any method.
These variables are instantiated when the class is loaded. Instance variables can be accessed
from inside any method, constructor or blocks of that particular class.
● Class variables: Class variables are variables declared with in a class, outside any method,
with the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.

Constructors:

When discussing about classes, one of the most important sub topic would be constructors. Every
class has a constructor. If we do not explicitly write a constructor for a class the Java compiler
builds a default constructor for that class.

Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.
S. Y. E&TC Programming in JAVA

Input:

Output:

FAQ:

How to call methods in java?


How to create instance of class?

References:

1. E. Balaguruswamy, Programming with Java: A Primer, McGraw Hill, 2009. ISBN:


9780070141698
2. R Nageswara Rao, Core Java, An Integrated Approach, Dreamtech Press, 2012. ISBN:
9788177228366

Conclusion:
1) Class serves as a blueprint for objects, encapsulating both data and behavior. Also class to store
information and methods to perform specific actions or computations on that data.By creating a
main class, we were able to instantiate objects of the defined class using the new keyword.
2) This allowed us to create specific instances of the class and access its methods to manipulate the
data or perform operations.By calling the methods on the object within the main class, we were
able to execute the desired functionality of the program. This demonstrated how objects can
interact with methods to perform tasks and process data.
Programming in Java

MIT Academy of Engineering, Alandi, Pune 412105


Department of Electronics & Telecommunication Engineering

Class : SY BTECH Subject – Java Programming

Name Of Student : Atharv Mahesh Musale

Roll No. : 250

Academic Year :2022-23

Experiment No. : 2

Date : 28/02/2023

Title : Different types of Methods


Title: To Write Different types of methods in Java

Aim of Experiment:
Write some simple programs using methods in Java such as
i) To find factorial of number.
ii) To display first 50 prime numbers.
iii) To find sum and average of N numbers.

Objective :
The objective of this assignment is to learn simple programming concepts & exercise simple problem
statements based on methods.

Theory:
Factorial of any number is the product of an integer and all the integers below it for example
factorial of 4 is

4! = 4 * 3 * 2 * 1 = 24.

Factorial of a number can be calculated in a program using recursion.

A Prime Number can be divided evenly only by 1, or itself.


And it must be a whole number greater than 1.

Example: 5 can only be divided evenly by 1 or 5, so it is a prime number.

But 6 can be divided evenly by 1, 2, 3 and 6 so it is NOT a prime number (it is a composite
number).

Recursion in Java

Recursion in java is a process in which a method calls itself continuously. A method in java that calls
itself is called recursive method.

It makes the code compact but complex to understand.

Syntax:

1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same
method 4. }
Java Recursion Example 1: Infinite times
1. public class RecursionExample1 {
2. static void p(){
3. System.out.println("hello");
4. p();
5. }
6.
7. public static void main(String[] args) {
8. p();
9. }
10. }

Output:

hello
hello
...
java.lang.StackOverflowError

Input:

Output:
FAQ:

What are different types of methods?


Can we have multiple return values in methods?, if yes, how?
What is recursion?
How array is stored and accessed for mathematical operations?

References:

1. E. Balaguruswamy, Programming with Java: A Primer, McGraw Hill, 2009. ISBN:


9780070141698
2. R Nageswara Rao, Core Java, An Integrated Approach, Dreamtech Press, 2012. ISBN:
9788177228366

Conclusion:

1) Methods facilitate code reuse. Once defined, a method can be called multiple times from
different parts of the program, eliminating the need to duplicate code and promoting efficient and
clean coding practices.
2) Allows methods to interact with other parts of the program, exchange data, and perform operations,
enhancing the program's functionality.
Programming in Java

MIT Academy of Engineering, Alandi, Pune 412105


Department of Electronics & Telecommunication Engineering

Class : SY BTECH Subject – Java Programming

Name Of Student : Atharv Mahesh Musale

Roll No. : 250

Academic Year 2022 23

Experiment No. : 3

Date : 09/03/2023

Title : Constructor and destructor in Java


Title: To study the Constructor and destructor in Java.

Aim of Experiment:
Write a program in Java to implement constructor and destructor by passing parameters in different
ways.

Objective:
The objective of this assignment is to learn the concepts of constructor and destructor.

Theory:
Introduction to Constructor and Destructor in Java
A constructor is something that initializes objects, and destructors are to destroy that initialization.
Java has automatic garbage collection, which used the mark and sweep’s algorithm.

What is Constructor and Destructor in Java?


A constructor is used to initialize a variable that means it allocates memory for the same A constructor
is nothing but automatic initialization of the object. Whenever the program creates an object at that
time constructor, is gets called automatically. You don’t need to call this method explicitly. Destructor
is used to free that memory allocated during initialization. Generally, in java, we don’t need to call the
destructor explicitly. Java has a feature of automatic garbage collection.

Why do we Need a Constructor and Destructor in Java?


Constructor and destructor are mostly used to handle memory allocation and de-allocation efficiently.
Constructor and destructor do a very important role in any programming language of initializing and
destroying it after use to free up the memory space.

How Constructor and Destructor Works in Java


A constructor is just a method in java, which has the same name as the class name. The constructor
method does not have any return type to it.

Look at the following example for more clarity:

class Employee {
Employee() {
}
}

If you see in the above example, we have not given any return type like int or void to the method,
which has the same name as a class name.

It is mainly used to initialize the object. When we are creating an object of a class, at that time,
constructor gets invoked.

How to create Constructors and Destructors in java?


class Employee {
Employee( ) { //This is constructor. It has same name as class name.
System.out.println("This is the default constructor");
}
}
Types of Constructor
There are two types of constructors; depending upon the type, we can add and remove variables.

1. Default Constructor
2. Parameterized Constructor
.

1. Default Constructor
This is the one type of constructor. By default, without any parameters, this constructor takes place.
This constructor does not have any parameters in it.

Example:

class Abc{
Abc( ){
System.out.println("This is the example of default constructor.");
}
}

2. Parameterized Constructor
As the name suggests, the parameterized constructor has some parameters or arguments at the time of
initializing the object.

Example:

import java.util.*;
class Square{
int width,height;
Square( int a , int b){
width = a;
height = b;
}
int area( ){
return width * height;
}
}
class Cal{
public static void main(String[] args){
{
Square s1 = new Square(10,20);
int area_of_sqaure = s1.area();
System.out.println("The area of square is:" + area_of_sqaure);
}
}
}
Destructor
Before start talking about the destructor, let me tell you there is no destructor in java. Destructor is in
C++ programming language. If we are talking about java, then java has a feature called automatic
garbage collector. Which free the dynamically allocated memory when there is no use. This concept is
very important, and you can explore more about this garbage collection in java.

Java uses the garb collection technique for memory allocation automatically. There is no need to
explicit use of destructors like C++. For allocating memory in java, we do not have a malloc function
like in C programming. The new operator in java does the same process of allocating memory.
new keyword allocates memory space for an object on heap memory. At the time of program
execution, a new keyword allocates some memory space for the object. End-user need to worry about
this as the program handles memory allocation. At the time when the object used in programs done
with the work, the memory used for the object is utilized for another task. This process of utilizing
memory efficiently is the job of garbage collection in java.

As we know, there is no destructor in java as it has finalize() method to do so. The following are some
of the key points to be noted.

Finalize() Methods
 Finalize method is work like a destructor and opposite of a constructor, as we have seen
earlier.
 Generally, the finalize method is used to remove the object.
 For using this method, we have to define this method in java explicitly.
 The finalize method starts working after garbage collection done with its work.
 This simply means that after freeing memory space by deallocating memory space from
objects, there are chances that memory utilization still there with other things like fonts etc.,
to delete that memory space or to frees up that space, we make use of finalize() method.

Errors observed:
The constructor is undefined
Input:
Output:

FAQ:
Why do we need constructor and destructor in Java?
What are the different types of constructors?

References:

1. E. Balaguruswamy, Programming with Java: A Primer, McGraw Hill, 2009. ISBN:


9780070141698
2. R Nageswara Rao, Core Java, An Integrated Approach, Dreamtech Press, 2012. ISBN:
9788177228366

Conclusion:

1) Constructors are special methods used to initialize objects. They are invoked when an object is
created and are responsible for setting the initial state of the object. Constructors have the same
name as the class and do not have a return type.

2) On the other hand, Java does not have explicit destructors like some other languages. Instead, it
relies on automatic garbage collection. When an object is no longer reachable and no longer
referenced by any variables, the Java Virtual Machine (JVM) automatically reclaims the memory
occupied by that object.
Programming in Java

MIT Academy of Engineering, Alandi, Pune 412105


Department of Electronics & Telecommunication Engineering

Class : SY BTECH Subject – Java Programming

Name Of Student : Atharv mAhesh Musale

Roll No. : 250

Academic Year 2022 23

Experiment No. : 4

Date : 21/03/2023

Title : Function/operator overloading


Title: To study the function/operator overloading.

Aim of Experiment:
Write a program in Java to implement function/operator overloading.
Objective:
The objective of this assignment is to learn the concepts of polymorphism.

Theory:

Introduction to Function Overloading in Java


Function Overloading in Java occurs when there are functions having the same name but have
different numbers of parameters passed to it, which can be different in data like int, double, float and
used to return different values are computed inside the respective overloaded method. Function
overloading is used to reduce complexity and increase the efficiency of the program by involving more
functions that are segregated and can be used to distinguish among each other with respect to their
individual functionality. Overloaded functions are related to compile-time or static polymorphism.
There is also a concept of type conversion, which is basically used in overloaded functions used to
calculate the conversion of type in variables.

Syntax
Overloaded functions have the same name but different types of arguments or parameters assigned to
them. They can be used to calculate mathematical or logical operations within the number of assigned
variables in the method. The syntax of the overloaded function can be given below, where there are up
to N number of variables assigned.

public class Overloaded Method


{
public int FunctionName(int x, int y) //Two parameters in the function
{
return (x + y); //Returns the sum of the two numbers
}
// This function takes three integer parameters
public int FunctionName(int x, int y, int z)
{
return (x + y + z);
}
// This function takes two double parameters
public double FunctionName(double x, double y)
{
return (x + y);
}//Many more such methods can be done with different number of parameters
// Code used to input the number and
public static void main(String args[])
{
FunctionName s = new FunctionName();
System.out.println(s.FunctionName(10, 20));
System.out.println(s. FunctionName(10, 20, 30));
System.out.println(s. FunctionName(10.5, 20.5));
}
}

Working of Function Overloading


Function overloading works by calling different functions having the same name, but the different
number of arguments passed to it. There are many coding examples that can be shown in order to
identify the benefits and disadvantages of function overloading properly.

Advantage of Function Overloading


Function overloading works with the same name. So we do not have to create methods that have the
same thing as work that is done inside a respective function. The functionality not only resolves the
problem of conflicting naming but also improves the readability of the program.

Examples of Function Overloading

Example #1
In coding example 1, we will see overloaded main(), which is used to show different outputs in the
panel and show how the overloaded main() is used in programming languages and how the calling of
the different functions produces different outputs, respectively.

Code:

//Java program with overloaded main()


import java.io.*;
public class Test
{
// First main method which is created
public static void main(String[] args)
{
System.out.println("Main function called");
Test.main("Everyone");
}
// First overloaded main method
public static void main(String ar1)
{
System.out.println("Hi, " + ar1);
Test.main("Hello Everyone", "Buenos dias");
}
//Second overloaded main method
public static void main(String ar1, String ar2)
{
System.out.println("Mi todo eres tu, " + ar1 + ", " + ar2);
}
}

When the main() is called, there is output which is shown significantly in the output panel as shown
below. First, the print statement of the main() is called and printed. Then, by distinguishing the number
of arguments, the program separates the two overloaded functions which are present in the piece of
code. The main() calls the first overloaded function, while the first overloaded function calls the
second overloaded function.
Example #2
In the second coding example, we are going to see functions that will perform multiplication but which
will have a different number of arguments assigned to them. This will help people in developing the
different functions which are meant for dealing with different arguments.

Code:

class Adder
{
static int multiply(int a,int b)
{
return a*b;
}
static int multiply(int a,int b,int c)
{
return a*b*c;}
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.multiply(110,110));
System.out.println(Adder.multiply(110,110,110));
}
}

Input:
Output:

FAQ:
What are the two types of function overloading in Java?
Can we overload a static method?

References:

1. E. Balaguruswamy, Programming with Java: A Primer, McGraw Hill, 2009. ISBN:


9780070141698
2. R Nageswara Rao, Core Java, An Integrated Approach, Dreamtech Press, 2012. ISBN:
9788177228366

Conclusion:
1) Overloading enhances code readability and reusability, as it allows programmers to use intuitive
and consistent naming conventions. By choosing the appropriate overloaded function or operator
based on the arguments provided, Java enables the creation of more expressive and efficient
programs.
Programming in Java

MIT Academy of Engineering, Alandi, Pune 412105


Department of Electronics & Telecommunication Engineering

Class : SY BTECH Subject – Java Programming

Name Of Student : Atharv Mahesh Musale

Roll No. : 250

Academic Year : 2022 23

Experiment No. : 5

Date : 30/03/23

Title : Inheritance in Java


Title: To study the concepts of inheritance in Java.

Aim of Experiment:
Write a program in Java to create a player class. Inherit the child classes from parent classes

Objective:
The objective of this assignment is to learn the concepts of inheritance in Java.

Theory:
Inheritance can be defined as the process where one object acquires the properties of another. With the
use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance, the most commonly used keyword would be extends and implements.
These words would determine whether one object IS-A type of another. By using these keywords we
can make one object acquire the properties of another object.
IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is
used to achieve inheritance.
public class Animal{
}

public class Mammal extends Animal{


}

public class Reptile extends Animal{


}

public class Dog extends Mammal{


}
Now, based on the above example, In Object Oriented terms, the following are true:
● Animal is the superclass of Mammal class.
● Animal is the superclass of Reptile class.
● Mammal and Reptile are subclasses of Animal class.
● Dog is the subclass of both Mammal and Animal
classes. Now, if we consider the IS-A relationship, we can say:
● Mammal IS-A Animal
● Reptile IS-A Animal
● Dog IS-A Mammal
● Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Example:
public class Dog extends Mammal{

public static void main(String args[]){

Animal a = new Animal();


Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This would produce the following result:
true
true
true
Since we have a good understanding of the extends keyword let us look into how the implements
keyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended by the classes.
Example:
public interface Animal {}

public class Mammal implements Animal{


}

public class Dog extends Mammal{


}
The instanceof Keyword:
Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and
dog is actually an Animal
interface Animal{}

class Mammal implements Animal{}

public class Dog extends Mammal{


public static void main(String args[]){

Mammal m = new Mammal();


Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
This would produce the following result:
true
true
true
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HAS-A
certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put
the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed
class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real work.
To achieve this, the Van class hides the implementation details from the users of the Van class. So
basically what happens is the users would ask the Van class to do a certain action and the Van class
will either do the work by itself or ask another class to perform the action.
A very important fact to remember is that Java only supports only single inheritance. This means that a
class cannot extend more than one class. Therefore following is illegal:
public class extends Animal, Mammal{}
However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.

Input:
// Parent class
class Player {
protected Str ng name;
protected nt age;

publ c Player(Str ng name, nt age) {


th s.name = name;
th s.age = age;
}

publ c vo d d splayDeta ls() {


System.out.pr ntln("Name: " + name);
System.out.pr ntln("Age: " + age);
}
}

// Ch ld class 1
class Cr cketPlayer extends Player {
pr vate Str ng team;

publ c Cr cketPlayer(Str ng name, nt age, Str ng team) {


super(name, age);
th s.team = team;
}

publ c vo d d splayDeta ls() {


super.d splayDeta ls();
System.out.pr ntln("Team: " + team);
}
}

// Ch ld class 2
class FootballPlayer extends Player {
pr vate Str ng club;

publ c FootballPlayer(Str ng name, nt age, Str ng club)


{ super(name, age);
th s.club = club;
}

publ c vo d d splayDeta ls() {


super.d splayDeta ls();
System.out.pr ntln("Club: " + club);
}
}

publ c class PlayerDemo {


publ c stat c vo d ma n(Str ng[] args) {
Cr cketPlayer cr cketPlayer = new Cr cketPlayer("Sach n", 48,
"Ind a");
FootballPlayer footballPlayer = new FootballPlayer("Mess ", 34,
"Barcelona");

System.out.pr ntln("Cr cket Player Deta ls:");


cr cketPlayer.d splayDeta ls();

System.out.pr ntln("\nFootball Player Deta ls:");


footballPlayer.d splayDeta ls();
}
}

Output:

FAQ:
What is is-a-relationship and has-a-relationship?
What is extends, interface?

References:

3. E. Balaguruswamy, Programming with Java: A Primer, McGraw Hill, 2009. ISBN:


9780070141698
4. R Nageswara Rao, Core Java, An Integrated Approach, Dreamtech Press, 2012. ISBN:
978817722836
Conclusion:
Through inheritance, subclasses automatically acquire all the non-private fields and
methods of the superclass, allowing code reuse and promoting a hierarchical
organization of classes. This eliminates the need to duplicate code and promotes
modular and maintainable designs.To inheriting the superclass's members, subclasses
can also add new members or override inherited members to modify their behavior.
Programming in Java

MIT Academy of Engineering, Alandi, Pune 412105


Department of Electronics & Telecommunication Engineering

Class : SY BTECH Subject – Java Programming

Name Of Student : Atharv Musale

Roll No. : 250

Academic Year 2022 23

Experiment No. : 6

Date : 10/04/23

Title : Exception Handling in Java


Title: To study exceptional handling using try and catch

Aim of Experiment:
Write a Java program file handling using try catch block for exceptional handling.

Objective:
To study try and catch for exception handling.

Theory:

The exception handling in java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained. In this page, we will learn about java exception, its
type and the difference between checked and unchecked exceptions.

What is an exception :

Dictionary Meaning: Exception is an abnormal condition.

In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.

What is exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.

Hierarchy of Java Exception classes:


There are mainly two types of exceptions: checked and unchecked where error is considered
as unchecked exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions


1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

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

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

1. try
2. catch
3. finally
4. throw
5. throws

Java try block:

Java try block is used to enclose the code that might throw an exception. It must be used within the
method.

Java try block must be followed by either catch or finally block.


Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref) {}

Syntax of try-finally block

try{
//code that may throw exception
}finally{}
Input:

Output:

FAQ:
What is exception handling?
How to use try catch block?
When finally() method is called?
What is the difference between final, finally and finalize commands?

References:

1. E. Balaguruswamy, Programming with Java: A Primer, McGraw Hill, 2009. ISBN:


9780070141698
2. R Nageswara Rao, Core Java, An Integrated Approach, Dreamtech Press, 2012. ISBN:
9788177228366
Conclusion:
1) Exception handling using the try-catch block in Java is essential for gracefully handling and
recovering from unexpected errors during program execution. By enclosing potentially error-
prone code within a try block, we can continue program execution and provide a fallback
mechanism when an exception occurs.
2) The catch block allows us to specify the type of exception to catch and define appropriate error-
handling logic. This approach ensures robustness and prevents abrupt program termination,
enhancing the overall reliability and stability of Java applications.
Programming in Java

MIT Academy of Engineering, Alandi, Pune 412105


Department of Electronics & Telecommunication Engineering

Class : SY BTECH Subject – Java Programming

Name Of Student : Atharv Mahesh Musale

Roll No. : 250

Academic Year : 2022 23

Experiment No. : 7

Date : 21/04/2023

Title : Packages in Java


Title: To study concept of package in Java

Aim of Experiment:
Write a Java program which imports user defined package and uses members of the classes contained
in the package.

Objective :
The objective of this assignment is to learn concept of packages in Java.

Theory:
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java
can be categorized in two form, built-in package and user-defined package. There are many built-in
packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here, we will have the detailed
learning of creating and using user-defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Simple example of java package

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

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

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

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

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

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents
the current folder.

There are three ways to access the package from outside the package.import package.*;

1. import package.classname;
2. fully qualified name
3. Input:
Output:

FAQ:
How package is used?
What is way to access to package?
What is sub-package?
What is the importance of protected and default access specifier in relation to package.

References:

3. E. Balaguruswamy, Programming with Java: A Primer, McGraw Hill, 2009. ISBN:


9780070141698
4. R Nageswara Rao, Core Java, An Integrated Approach, Dreamtech Press, 2012. ISBN:
9788177228366

Conclusion:
1) A package is a way to organize related classes, interfaces, and other resources. It provides a
mechanism to group classes into logical units, making it easier to manage and organize large
codebases.
2) Packages help avoid naming conflicts by providing a unique namespace for classes. They also
promote code reusability and modularity by allowing classes to be encapsulated and accessed only
within the package or by classes explicitly granted access through modifiers like public or
protected.

Programming in Java
MIT Academy of Engineering, Alandi, Pune 412105
Department of Electronics & Telecommunication Engineering

Class : SY BTECH Subject – Java Programming

Name Of Student : Atharv Mahesh Musale

Roll No. : 250

Academic Year : : 2022 23

Experiment No. : 8

Date : 09/05/23

Title : Interfaces in Java


Title: Write a Java program which implements interface.

Aim of Experiment:
Write a program in java to implement interface using suitable example.

Objective :
The objective of this assignment is to learn the concept of interface and its implementation.

Theory:
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
Following is an example of an interface −

/* 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\

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

This will produce the following result –

Output

Mammal eats
Mammal
travels
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.

Extending Interfaces
An interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods of
the parent interface.

The following Sports interface is extended by Hockey and Football interfaces.

Example
// Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to
define the three methods from Football and the two methods from Sports.

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 −

Example
public interface Hockey extends Sports, Event

Input:

Output:
Application:
 Abstraction and Polymorphism
 API Design
 Multiple Inheritance of Type
FAQ:
What is the advantage of implementing interface?
How to implement multiple inheritance using
interface

References:

5. E. Balaguruswamy, Programming with Java: A Primer, McGraw Hill, 2009. ISBN:


9780070141698
6. R Nageswara Rao, Core Java, An Integrated Approach, Dreamtech Press, 2012. ISBN:
9788177228366

Conclusion:

Implementing interfaces promotes code reuse, flexibility, and separation of concerns,


as different classes can implement the same interface and provide their own unique
implementations. Interfaces are widely used in API design, event handling, dependency
injection, and unit testing, among other areas. They enable multiple inheritance of type
and facilitate loose coupling between components.

You might also like