Y23 Aoop Co1&co2 - Notes
Y23 Aoop Co1&co2 - Notes
( AOOP - R/A/E )
Lecture Notes
Prepared By
Dr MSR PRASAD
SEC-11 Adv
SYLLABUS
CO-1
1. Design Patterns
Creational Patterns
Structural Patterns
Behavioral Patterns
SOLID Principles
Code Smells
Refactoring Techniques
CO-2
Introduction to Generics, Usage of Generics with Interfaces, Building Stacks, Queues, and
Priority Queues
Introduction to Multithreading and Parallel Programming, Thread Concepts & States, Creating
Tasks & Threads, Thread Classes, Thread Pools, Thread Synchronization & Locks, Cooperation
Among Threads, Case Study: Producer/Consumer, Blocking Queues, Semaphores, Deadlock
Avoidance, Synchronized Collections & Parallel Programming
CO-4
JDBC: API, Components, Architecture (2-Tier & 3-Tier), Drivers & Their Types, Packages for JDBC
Connection, Steps to Connect to Databases (PostgreSQL)
7. Servlets
Overview, Life Cycle of a Servlet, Attributes in Servlets, Interaction Between Client & Servlet,
Servlet Demo Application Development with Sessions
Overview & Advantages Over Servlets, Features and Syntax, Life Cycle of JSP, Environmental
Setup for JSP, Interaction Between Client, JSP & Server, JSP Demo Application Development
CO - 1
SHORT ANSWER QUESTIONS ( from CO-1 )
1. Types of inheritance
Answer:
a) multilevel b) multiple c) Hierarchical d) hybrid inheritance
Answer:
The observer design pattern is a behavioral design pattern that's useful when you
want to be notified of changes to an object's state. In this pattern, the object being
monitored is called the subject, and the object that monitors it is called the observer.
It supports the principle of loose coupling between objects that interact with each
other. It allows sending data to other objects effectively without any change in the
Subject or Observer classes. Observers can be added/removed at any point in time.
the strategy design pattern is a behavioral pattern that allows for the selection of an
algorithm during runtime. It provides flexibility and reusability by enabling the
calling code to choose from a set of algorithms instead of implementing a single
one.
It allows you to define a family of algorithms, encapsulate each one, and make them
interchangeable. It enables you to select and use an algorithm at runtime without
tightly coupling the client code to a specific implementation.
Implementation comments - The target audience is the developers that work on the
codebase.
Variables are used to represent data items in program. Variables are declared with
data types.
Eg . int marks;
boolean flag;
a) length
b) begin with small letter or underscore
c) special characters used
Class methods: they are static methods called by its class or by any object.
Instance method : they are non static methods , called by only object of the class.
Eg.
Class Hamper{
Static void show(){
}
Void display(){
}
Public static void main(String[] args){
Hamper h1 = new Hamper();
Hamper. Show(); // static method call
h1.dispaly(); // non static method call
}
}
LONG ANSWER QUESTIONS ( from CO-1 )
class DemoInh1{
public static void main(String[] args){
Animal aa = new Animal();
Human hh = new Human();
Monkey mm = new Monkey();
aa.eat();
aa.sleep();
mm.eat();
mm.jump();
hh.study();
hh.eat();
hh.sleep();
}
}
Answer:
Method Overriding: redefining a method from its super class. method overriding,
is an example of runtime polymorphism where as method over loading is the
example for compile time polymorphism.
Program:
class Monkey implements Animal{
public void eat(){
System.out.println("Monkeys eat vegitarian food");
}
public void sleep(){
System.out.println("Monkeys sleep on trees");
}
void jump(){
System.out.println("Monkeys jumps from tree to tree");
}
}
mm.eat();
mm.jump();
hh.study();
hh.eat();
hh.sleep();
}
}
Program:
abstract class Car {
abstract void steering();
abstract void breaking();
}
Class Maruthi extends Car{
@override
void steering(){
System.out.println(“ steering helps in turning the car
towards right and left”);
}
void breaking(){
System.out.println(“ breaks helps in slow down/stopping
the car”);
}
}
Class Demo{
Public static void main(String[] args){
Car c1 = new Maruthi();
c1. Steering();
c1.breaking();
}
}
Program:
abstract class Brazo {
abstract void callMe();
}
Class Carzo extends Brazo{
@override
void callMe(){
System.out.println(“ overriding callMe method from Brazo
calss”);
}
}
Class Demo{
Public static void main(String[] args){
Brazo b1 = new Carzo();
b1. callMe();
}
}
Program:
interface Animal {
void eat();
void sleep();
}
class DemoInh1{
public static void main(String[] args){
Human hh = new Human();
Monkey mm = new Monkey();
mm.eat();
mm.jump();
hh.study();
hh.eat();
hh.sleep();
}
}
6. Interface - Example program -2
Answer:
overridden methods of interface are public only, demonstration of the statement is
the following statement.
Program :
interface One {
void callMe();
}
void show(){
System.out.println(" Today is Sunny day ");
}
}
class DemoIntf1 {
public static void main(String[] args){
IntImpl if1 = new IntImpl();
if1.callMe();
if1.show();
}
}
7. Interface –Example program -3 ( Extends key word)
Answer:
Interfaces can be extended, as they follow inheritance of OOP concept.
Program :
interface One {
void callMe();
}
interface Two extends One {
void callMeToo();
}
// concrete class
class IntImpl implements Two {
public void callMe(){
System.out.println("callme: output");
}
public void callMeToo(){
System.out.println("callmeToo: output");
}
void show(){
System.out.println(" Today is wednesday");
}
}
class DemoIntf3 {
public static void main(String[] args){
IntImpl if1 = new IntImpl();
if1.callMe();
if1.callMeToo();
if1.show();
}
}
Program :
interface One{
void callMe();
}
class Hello{
void greet(){
System.out.println("Hello world");
}
}
class DemoIntf5{
public static void main(String[] args){
HelloOne ho1 = new HelloOne();
ho1.callMe();
ho1.greet();
ho1.show();
}
}
1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can have static methods, Interface can't have static methods, main
main method and constructor. method or constructor.
5) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Important points:
1. Private default constructor
2. Static object
3. Static method to return the object to the caller.
4. Number of utility methods to be used by the object
Program :
class Hello{
private Hello(){
}
static Hello obj = new Hello();
void show(){
System.out.println("Hello World");
}
}
class DemoSing1 {
public static void main(String[] args){
Hello h1 = Hello.getObject();
h1.show();
}
}
The pattern encapsulates object creation logic in a separate class, making the code
more flexible and maintainable. It also promotes loose coupling by eliminating the
need to bind application-specific classes into the code. This means the code only
interacts with the abstract class or resultant interface, so it can work with any
classes that extend or implement that interface.
Program:
import java.util.Scanner;
interface Shape{
void draw();
}
class ShapeFactory {
Shape getShape(int x){
if (x==1)
return new Circle();
else if(x==2)
return new Square();
else if(x==3)
return new Rectangle();
else
return null;
}
}
class DemoFact1 {
public static void main(String[] args){
Shape sh;
int x;
ShapeFactory shft= new ShapeFactory();
Scanner in = new Scanner(System.in);
System.out.println("Enter 1/2/3 for circle/square/rect
:");
x=in.nextInt();
sh= shft.getShape(x);
sh.draw();
}
}
class BankFactory {
Service getService(int x){
if (x==1)
return new SBI();
else if(x==2)
return new HDFC();
else if(x==3)
return new ICICI();
else return null;
}
}
class FactoryDemo{
public static void main(String[] args){
Service sh;
int bank;
Scanner in = new Scanner(System.in);
System.out.println(" Enter 1/2/3 for SBI/HDFC/ICICI
banks”);
bank= in.nextInt();
BankFactory bf = new BankFactory();
sh= bf.getService(bank);
sh.loanPayment();
}
}
Factory Method Pattern allows the sub-classes to choose the type of objects to
create. It promotes the loose-coupling by eliminating the need to bind application-
specific classes into the code.
Abstract Factory design – block diagram
Program:
interface Shape{
void draw();
}
class FactoryProducer{
static AbsFactory getFactory(int x){
if (x==1)
return new ShapeFactory();
else if (x==2)
return new RoundedShapeFactory();
else return null;
}
}
class AbsFactDemo1{
public static void main(String[] args){
AbsFactory abf;
Shape sh;
abf = FactoryProducer.getFactory(2);
sh= abf.getShape(2);
sh.draw();
}
}
Program :
// Agrigation program – object as a instance variable (through constructor)
class Address {
String d_no;
String city;
void show_details(){
System.out.println("Door no -> "+d_no);
System.out.println("city -> "+ city);
}
}
class Employee {
String name;
String emp_no;
Address ad;
void show_details(){
ad.show_details();
System.out.println("name -> "+ name);
System.out.println("emp no -> "+emp_no);
}
}
class Aggregation1{
public static void main(String[] args){
Aggregation:
Class contains object of another class as it’s instance variable or as a local variable
so that all the members of the class can be accessed.
Advantages:
Structural patterns explain how to assemble objects and classes into larger
structures while keeping these structures flexible and efficient. These patterns help
make it easier to identify a simple way to realize relationships between entities.
SpCrikPlayer class is acting like a connector to get methods from both of the
interfaces.
Program :
interface Cricket{
void playCricket();
}
interface Hockey{
void playHockey();
}
class CricPlayer implements Cricket{
public void playCricket(){
System.out.println(" playing cricket is my passion");
}
}
class AdoptDemo1 {
public static void main(String[] args){
Cricket ck, sck;
Hockey hk;
hk= new HockPlayer();
hk.playHockey();
ck = new CricPlayer();
sck = new SpCrikPlayer();
ck.playCricket();
sck.playCricket();
}
}
interface Duck{
void kwack();
}
class AdoptDemo2 {
public static void main(String[] raga){
Parrot p1;
Duck d1;
}
}
interface Deco{
void display();
}
class BridgeDemo1{
public static void main(String[] msr){
Shape sh;
Deco dc;
sh = new Rectangle();
dc = new Deco1(sh);
dc.display();
}
}
20. Bridge design Pattern (Example-2)
Answer:
The Bridge design pattern separates an abstraction from its implementation,
allowing both to change independently. This structural pattern increases flexibility
and maintainability in complex systems.
Program:
interface Bank{
void show();
}
interface Account{
void openAcc();
}
class BridgeDemo2{
public static void main(String[] msr){
Bank bnk;
Account acc;
acc = new SavingAcc();
bnk = new Axis(acc);
bnk.show();
The Facade pattern offers the following benefits: It shields clients from subsystem
components, thereby reducing the number of objects that clients deal with and
making the subsystem easier to use. It promotes weak coupling between the
subsystem and its clients. Often the components in a subsystem are strongly
coupled.
Program:
void draw();
System.out.println(" I am a Rectangle");
System.out.println(" I am a square");
System.out.println(" I am a circle");
}
class ShapeMaker {
public ShapeMaker() {
void drawCircle(){
circle.draw();
void drawRectangle(){
rectangle.draw();
void drawSquare(){
square.draw();
}
class DemoFacadePattern1 {
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
interface MobilePhone {
void modelNo();
void price();
}
ShopKeeper(){
iphone= new Iphone();
samsung=new Samsung();
blackberry=new Blackberry();
}
void iphoneSale(){
iphone.modelNo();
iphone.price();
}
void samsungSale(){
samsung.modelNo();
samsung.price();
}
void blackberrySale(){
blackberry.modelNo();
blackberry.price();
}
}
class DemoFacade2 {
public static void main(String args[]) {
sk.iphoneSale();
sk.samsungSale();
sk.blackberrySale();
}
}
Advantages:
Model diagram:
24. Template design pattern for “making Tea” – Example program
Program:
abstract class Drink{
abstract void boilWater();
abstract void addTeaPowder();
abstract void addSugar();
abstract void serveTea();
void addTeaPowder(){
System.out.println("add TEA powder and milk ");
}
void addSugar(){
System.out.println("add sugar as per your taste ");
}
void serveTea(){
System.out.println("Serve Tea in cups");
}
}
class TempDemo2{
public static void main(String[] args){
Drink gg;
gg= new Tea();
gg.makeTea();
}
}
hasNext() method will check whether next element is there in the list or not,
accordingly returns true if available otherwise returns false.
next() method will return the next element from the list if available.
Both these methods are made available through a interface, any class implementing
this interface can use both of these methods.
The implemented class must take care of objects of any type may be String or any
user defined type.
interface Iterator {
public boolean hasNext();
public Object next();
}
interface Iterator {
Object next();
boolean hasNext();
}
class IteratorDemo1{
public static void main(String[] msr){
NameIterator ni = new NameIterator();
while(ni.hasNext())
System.out.println((String) ni.next());
}
}
interface Iterator {
Object next();
boolean hasNext();
}
class IteratorDemo2{
public static void main(String[] msr){
NumIterator ni = new NumIterator();
while(ni.hasNext())
System.out.println((Integer) ni.next());
}
}
28. Command Design Pattern (Example program-1)
Answer:
The Command design pattern is a behavioral pattern that transforms a request into a
stand-alone object. It focuses on separating the sender of a request from the
receiver.
class WatchSon{
void bringVeg(){
System.out.println(" brought vegitables");
}
}
class WatchMan{
WatchSon ws;
WatchMan(WatchSon ws1){
ws = ws1;
}
void bringVeg(){
ws.bringVeg();
}
}
class Husband{
WatchMan wm;
Husband(WatchMan wm1){
wm = wm1;
}
void bringVeg(){
wm.bringVeg();
}
}
class CommandDemo1{
public static void main(String[] msr){
WatchSon w1 = new WatchSon();
WatchMan w2 = new WatchMan(w1);
Husband w3 = new Husband(w2);
w3.bringVeg();
}
}
class Account {
void savings(){
System.out.println(" your savings account opened");
}
void current(){
System.out.println(" your current account opened");
}
}
class BankBazar{
Bank bk;
BankBazar( Bank bk1){
bk=bk1;
}
void service(int x){
bk.openAcc(x);
}
}
class CommandDemo2{
public static void main(String[] msr){
Account acc = new Account();
SBI sb = new SBI(acc);
BankBazar bz = new BankBazar(sb);
bz.service(2);
}
}
Program-1:
interface Mobile{
void model();
void price();
}
class SalesMan{
Mobile mb;
SalesMan(Mobile mb1){
mb=mb1;
void showDetails(){
mb.model();
mb.price();
class DepInj1{
Mobile mb;
mb = new Samsung();
sm.showDetails();
Program:
interface Shape{
void area(int x, int y);
class ShapeMaker{
Shape sh;
ShapeMaker(Shape sh1){
sh = sh1;
}
void ShapeArea(int x, int y){
sh.area(x,y);
class DepInj2{
sm.ShapeArea(5,10);
Program:
import java.util.Scanner;
interface DChain{
DChain chain;
chain = dc;
if (x>1) chain.dispense(x);
}
}
DChain chain;
chain = dc;
if (x>2) chain.dispense(x);
DChain chain;
chain = dc;
class DemoChainExams{
int n;
c1.setNextChain(c2);
c2.setNextChain(c3);
n= in.nextInt();
c1.dispense(n);
import java.util.Scanner;
interface DispenseChain {
DispenseChain chain;
chain=nextChain;
} else chain.dispense(cur);
}
class Rs20Dispenser implements DispenseChain{
DispenseChain chain;
chain=nextChain;
} else chain.dispense(cur);
DispenseChain chain;
class DemoChainATM {
c1.setNextChain(c2);
c2.setNextChain(c3);
while (true) {
int amount = 0;
amount = input.nextInt();
if (amount % 10 != 0) {
return;
c1.dispense(amount);
Simple:
Maintainable:
Testable:
Readable:
1. All the resources must be placed in the respective folders for pro use and
maintenance
2. Proper Naming : all variables, constants, class names, method names,
Enum names must follow the conventions used in the industry
3. Anatomy of java program : as per the industry standards
I am going to illustrate a java program for the above concepts of clean coding,
Program:
// clean code program
// method's long parameter list reduced
// Address data class, collection of variables
class Address{
int house_no;
int road_no;
String city;
// constructor for data class
Address(int h, int r, String c){
house_no = h;
road_no = r;
city = c;
}
}
// main class
class StudentX{
// this method is getting more data from address object
void show(String name, Address ad1){
System.out.println( name );
System.out.println( ad1.house_no );
System.out.println( ad1.road_no );
System.out.println( ad1.city );
}
// driver method
public static void main(String[] args){
Address ad = new Address(100, 22, "vja");
StudentX st1 = new StudentX();
st1.show("Rahul",ad);
}
}
Bloaters: Bloaters are code, methods and classes that have increased to such
gargantuan proportions that they are hard to work with. Usually these smells do not
crop up right away, rather they accumulate over time as the program evolves (and
especially when nobody makes an effort to eradicate them). Long Method, Large
Class, Primitive Obsession, Long Parameter List and Data Clumps are famous in
this category.
Object-Orientation Abusers: All these smells are incomplete or incorrect application
of object-oriented programming principles. Switch Statements, Temporary Field,
Refused Request and Alternative Classes with Different Interface are known as
object-orientation abusers code smells.
Change Preventers: These smells mean that if you need to change something in one
place in your code, you have to make many changes in other places too. Program
development becomes much more complicated and expensive as a result. Code
smells like Divergent Change, Shotgun Surgery and Parallel Inheritance Hierarchies
are in this category.
Couplers: All the smells in this group contribute to excessive coupling between
classes or show what happens if coupling is replaced by excessive delegation. Some
examples would be Feature Envy, Inappropriate Intimacy, Message Chains, Middle
Man and Incomplete Library Class
2. Long Method: A long method contains too many lines of code. Any code
with more than 25 lines of code should make you question. It could be solved
using refactoring techniques like changing expression into sub-expression,
complex codes into a new function in order to make a function or method a
small and easy to read without changing its functionality.
3. Long Parameter List: Any function with more parameters is obviously more
complex. One of the thumb rules is to use a maximum of 3 to 4 parameters in
a function.
4. Large Classes: A class contains many methods/lines of code/fields is
considered a code smell. Refactoring techniques could be done like, extract
class, extract subclass, extract interface, duplicate observed data.
5. Duplicate Code: When a code is repeated for more than two times, merge it
into a function or a method of the class. If the same code is found in two or
more classes, using the extract method we can refactor the code smell.
6. Dead Code: The code that is not being used. A function with no calls or the
condition that never occurs. Delete unused code and unnecessary files.
Program:
// clean code program
// method's long parameter list reduced
// Address data class, collection of variables
class Address{
int house_no;
int road_no;
String city;
// main class
class StudentX{
// driver method
public static void main(String[] args){
Address ad = new Address(100, 22, "vja");
StudentX st1 = new StudentX();
st1.show("Rahul",ad);
}
}
class Parent {
String name;
String ph;
Parent(){
}
void show(){
System.out.println(" name ="+ name);
System.out.println(" phone ="+ ph);
System.out.println(" branch ="+ branch);
System.out.println(" college ="+ clg);
}
}
class DemoLiskov{
public static void main(String[] args){
Parent obj = new Derived("Rahul","99999","CSE","KLEF");
// Liskov substitution goes here...
Derived doj = new Derived("Rani","88888","CSE","KLEF");
doj.show();
doj.display();
}
}
42. Dependency Inversion – program (clean coding)
Program:
class Parent {
Parent(){
}
void show(){
System.out.println("show method parent class");
}
}
class Derived extends Parent{
void show(){
System.out.println("show method child class");
}
void display(){
System.out.println("display method of child class");
}
}
class DemoDepInversion{
public static void main(String[] args){
//Parent obj = new Parent();
Derived obj = new Derived();
obj.show();
obj.display();
}
}
void hello(){
System.out.println(" Hello from one class");
}
}
void borrow(){
System.out.println(" borrow from Two class");
}
}
class InterfaceSegre{
public static void main(String[] args){
Iface1 oo;
oo = new One();
oo.show();
oo = new Two();
oo.show();
}
}
44. Usage of Data class – program ((clean coding)
Program:
class Data {
int x;
int y;
Data (int x1 , int y1){
x = x1;
y = y1;
}
}
class Compute{
Data dt;
Compute(Data dt1){
dt = dt1;
}
int sum(){
return dt.x + dt.y;
}
int subtract(){
return dt.x - dt.y;
}
}
class DataClass1{
public static void main(String[] msr){
Data dd = new Data(20,10);
Compute cp = new Compute(dd);
System.out.println("sum ="+ cp.sum());
System.out.println("difference ="+ cp.subtract());
}
}
45. Refactoring techniques - Example program.
Answer:
• Refactoring encompasses a number of specific code hygiene practices. When
it comes to eliminating code smells, however, there are three particularly
effective techniques: one that focuses on methods, another that focuses on the
method calls and a third that focuses on classes.
-------------------------------------
Program before refactoring:
-------------------------------------
class StudentY{
void show(String name, int house_no, int road_no, String
city){
System.out.println(name);
System.out.println(house_no);
System.out.println(road_no);
System.out.println(city);
}
// main class
class StudentX{
// driver method
public static void main(String[] args){
Address ad = new Address(100, 22, "vja");
StudentX st1 = new StudentX();
st1.show("Rahul",ad);
}
}
PrintHelloMethod(String name) {
this.name = name;
}
// normal method
public void print() {
System.out.println("Hello, " + name);
}
}
class Refactor2{
public static void main(String[] args){
PrintHelloMethod phm = new PrintHelloMethod("world");
phm.printHello();
}
}
// After refactoring
interface MyDelegate {
void doSomething();
}
class MyClass {
MyDelegate delegate;
MyClass() {
this.delegate = new MyDelegate();
}
public void doSomething() {
delegate.doSomething();
}
}
50. Remove MiddleMan - java example ( Refacoring )
Program:
// Normal way...
class Boss1 {
private Worker w1;
Boss1( Worker ww){
w1 = ww;
}
class Worker{
void doSomething(){
System.out.println(" brought 1 kg chillies");
}
}
class Refactor5 {
public static void main(String[] args){
Worker w10 = new Worker();
Boss1 bb1 = new Boss1(w10);
bb1.doSomething();
}
}
// refactored way...
class Boss1 {
public void doSomething() {
System.out.println(" brought 1 kg chillies");
}
}
class Refactor51 {
public static void main(String[] args){
Boss1 bb1 = new Boss1();
bb1.doSomething();
}
}
// After refactoring
abstract class Bird {
private String type;
@Override
public String getSpeed() {
return "average";
}
}
@Override
public String getSpeed() {
return (numberOfCoconuts > 2) ? "tired" : "average";
}
}
class NorwegianBlueParrot extends Bird {
private boolean isNailed;
private int voltage;
@Override
public String getSpeed() {
return (isNailed) ? "0" : "beautiful";
}
}
// Usage example
Bird bird = new EuropeanSwallow();
System.out.println(bird.getSpeed()); // "average"
Generics does not work with primitive types (int, float, char, etc).
Syntax :
public int compareTo(Object obj): It is used to compare the current object with
the specified object. It returns
o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.
4. HashSet – Explanation
Answer:
HashSet is commonly used if we have to access elements randomly. It is because
elements in a hash table are accessed using hash codes. The hashcode of an
element is a unique identity that helps to identify the element in a hash table.
HashSet cannot contain duplicate elements. Hence, each hash set element has a
unique hashcode.
Add(), remove(), size(), addAll(), retainAll(), removeAll(), clear() are the main
Collection framework classes are used to store and manage variety of Objects.
6. Map - Explanation
Answer:
Map interface is implemented by Hashmap, LinkedHashMap and TreeMap
A map contains values on the basis of key, i.e. key and value pair. Each key and
value pair is known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a
key.
put(), remove(), getKey(), getValue(), entrySet() are the major methods of the Map.
Public Boolean hasNext() – returns true if element/s are available otherwise false.
Public void remove() – last element returned by the iterator will be removed
LONG ANSWER QUESTIONS ( from CO-2 )
Java Generics allows us to create a single class, interface, and method that can be
used with different types of data (objects).
Generics does not work with primitive types (int, float, char, etc).
Advantages:
Type Parameters :
The type parameters naming conventions are important to learn generics thoroughly.
The common type parameters are
Program : whether the given number is Zero/Non-zero (Integer and Double types)
class Gen10{
int i;
double d;
String s;
if( (Integer)data1 == 0)
System.out.println("ZERO");
else
System.out.println("non ZERO");
if( (Double)data1 == 0)
System.out.println("ZERO");
else
System.out.println("non ZERO");
g1.<Integer>check(200);
g1.<Integer>check(0);
g1.<Double>check(12.6);
g1.<Double>check(0.0);
}
}
Program: whether the given number is even/odd (Integer and Double types)
T data1;
Gen10(T data1){
this.data1 = data1;
void check(){
int i;
double d;
String s;
if( (Integer)data1 == 0)
System.out.println("ZERO");
else
System.out.println("non ZERO");
if( (Double)data1 == 0)
System.out.println("ZERO");
else
System.out.println("non ZERO");
g1.check();
g2.check();
G3.check();
g4.check();
class Even {
<T> void checkOddEven (T number) {
if (number instanceof Integer) {
if ((Integer)number % 2 == 0)
System.out.println((Integer)number + "
is even number");
else
System.out.println((Integer)number + "
is odd number");
} else
if (number instanceof Double) {
if ((Double)number % 2 == 0)
System.out.println((Double)number + "
is even number");
else
System.out.println((Double)number + "
is odd number");
}
}
}
public class EvenDemo {
public static void main(String[] args) {
Even e = new Even();
e.<Integer>checkOddEven(11);
e.<Double> checkOddEven(13.0);
}
}
class CompDemo{
public static void main(String[] args){
Answer:
Comparable Comparator
2) Comparable affects the original class, Comparator doesn't affect the original
i.e., the actual class is modified. class, i.e., the actual class is not
modified.
6. Clonable Interface
Program:
class Student implements Cloneable {
int id;
String name;
Student(int id, String name){
this.id = id;
this.name = name;
}
@Override
Public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
class ClonableInterface{
public static void main(String[] args) {
Student s = new Student(101, "Rahul");
System.out.println(s.id + " " + s.name);
try {
Student s1 = (Student) s.clone();
System.out.println(s1.id + " " + s1.name);
}catch (Exception e) {
System.out.println(e);
}
}
}
numbers.set(3,”Malaysia” );
System.out.println("size"+ countries.size());
System.out.println(" ");
countries.remove(2);
Iterator itr= countries.iterator();
while(itr.hasNext()) {
System.out.print(itr.next());
System.out.print(" , ");
}
System.out.println("size"+ countries.size());
}
}
import java.util.Stack;
public class Stack1
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
System.out.println("top of the stack ="+ stk.pop());
}
}
class PriorityQueue1 {
public static void main(String[] args) {
// Create a PriorityQueue using the natural
ordering (ascending)
PriorityQueue<Integer> pq = new
PriorityQueue<>();
import java.util.*;
class Set1 {
public static void main(String[] klu){
System.out.println(list);
System.out.println(list);
a.addAll(Arrays.asList(
new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));
b.addAll(Arrays.asList(
new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));
Set<Integer> union = new LinkedHashSet<>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);
Map in Java is an interface available in java. util package and it stores the data in
key and value pairs. It does not allow duplicate keys.
TreeMap, HashMap and LinkedHashMap are the classes that are implementing
Map interface.
The map() operation in Java 8 streams transforms the elements of a collection based
on a specified function. It takes a Function<T, R> as input, where T is the type of
the input element and R is the type of the output element.
Changing Element:
hm1.put(new Integer(2), "For");
Removing Elements:
hm1.remove(new Integer(4));
// removing an element
mp.remove("four");
// load elements
mp.put(5,"India");
mp.put(2,"Srilanka");
mp.put(3,"USA");
mp.put(4,"Russia");
mp.put(1,"China");
System.out.println(" No of element in the map (before) :"+mp.size());
// removing an element
mp.remove(4);
interface Eatable{
void eat();
}
class FuncInterface1 {
public static void main(String[] args){
Eatable eb = new Eatable(){
public void eat(){
System.out.println(" eating .. fruits");
System.out.println(" eating .. sweets");
}
};
eb.eat();
}
}
class Lamba2 {
public static void main(String[] args){
Eatable eb =(String a, String b)->{
System.out.println(" eating .. "+a);
System.out.println(" eating .. "+b);
};
eb.eat("fruits","sweets");
}
}
20. Nested classes
a) Inner class : The purpose of nested classes is to group classes that belong
together, which makes your code more readable and maintainable.
class Outer
{
int outer_x=100;
void test()
{
Inner inner = new Inner();
inner.display();
inner.showy();
}
class Inner
{
int y=10;
void display()
{
System.out.println("dispaly: outer_x =" + outer_x);
}
void showy()
{
System.out.println(y);
}
}
}
class InnerClass
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
b) Local class : A class i.e., created inside a method, is called local inner class in java. Local
Inner Classes are the inner classes that are defined inside a block. Generally, this block is a
method body.
Program 1:
class JLInner1{
private int data=30;
void display(){
class Local{
void msg(){
System.out.println(data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
JLInner1 obj=new JLInner1();
obj.display();
}
}
Program 2:
class JLInner2{
private int data=30;//instance variable
void display(){
int value=50;
class Local{
void msg(){
System.out.println("local variable: "+value);
System.out.println("instance variable: "+data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
JLInner2 obj=new JLInner2();
obj.display();
}
}
c) Anonymous class : a class that has no name is known as an anonymous inner class in Java.
It should be used if you have to override a method of class or interface.
Program 1:
abstract class Person{
abstract void eat();
}
class JAInner1{
public static void main(String args[]){
Person p=new Person(){
void eat(){
System.out.println("nice fruits");
}
};
p.eat();
}
}
Program 2:
interface Eatable{
void eat();
}
class JAInner2{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){
System.out.println("nice fruits");
}
};
e.eat();
}
}