3 Mech - Java Programming Unit 2
3 Mech - Java Programming Unit 2
proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
JAVA PROGRAMMING
Created by :
Dr J.Sathiamoorthy Associate Professor / CSE
Date : 08.08.2022
4
1. CONTENTS
Page
S. No. Contents
No
1 Contents 5
2 Course Objectives 6
3 Pre Requisites 7
4 Syllabus 8
5 Course outcomes 9
7 Lecture Plan 11
9 Lecture Notes 15
10 Assignments 89
5
2. COURSE OBJECTIVES
6
3. PRE REQUISITES
• Pre-requisite Chart
7
4. SYLLABUS
OUTCOMES:
At the end of this course, the students will be able to:
CO1: Understand the Object Oriented Programming concepts and fundamentals of Java
CO2: Develop Java programs with the packages, inheritance and interfaces
CO3: Build applications using Exceptions and Threads.
CO4: Build Java applications with I/O streams and generics classes
CO5: Use Strings and Collections in applications
8
5. COURSE OUTCOME
CO4 Build Java applications with I/O streams and generics classes K3
9
6. CO - PO / PSO MAPPING
C203.1 K3 3 3 3 - - - - - - - - - 3 2 2
C203.2 K3 3 2 2 - - - - - - - - - 3 2 2
C203.3 K3 3 2 2 - - - - - - - - - 3 2 2
C203.4 K3 3 2 2 - - - - - - - - - 3 2 2
C203.5 K3 3 2 2 - - - - - - - - - 3 2 2
10
7. LECTURE PLAN : UNIT – II
Highe
Proposed Actual st
S. Mode of Delivery
Lecture Topic Lecture CO Cognit LU Outcomes Remark
No Delivery Resources
Date Date ive
Level
Apply Packages in
MD1 &
8 Importing Packages K3 T1 Java Programming
MD5
2 3
5 6 7
10
11 12
13 14
15 16
17 18
19
Across
2. Hiding internal details and showing functionality is
6. Any entity that has state and behavior is known as
9. The ______is accessible everywhere
11. When one task is performed by different ways known as
14. _______keyword Used in a class declaration to specify the superclass; used in an interface
declaration to specify one or more super interfaces.
15. When one object acquires all the properties and behaviors of parent object known as
16. can be used to refer immediate parent class instance variable or method.
17. Binding (or wrapping) code and data together into a single unit is known as
19. The __________ is accessible only within package
Down
1. Java automatically frees the used memory for other uses
3. class which is the superclass of all classes
4. is a special type of method that is used to initialize the object.
5. keyword Included in a class declaration to specify one or more interfaces that are used by
the current class.
7. Collection of objects is called . It is a logical entity.
8. is a group of similar types of classes, interfaces, and sub- packages.
10. the________is accessible within a package and outside the
package but through inheritance only
12. keyword is used to apply restrictions on class, method, and variable.
13. The______is accessible only within class
18. Classes maintain one copy of class variables regardless of how many instances exist of that
class.
SCRAMBLED WORDS
LCIBUP _________________________
DFUEATL __________________________
ACITTS __________________________
OTCEJB __________________________
ERITPAV __________________________
TABTANCISOR __________________________
CASSL __________________________
NMSITLEEPM __________________________
GPEACKA __________________________
OABELGNLETOCACGIR __________________________
SOURCTOCTNR __________________________
DTXNEES __________________________
SRIPMHMLYOPO __________________________
ERPUS __________________________
LAFNI __________________________
JBETCO __________________________
OREPECTDT __________________________
PIEATLSUNNACO __________________________
HANETREINIC __________________________
WORD SEARCH
G A R B A G E C O L L E C T I O N
V K N D X R E P U S O K K Q L D N
P O A O S S A L C T F B D Q G H B
M T B C I G P H Z O I Q J G Y A O
R W H J O T I U W J N Y G E B T I
W Q R E E N A T B G A G F W C S P
N D B C Y C S L T L L T T G G T O
P O P N P W T T U T I B C E D N L
R C I A E G T T R S D C H E L E Y
O V S T A T I C Y U P T F D C M M
T H Y I C T A D E D C A J X V E O
E Q R R V A T V K X U T C P A L R
C O T E Q E R L I L T I O N G P P
T P T H W K D T T R W E R R E M H
E V S N F U K A S Y P T N O D I I
D O G I H H O L C B E L V D W J S
V J S P A C K A G E A Z I P S K M
• Inheritance can be defined as the process of acquiring all the properties and
behaviors of one class to another
• Acquiring the properties and behavior of child class from the parent class
• Inheritance represents the IS-A relationship, also known as parent-child
relationship which is illustrated in Figure 2.1
Syntax:
class subClass extends superClass
{
//methods and fields
}
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
Super Class/Parent Class: Superclass is the class from where a subclass inherits
Example:
class Fruit
{
String taste = “Sweet";
void printTaste()
{
System.out.println(“Taste is: " + taste);
}
}
class Mango extends Fruit
{
String name = “Mango";
void printName()
{
System.out.println("Name is: " + name);
}
}
class SingleDemo
{
public static void main(String args[])
{
Mango m1 = new Mango();
m1.printTaste();
m1.printName();
}
}
OUTPUT
Taste is: Sweet
Name is: Mango
Hierarchical Inheritance
Process of extending more than one subclasses from single super
class Fruit
{
String taste = “Sweet";
void printTaste()
{
System.out.println(“Taste is: " + taste);
}
}
class Mango extends Fruit
{
String name = “Mango";
void printName()
{
System.out.println("Name is: " + name);
}
}
class Apple extends Fruit
{
String name = “Apple";
void printName()
{
System.out.println("Name is: " + name);
}
}
class HierarchicalDemo
{
public static void main(String args[])
{
Mango m1 = new Mango();
m1.printTaste();
m1.printName();
Apple a1 = new Apple();
a1.printTaste();
a1.printName();
}
}
OUTPUT
Taste is: Sweet
Name is: Mango
Taste is: Sweet
Name is: Apple
MULTILEVEL INHERITANCE
Process of extending subclass from another sub class. Figure 2.5
OUTPUT
Taste is: Sweet
Name is: Mango
Weight is: 2
HYBRID INHERITANCE
Process of extending new classes by combining more than one forms of
inheritance. Figure 2.6 illustrates Hybrid Inheritance which combines Multilevel and
Hierarchical Inheritances.
OUTPUT
Taste is: Sweet
Name is: Mango
Taste is: Sweet
Name is: Papaya
Weight is: 5
Protected
members
Protected Members
OUTPUT
Accessing Protected member of Super class
Total : 30
Constructors
in sub classes
Constructors in sub classes
Syntax
subclassname()
{
super();
//
}
super() should be the first statement in subclass constructor
Uses of super
class A
{
A()
{
System.out.println("Base Class default Constructor");
}}
public class B extends A
{
B()
{
super();
System.out.println("Derived Class default Constructor");
}
public static void main(String args[])
{
B b = new B();
}}
Output:
Base Class default Constructor
Derived Class default Constructor
Uses of super
In the above example since the variable val is present in both super class and
subclass superclass value will be overridden by the subclass. So the val 20
gets printed.
Uses of super
Case 2: If we want to access the superclass val, then we should use the
keyword super.
class A
{
int val=10;
}
public class B extends A
{
int val=20;
void disp()
{
System.out.println("Value is : "+super.val);
}
public static void main(String args[])
{
B b = new B();
b.disp();
}}
Output :
Value is: 10
Uses of super
a) super
b) this
c) extent
d) extends
6. If super class and subclass have same variable name, which keyword
should be used to use super class?
a) super
b) this
c) upper
d) classname
7. What would be the result if a class extends two interfaces and both
have a method with same name and signature? Lets assume that the class
is not implementing that method.
a) Runtime error
b) Compile time error
c) Code runs successfully
d) First called method is executed successfully
}
}
public class Program {
public static void main(String[] args) {
Cat c = new Cat();
}
}
Method
Overriding
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java. In other words, If a subclass provides the
specific implementation of the method that has been declared by one of its parent
class, it is known as method overriding
Usage of Java Method Overriding
1. Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
2. Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance)
Example Program
import java.util.Scanner;
interface maths
{
public void add();
public void sub();
public void mul();
public void div();
}
class Arithmetic implements maths
{
@Override
public void add()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values to perform addition");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a + b;
System.out.println("Sum of "+a+" and "+b+" is "+s);
}
Method Overriding
@Override
public void sub()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values to perform subtraction");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a - b;
System.out.println("Difference of "+a+" and "+b+" is "+s);
}
@Override
public void mul()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values multiplication");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a * b;
System.out.println("Product of "+a+" and "+b+" is "+s);
}
@Override
public void div()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter any two integer values division");
int a = kb.nextInt();
int b = kb.nextInt();
int s = a / b;
System.out.println("Quotient of "+a+" and "+b+" is "+s);
}
} // Arithmetic
Method Overriding
public class Main
{
Output :
Enter any two integer values to perform addition
10
10
Sum of 10 and 10 is 20
Enter any two integer values to perform subtraction
20
10
Difference of 20 and 10 is 10
Enter any two integer values multiplication
10
10
Product of 10 and 10 is 100
Enter any two integer values division
1000
10
Quotient of 100 and 10 is 10
Abstract Classes
abstract void sum(int x, double y); //no method body and abstract
Abstract method can only be used in an abstract class, and it does not have a
body.
If a class includes abstract methods, then the class itself must be
declared abstract.
Example:
public abstract class demo
{
// declare fields
// declare nonabstract methods
abstract void draw();
}
Example:
abstract class shape
{
public abstract void draw();
public void paint()
{
System.out.println(“R.M.D Engineering College");
}
public static void main(String args[])
{ shape obj= new shape(); // will generate an error
}
}
When this program gets executed, it will give compilation error, because it is
not possible to create an object of the abstract class shape.
Inheritance of Abstract Classes and Methods
Program:
abstract class Shape
{
int a=3,b=4;
abstract void Area();
}
class Rectangle extends shape
{
int rectarea;
void Area()
{
rectarea=a*b;
System.out.println(“Area of rectangle is:“ +rectarea);
} }
class Triangle extends Shape
{
int triarea;
void Area()
{
triarea=(int) (0.5*a*b);
System.out.println(“Area of triangle is:“ +triarea);
}}
class Circle extends Shape
{
int circlearea;
void printarea()
{
circlearea=(int) (3.14*a*a);
System.out.println(“Area of circle is:“+circlearea);
} }
public class Demo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.Area();
Triangle t=new Triangle();
t.Area();
Circle c=new Circle();
c.Area();
} }
OUTPUT:
Area of rectangle is: 12
Area of triangle is: 6
Area of circle is: 28
Abstract class with constructor, data member &
methods
An abstract class can have a data member, abstract method, non-
abstract method and constructor.
An abstract class can contain constructors in Java.A constructor of abstract class is
called when an instance of a inherited class is created.
Example :
abstract class Shape
{
Shape()
{
System.out.println(“Shape Class Created");
}
abstract void area();
void print()
{
System.out.println(“Abstraction using Constructors");
} }
//Creating a Child class which inherits Abstract class
class Rectangle extends Shape
{
void area()
{
System.out.println(“Area of Rectangle is length * breadth");
} }
//Creating a Test class which calls abstract and non-
abstract methods
class TestDemo
{
public static void main(String args[])
{
Rectangle r = new Rectangle();
r.area();
r.print();
} }
Output:
Shape Class Created
Area of Rectangle is length * breadth
Abstraction using Constructors
Overriding of Abstract Methods
In Java, it is mandatory to override abstract methods of the superclass in the
subclass. It is because the subclass inherits abstract methods of the
superclass.
Since the subclass includes abstract methods, we need to override them.
Note: If the subclass is also declared abstract, it's not mandatory to override
abstract methods.
Example:
abstract class Car
{
abstract void makeSound();
public void run()
{
System.out.println(“Running smoothly.");
}}
class Honda extends Car
{
public void makeSound()
{
System.out.println(“Noise Created");
}}
class Demo1
{
public static void main(String[] args)
{
Honda s= new Honda();
s.makeSound();
s.run();
}}
Output:
Noise Created
Running smoothly
We have created an abstract class Car. The class contains an abstract method
makeSound() and a non-abstract method run(). The subclass Car overrides
the abstract method makeSound().
Quiz
1. Which of these class is superclass of every class in Java
a) String class
b) Object class
c) Abstract class
d) ArrayList class
class Output
System.out.print(obj.getclass());
a) Object
b) class Object
c) class java.lang.Object
d) Compilation Error
• 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.
• Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
Since the package creates a new namespace there is no chance for any name
conflicts with names in other packages. Using packages, it is easier to provide
access control and it is also easier to locate the related classes.
Creating a Package
While creating a package, name for the package is chosen and included in
the package statement at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that are included in the package.
The package statement should be the first line in the source file.
There can be only one package statement in each source file, and it applies to all
types in the file. If a package statement is not used then the class, interfaces,
enumerations, and annotation types will be placed in the current default package.
To compile the Java programs with package statements, you have to use -d option
as shown below.
Then a folder with the given package name is created in the specified destination,
and the compiled class files will be placed in that folder
Now a package/folder with the name mypack will be created in the current directory
and these class files will be placed in it for the Example Code 1.
Example Code 1:
Syntax
Example to Compile:
javac -d . Simple.java
Example to Execute:
java mypack.Simple
Example Code 2:
// Create a Java Source File named A.java
package pack;
public class A {
public int Add(int a, int b) {
return (a + b);
}
}
do {
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Multiplication");
System.out.println("4.Exit");
System.out.println("Enter the choice");
ch = in.nextInt();
switch (ch) {
case 1:
A a = new A();
d = a.Add(a1, b1);
System.out.println("Addition values:" + d);
break;
case 2:
B b = new B();
d = b.Sub(a1, b1);
System.out.println("Subtraction values:" + d);
break;
case 3:
C c = new C();
d = c.Mul(a1, b1);
System.out.println("Multiplication values:" + d);
break;
}
} while (ch < 4);
}
}
Output:
Enter the first value: 5
Enter the Second Value: 6
1.Addition
2.Subtraction
3.Multiplication
4.Exit
Enter the choice
1
Addition values:11
1.Addition
2.Subtraction
3.Multiplication
4.Exit
Enter the choice
2
Subtraction values:-1
1.Addition
2.Subtraction
3.Multiplication
4.Exit
Interfaces:
Defining an interface, implementing interface,
differences between classes and interfaces and
extending interfaces
Interface in Java
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Internal addition by compiler
The java compiler adds public and abstract keywords before the interface method.
More, it adds public, static and final keywords before data members. In other words,
Interface fields are public, static and final by default, and methods are public and
abstract.
interface Bank {
float rateOfInterest();
}
}
}
Example:
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A6 obj = new A6(); obj.print();
}
}
Output:
Hello
Example:
interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();
d.draw();
}
}
Output:
drawing circle
Example
interface printable
{
void print();
interface MessagePrintable
{
void msg();
}
}
interface A
int x=10;
interface B
int x=100;
}
class Hello implements A,B
{
public static void Main(String args[])
{
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}
1)Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods. Sinc Java 8, it can have default and static
methods also.
2)Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.
3)Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4)Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5)The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
7) An abstract class can be extended using An interface class can be implemented using
keyword extends. keyword implements
Quiz
1. Which of these can be used to fully abstract a class from its
implementation?
a) Objects
b) Packages
c) Interfaces
a) True
b) False
a) public static
b) private final
c) public final
d) static final
a) Method definition
b) Method declaration
d) Method name
5. What type of methods an interface contain by default?
a) Abstract
b) Static
c) Final
d) private
a) The concrete class implementing that method need not provide implementation
of that method
b) Runtime exception is thrown
c) Compilation failure
d) Method not found exception is thrown
7. What happens when a constructor is defined for an interface?
a) Compilation failure
b) Runtime Exception
c) The interface compiles successfully
d) The implementing class will throw exception
a) Compilation failure
b) Runtime Exception
c) The JVM is not able to identify the correct variable
d) The interfaceName.variableName needs to be defined
Predict the output of the following code snippets
Example
Output :
We will get the compile time error like “The type Child cannot subclass the final
class Parent”.
Exception in thread "main" java.lang.Error: Unresolved compilation problem
Static Methods in a Interface
Static Methods in Interface are those methods, which are defined in
the interface with the keyword static. Unlike other methods in Interface, these static
methods contain the complete definition of the function and since the definition is
complete and the method is static, therefore these methods cannot be overridden or
changed in the implementation class.
a simple static method is defined and declared in an interface which is
being called in the main() method of the Implementation Class InterfaceDemo.
Unlike the default method, the static method defines in Interface hello(), cannot be
overridden in implementing the class.
interface NewInterface
{
static void hello() // static method
{
System.out.println("Hello, New Static Method Here");
}
// Implementation Class
public class InterfaceDemo implements NewInterface {
2. Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains only the method print Area () that prints the
area of the given shape.
3. Develop a Java application to generate Electricity bill. Create a class with the
following members: Consumer no., consumer name, previous month reading,
current month reading, type of EB connection (i.e domestic or commercial).
Compute the bill amount using the following tariff.
• First 100 units - Rs. 1 per unit 101-200 units - Rs. 2.50 per unit
• 201 -500 units - Rs. 4 per unit > 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as
follows:
• First 100 units - Rs. 2 per unit 101-200 units - Rs. 4.50 per unit
• 201 -500 units - Rs. 6 per unit > 501 units - Rs. 7 per unit
4. Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains only the method print Area () that prints the
area of the given shape.
11. Part A
Question and Answers
PART - A
• Form this above figure, Class A is being inherited by Class B. So, Class A is a
Super class or Base class.
• Form this above figure, Class B is inherits the properties of Class A. So, Class
B is a Sub class or Derived class.
• Here, Class A is a parent class and Class B is a child class which inherits the
properties and behavior of the parent class.
• A is the parent class for B and class B is the parent class for C.
• Here, class B inherits the properties and behavior of class A and class C
inherits the properties of class B.
• So in this case class C implicitly inherits the properties and methods of class
A along with Class B.
• Here, Class B and C are the child classes which are inheriting from the parent
class i.e Class A.
11. Tell, Can you use both this() and super() in a Constructor? (K1)(CO2)
• NO, because both super() and this() must be first statement inside a
constructor. Hence we cannot use them together.
13. What are the rules for creating abstract method? (K1)(CO2)
• Method that is declared without any body within an abstract class is
called abstract method.
• Syntax:
abstract return_type function_name();
• The definition of abstract method is should be in the child class.
Class Roll
Class Student
24. What is the difference between a static and a non-static inner class?
(K1)(CO2)
• A non-static inner class may have object instances that are associated with
instances of the class's outer class. A static inner class does not have any
object instances.
3. How to define an interface? Why do the members of interface are static and
final? (13) (K3)(CO2)
6. Define Package? How does compiler locate packages? Explain arrays in java?
(K1, CO1)
13. Online Certifications
1. https://www.hackerrank.com/skills-verification/java_basic
2. https://www.sololearn.com/Course/Java/
3. https://www.coursera.org/specializations/object-oriented-programming
4. https://www.udemy.com/course/java-the-complete-java-developer-course/ [Paid]
5. https://nptel.ac.in/courses/106/105/106105191/ [Paid]
6. https://education.oracle.com/java-se-8-fundamentals/courP_3348 [Paid]
14. Real Time Applications
• Scientific Applications
• Financial Applications
• Games
• Desktop Applications
• Web Applications
103
15. Content Beyond Syllabus
Multiple inheritance in Java by interface
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class MultipleDemo implements Printable,Showable
{
public void print(){System.out.println("Hello");
}
public void show(){System.out.println("Welcome");
}
Name of the
S.NO Start Date End Date Portion
Assessment
105
17. Prescribed Text Books and References
TEXTBOOK:
REFERENCES:
Normal 4%
NRI 6%
Requirements:
1. Separate classes should be created for the different types of
accounts.
2. All classes should be derives from an abstract class named
‘Account’ which contains a method called ‘calculateInterest’.
3. Implement the calculateInterest method according to the type of
the account, interest rates, amount and age of the account holder.
4. If the user is entering any invalid value (For eg. Negative value) in
any fields, raise a user defined exception.
Sample class structure is given below:
Account(Abstract)
double interestRate
double amount
FDAccount
double interestRate
double amount
int noOfDays
ageOfACHolder
abstract double calculateInterest()
SBAccount
double interestRate
double amount
abstract double calculateInterest()
RDAccount
double interestRate
double amount
int noOfMonths;
double
monthlyAmount;
abstract double calculateInterest()
Disclaimer:
This document is confidential and intended solely for the educational purpose of RMK Group of
Educational Institutions. If you have received this document through email in error, please notify the
system manager. This document contains proprietary information and is intended only to the
respective group / learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender immediately by e-mail if you
have received this document by mistake and delete this document from your system. If you are not
the intended recipient you are notified that disclosing, copying, distributing or taking any action in
reliance on the contents of this information is strictly prohibited.