0% found this document useful (0 votes)
253 views

CS8392 Unit II Notes

This document discusses inheritance and interfaces in object-oriented programming. It defines inheritance as deriving a new subclass from an existing superclass to reuse methods and fields. The key types of inheritance discussed are single, multilevel, hierarchical, and multiple inheritance. Multiple inheritance through classes is not supported in Java due to complexity, but multiple inheritance through interfaces is supported.

Uploaded by

Keerthi Varman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
253 views

CS8392 Unit II Notes

This document discusses inheritance and interfaces in object-oriented programming. It defines inheritance as deriving a new subclass from an existing superclass to reuse methods and fields. The key types of inheritance discussed are single, multilevel, hierarchical, and multiple inheritance. Multiple inheritance through classes is not supported in Java due to complexity, but multiple inheritance through interfaces is supported.

Uploaded by

Keerthi Varman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

OBJECT ORIENTED PROGRAMMING

Subject Code: CS8391

Unit II
INHERITANCE AND INTERFACES

Inheritance – Definition:

Derive a new class (subclass) from an existing class (base class or


superclass) is called as Inheritance. Inheritance concept is mainly used
for code reusability.
The idea behind inheritance in java is that new classes are created
from the existing classes. When new classes are created, you can reuse
methods and fields of parent class, and you can add new methods and
fields also. Inheritance represents the IS-A relationship, also known as
parent-child relationship.

The parent class or base class is called as super class.


 Super Class: The class whose features are inherited is known as
super class (or a base class or a parent class).

 Sub Class: The class that inherits the other class is known as sub
class (or a derived class, extended class, or child class).
o Derived class = Parent class fields + new fields.

 Keywords used:
o extends - In case of Java class and abstract class
o implements – In case of Java interface.

Syntax:

𝑐𝑙𝑎𝑠𝑠 𝑆𝑢𝑝𝑒𝑟𝑐𝑙𝑎𝑠𝑠 { ..... ..... }


𝑐𝑙𝑎𝑠𝑠 𝑆𝑢𝑏𝑐𝑙𝑎𝑠𝑠 𝒆𝒙𝒕𝒆𝒏𝒅𝒔 𝑆𝑢𝑝𝑒𝑟𝑐𝑙𝑎𝑠𝑠
{ ..... ..... }

The extends keyword indicates that you are making a new class
that derives from an existing class.
Example of inheritance:

Animal Animal class Animal

Field: Legs {
int legs;
...
}

Dog
Dog class Dog extends Animal
Field: Tail {
Super class : Animal
Sub class : Dog int tail;
Super class (Animal) has
...
datamember named legs
and subclass (Dog) has }
field named tail.
Filename : Dog.java
class Animal Output:
Dog has 4 legs
{ Dog has 1 tail
int legs = 4;
}

public class Dog extends Animal Super class data member is


accessed in the sub class
{
int tail = 1;
public static void main(String args[])
{
Dog d = new Dog();
System.out.println("Dog has "+ d.legs + " legs");
System.out.println("Dog has " + d.tail + " tail");
}}

Access specifier is Access specifier is Access specifier is


private: public: protected:

class Animal class Animal class Animal


{ { {
private int legs = 4; public int legs = 4; protected int legs = 4;
} } }

Output: Output: Output:


Compile error: legs has Dog has 4 legs Dog has 4 legs
private access in Animal Dog has 1 tail Dog has 1 tail
When a class is extended, sub-class inherits all the public, protected and
default properties of the super class. Private fields and methods of the super
class are NOT INHERITED by the sub-class.
Types of Inheritance:

Types of Inheritance

Based on Based on
Java class interface

Single Multilevel Hierarchical Multiple Hybrid


inheritance inheritance inheritance inheritance inheritance

Single Inheritance:
When a subclass is derived from a single super class, is called as Single
Inheritance.

Super class : person


Data members : name;
Member function : detail()

Subclass : student
Member function : display()
Filename : student.java

class person
{
String name = "Gayathri";
void detail() Super class
{
System.out.println("Am studying Java");
}
}

public class student extends


person {
void display()
{
System.out.println("My name is :" + name);
} Sub class

public static void main(String args[])


{ Output:
student p = new student(); My name is :Gayathri
p.display(); Am studying Java
p.detail();
}}

Multilevel Inheritance:
When a class extends a class, which in turn extends another class then it’s
called as multilevel inheritance. For example class C extends class B and class B
extends class A then this type of inheritance is known as multilevel inheritance.

Super class : People


Data members : name;
Member function : detail()

Subclass : Employee
Data members : eno;

Subclass : Leader
Data members : teamsize;

People is the superclass


Employee is the subclass of People
Employee is the superclass of Leader
Leader is the subclass of Employee
Filename : Test.java

class People
{ String name = "Gayathri";
void detail()
{
System.out.println("Method in Superclass");
}}

class Employee extends People


{int eno = 1901; }

class Leader extends Employee Output:


Employee name : Gayathri
{ int teamsize = 15; }
Employee no : 1901
Team size : 15
public class Test Method in Superclass
{
public static void main(String args[])
{
Leader x = new Leader();
System.out.println("Employee name : "+ x.name);
System.out.println("Employee no : "+ x.eno);
System.out.println("Team size : "+ x.teamsize);
x.detail();
}}

Hierarchical Inheritance
When multiple classes inherit from a single superclass, then this type of
inheritance is called as Hierarchical Inheritance. Here, there is one super class
and multiple sub classes.

Engineer

CSE EEE Civil

Engineer is the superclass


CSE, EEE, Civil are the subclasses of
Here Class A acts as the parent superclass, Engineer
for sub classes Class B, Class C
and Class D
Filename : Civil.java

class Engineer
Output:
{ String college = "IIT"; } EEE student is studying in : IIT
CSE student is studying in : IIT
Civil student is studying in : IIT
class EEE extends Engineer { }
class CSE extends Engineer { }

public class Civil extends Engineer {


public static void main(String args[]) {
EEE e = new EEE();
CSE c = new CSE();
Civil ci = new Civil();
System.out.println("EEE student is studying in : "+ e.college);
System.out.println("CSE student is studying in : "+ c.college);
System.out.println("Civil student is studying in : "+ ci.college);
}}

Multiple inheritance is not supported in java:


In java programming, multiple and hybrid inheritance is not supported through
classes but supported through interface only. To reduce the complexity and simplify the
language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object,
there will be ambiguity to call method of A or B class.

Class A Class B
msg() msg()

Class C
Class C object, doesn’t know which msg() method to be invoked.
Filename : C.java

class A
{
void msg()
{
System.out.println("Hello");
}}

class B
{ void msg()
{
System.out.println("Welcome");
}}

public class C extends A,B //suppose if it were


{
public static void main(String args[])
{
C obj=new C();
obj.msg(); //which msg() would be invoked?
}}

Purpose of Inheritance
 It promotes the code reusability i.e the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
 It promotes polymorphism by allowing method overriding.
Constructors in Java Inheritance:
In Java, super class default constructor is invoked automatically in sub class.
Object is created for the sub class. With the sub class object, super class constructors
are invoked.
Constructors in Multilevel Inheritance

Filename : Test.java
Class A is the Super class. Class B is inherited from Class A
class A class B extends A
{ {
A() B()
{ {
System.out.println("Class A "); System.out.println("Class B ");
} }
} }
Class C is inherited from Class B. Class D is inherited from Class C.
class C extends B class D extends C
{ {
C() D()
{ {
System.out.println("Class C "); System.out.println("Class D ");
}
}
}
}
public class Test
Output:
{
Class A
public static void main(String[] args) Class B
{ Class C
D d = new D(); Class D

}
Super Keyword in Java
The super keyword in java is a reference variable that is used to refer parent class
objects. The keyword “super” came into the picture with the concept of Inheritance. It is
majorly used in the following contexts:
 Use of super with variables

 Use of super with methods

 Use of super with constructors

Use of super with variables


When both the super class and sub class has same data members, there is a
possibility of ambiguity for the JVM. This is overcome by the keyword “super”.
Filename : Test.java
Super class: A
Data members : number;

Sub class: B
class A Data members : number;
{ Member function : display()

int number = 200;


}
Super class number = 200
is printed
class B extends A
{
int number = 500;
Sub class number = 500
void display() is printed

{
System.out.println(number);
System.out.println(super.number);
}
}

public class Test


{
public static void main(String args[]) Output:
{ 500
200
B b =new B();
b.display();
} }
Use of super with methods
Whenever a parent and child class have methods with the same name, the ambiguity is
resolved using the super keyword.

Filename : Test.java
Super class: A
Member function : display()
class A
{
void display() Sub class: B
Member function : display()
{
System.out.println("This is Super class");
}

} Inside the Sub class method display() ,


the super class method display()is
called
class B extends A
{
void display()
{
System.out.println("This is sub class");
super.display();
} Sub class method
} display() is invoked

public class Test


{
public static void main(String args[])
{
B b =new B();
b.display();
Output:
} } This is sub class
This is Super class
Use of super with constructors:
Super keyword can also be used to access the parent class constructor. One more
important thing is that, ‘’super’ can call both parametric as well as non-parametric
constructors depending upon the situation. Call to super() must be first statement in
Derived(Student) Class constructor.

Filename : Test.java
Super class: A
Data members : num;
class A
Constructor : A()
{
int num;
Sub class: B
A() Constructor : B()
{
System.out.println("A is created");
}}

class B extends A
{ Super class default
constructor is invoked first
B()
{
System.out.println("B is created");
}}

public class Test


{
public static void main(String args[])
{ Output:
A is created
B b = new B(); B is created
} }
Filename : Test.java
Super class: A
Data members : num;
class A Constructor : A()
{

int num; Sub class: B


A() Constructor : B()
B(num)
{
System.out.println("A is created");
} }

class B extends A Super class default constructor


is invoked first. Then one
{
argument constructor in the sub
B() class is invoked.
{
System.out.println("B is created");
}
B(int num)
{
System.out.println("Number inside sub class");
}
}
Output:
A is created
Number inside sub class
public class Test
{
public static void main(String args[])
{
B b = new B(10);
} }
Filename : Test.java
class A
{ Super class: A
Data members : num;
int num; Constructor : A()
A() A(num)

{ System.out.println("A is created");
} Sub class: B
Constructor : B()
A(int num) B(num)
{
System.out.println("Number inside super class");
}}
Though one argument constructor
in the super class is available, only
class B extends A super class default constructor is
{ invoked.
B()
{ System.out.println("B is created"); }

B(int num)
{
System.out.println("Number inside sub lass");
}}

public class Test


{
public static void main(String args[])
Output:
{ A is created
Number inside sub class
B b = new B(10);
} }
Filename : Test.java
class A
{ Super class: A
Data members : num;
int num; Constructor : A()
A(num)
A()
{
System.out.println("A is created"); Sub class: B
Constructor : B()
} B(num)
A(int num)
{
System.out.println("Number inside super class");
}
}

class B extends A
{
B()
{
System.out.println("B is created");
}
B(int num) One argument constructor in
the super class is invoked.
{

super(num);
System.out.println("Number inside sub class");
}}

public class Test


{ Output:
public static void main(String args[]) Number inside super class
Number inside sub class
{
B b = new B(10);

} }
Polymorphism in Java
Polymorphism is derived from two Greek words: poly and morphs. The word
“poly” means many and “morphs” means forms. The ability to take more than one forms
is called as polymorphism.

Method overloading in Java:


When the compiler is able to select the appropriate function at the compile time
itself, then it’s called as compile time polymorphism. Method overloading or function
overloading is compile time polymorphism. It’s called as early binding or static binding or
static linking.
Same function name with different number of parameters or different order of
parameters or different types of parameters, it’s called as method overloading.
 Overloading methods differ in number of parameters
o int add(int);

o int add(int,int);

 Overloading methods differ in types of
parameters o int add(float,float);

o int add(int,int);

 Overloading methods differ in order of parameters
o int add(float,int);
o int add(int,float);
Filename : Addition.java
public class Addition
Same function name sum with
{ different number of arguments
void sum(int n1, int n2) is presented in the same class.

{
System.out.println("Addition : "+ (n1+n2));
}

void sum(int n1, int n2, int n3)


{
System.out.println("Addition : "+ (n1+n2+n3));
} Output:
Addition : 30
public static void main(String args[]) Addition : 18
{
Addition a = new Addition();
a.sum(10,20); Calls the method with 2 parameters.
a.sum(3,6,9); Calls the method with 3 parameters.

} }

Method overriding in Java


If both the super class (parent class) and the subclass (child class) have the same
method name, it is known as method overriding in java.

Super class: Animal


Member function: move()
Same function
extends name, move() in
both the super class
Sub class: Dog
and sub class.
Member function: move()

When a method in a subclass has the same name, as a method in its super-class,
then it is said to override the method in the super-class.
Filename : Test.java
class Animal
{
void move()
{ System.out.println("Super class move"); }
} Output:
Super class move
sub class move
sub class move
class Dog extends Animal
{
void move()
{ System.out.println("sub class move"); }
}

public class Test


{
public static void main(String[] args)
{
Animal ani = new Animal();
ani.move(); Super class refers to super class object

Dog dd = new Dog();


Sub class refers to sub class object
dd.move();

Animal doggy = new Dog();


Super class refers to sub class object
doggy.move();
}

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. There are two ways to achieve abstraction in java
 Abstract class (0 to 100%)

 Interface (100%)
Abstract class in Java
A class that is declared with abstract keyword is known as abstract class in java.
It can have abstract and non-abstract methods (method with body). An abstract class is
never instantiated.
𝑎𝑏𝑠𝑡𝑟𝑎𝑐𝑡 𝑐𝑙𝑎𝑠𝑠 𝑐𝑙𝑎𝑠𝑠𝑛𝑎𝑚𝑒
{ 𝑀𝑒𝑚𝑏𝑒𝑟𝑠;
𝑐𝑜𝑛𝑐𝑟𝑒𝑡𝑒 𝑚𝑒𝑡ℎ𝑜𝑑𝑠;
𝐴𝑏𝑠𝑡𝑟𝑎𝑐𝑡 𝑚𝑒𝑡ℎ𝑜𝑑𝑠
Syntax :}
{ ;

ℎ ;

ℎ }

Example : abstract class A { }


Concrete Class Abstract Class
A concrete class is one which is
containing fully defined methods or
A partial implemented class is called an
implemented methods. Fully
abstract class.
implemented class is known as
concrete or normal class.

Super class: Test Super class: Test


Member function: msg() Member function: msg()

Sub class: Normal Sub class: Normal

In concrete class, member functions In abstract class, it can have abstract


are fully defined. methods or concrete methods.
Filename : Normal.java Filename : Normal.java

class Test abstract class Test


{ {
void msg() abstract void msg();
{ }
System.out.println("Hello CSE");
} public class Normal extends Test
} {
void msg()
public class Normal extends Test {
{ System.out.println("Hello CSE");
public static void main(String args[]) }
{ public static void main(String args[])
Normal n= new Normal(); {
n.msg(); Normal n= new Normal();
} n.msg();
} }}

Rules for abstract class:


 An abstract class is a class that is declared abstract

 Abstract classes cannot be instantiated

 Abstract classes can be sub-class
 It may or may not include abstract methods

 If subclass doesn’t provide implementations then the subclass must also be
declared abstract.

Abstract method in Java


 Method that is declared without any body(implementation) within an abstract
class are called abstract method.

 The implementation of the method will be defined by its subclass. Abstract
method can never be final and static.
Syntax : 𝑎𝑏𝑠𝑡𝑟𝑎𝑐𝑡 𝑅𝑒𝑡𝑢𝑟𝑛𝑇𝑦𝑝𝑒 𝑚𝑒𝑡ℎ𝑜𝑑𝑁𝑎𝑚𝑒(𝐿𝑖𝑠𝑡 𝑜𝑓 𝑓𝑜𝑟𝑚𝑎𝑙 𝑝𝑎𝑟𝑎𝑚𝑒𝑡𝑒𝑟);
Example : abstract void display(); (or) abstract int sum(int a, int b);
Concrete Method Abstract Method
Concrete class is one which is Method that is declared without any body
containing fully defined methods or (implementation) within an abstract
implemented method class is called abstract method.

abstract keyword says

this is abstract class


abstract class Test
{

abstract void msg(); Abstract method

void display()
{
System.out.println("Hello CSE"); Concrete method
}

}
Abstract class are never instantiated which means we can't create an object to
Abstract class.
abstract class Test
{
void display()
{ System.out.println("Java Programming"); }
}
public class Normal extends Test
{
public static void main(String args[])
{ Compile time error
Test n= new Test(); Object for the abstract
class cannot be created

Test n= new Normal(); Its OK.


}}
Simple example to explain abstract class and abstract method in Java:

Filename : Test.java
abstract class Test Super class is the abstract class
{
Member function is declared, but NOT
abstract void msg();
DEFINED. This is Abstract method

void display()
Member function is
{ System.out.println("Java Programming");
defined. This is Concrete
} method.
}

public class Normal extends Test


{
void msg()
{ Abstract method is defined
in the sub class
System.out.println("Hello CSE");
}
public static void main(String args[])
{
Normal n= new Normal();
n.display();
Output:
n.msg(); Java Programming
Hello CSE
}

Points to remember for abstract classes:


 Abstract class and interfaces are different concepts.

 Abstract method should be inside the abstract classes.

 Abstract class may or may not have abstract methods. Even a single abstract
method is present, and then the class must be declared abstract.
 Abstract class can have Constructors, Member variables and normal methods.

 Abstract class are never instantiated which means we can't create an object to
Abstract class.

 Abstract class can be extended.

 An abstract method must be overridden in a subclass.
Advantage of Abstract Class
 Abstract classes can group several related classes together as siblings. Grouping
classes together is important in keeping a program organized and understandable.

 Abstract class is a way to organize inheritance

Disadvantage of Abstract Class


 Abstract classes cannot be instantiated

Final keyword in java


Final is a non-access modifier applicable only to a variable, a method or a class.

Final variable Values cannot be changed

Final methods Prevent method overriding

Final classes Prevent Inheritance

Final variable
Final variables are nothing but constants. The value of a final variable cannot be
changed once it is initialized.

public class race


{ speed is a final variable of integer
final int speed = 200 ; datatype, which is initialized with the
value 200
void run()
{
speed = 700; Compile time error
speed = 200 is changed to speed = 700
}

public static void main(String args[])


{
race r = new race();
r.run();
}
}

If final variables are not initialized with their values, it can be initialized only in the
constructors. It cannot be initialized with the member functions.
Final variables cannot be initialized inside methods.
public class race
{
final int speed ;

void run()
{ Compile time error
speed = 700; cannot assign a value to final variable speed

System.out.println("My speed is "+ speed);


}

public static void main(String args[])


{
race r = new race();
r.run();
}
}

Final variables can be initialized inside constructors


public class race
{
final int speed;

race()
{ Inside the constructor,
speed = 1000; final variables CAN
System.out.println("My speed is "+ speed); BE initialized
}

public static void main(String args[])


{ Output:
race r = new race(); My speed is 1000
} }

Final Methods
Final method cannot be overridden. Parent class final method can be used, but it
can’t be overridden in subclass.
Base class Derived class Description
class race public class Test extends race
{ { Super class has method,
void run() void run() run() and the sub class
{ { …. } also has the method,
… run().
} public static void main(String args[])
} { Super class, run() will
race r = new race(); be invoked
r.run();
} }
Base class Derived class Description
class race public class Test extends race
{ { Super class has method,
final void run() void run() run() and the sub class
{ { …. } also has the same
… method, run().
} public static void main(String args[])
} { Here, final methods
race r = new race(); CANNOT be overridden
r.run();
} } Note:
Final methods can be
inherited, but cannot be
overridden.

Final class

Final class cannot be extended


final class race
{ } Compile time error
cannot inherit from final race

public class Test extends race


{ public static void main(String args[])
{ }
}

INTERFACES

 Interface is a pure abstract class. They are syntactically similar to classes, but
objects cannot be created. Interface is used to achieve complete abstraction in
Java. It has the collection of
o Abstract methods

o Static and final constants.

 Java uses interface to implement multiple inheritance.

 Interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
 Interface does not contain any constructors.

 Interface is not extended by a class; it is implemented by a class and it can
extend multiple interfaces.

Syntax for declaring Interfaces


// ,
// ℎ

𝒊𝒏𝒕𝒆𝒓𝒇𝒂𝒄𝒆 𝑖𝑛𝑡𝑒𝑟𝑓𝑎𝑐𝑒𝑛𝑎𝑚𝑒
{
// 𝐴𝑛𝑦 𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑓𝑖𝑛𝑎𝑙,𝑠𝑡𝑎𝑡𝑖𝑐 𝑓𝑖𝑒𝑙𝑑𝑠
// 𝐴𝑛𝑦 𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑎𝑏𝑠𝑡𝑟𝑎𝑐𝑡 𝑚𝑒𝑡ℎ𝑜𝑑 𝑑𝑒𝑐𝑙𝑎𝑟𝑎𝑡𝑖𝑜𝑛𝑠
}
𝑃𝑢𝑏𝑙𝑖𝑐 𝑐𝑙𝑎𝑠𝑠 𝑐𝑙𝑎𝑠𝑠𝑛𝑎𝑚𝑒 𝑖𝑚𝑝𝑙𝑒𝑚𝑒𝑛𝑡𝑠 𝑖𝑛𝑡𝑒𝑟𝑓𝑎𝑐𝑒𝑛𝑎𝑚𝑒
{ }
Simple example to explain abstract class and abstract method in Java:

Filename : Test.java

interface myname myname is the name of the interface.


{
Variables are NOT instance variables. They are
int n = 500; either final or static. No need of keywords.

void print(); Methods in the interface are implicitly abstract.


} No need to specify abstract keyword.

public class Test implements myname


{
public void print() Methods in an
{ System.out.println("Java Interface" + n); } interface are public

public static void main(String args[])


{ Test t = new Test();
t.print();
}
}

Implementing interface using Real world example:


Let’s consider the example of bank like SBI, HDFC, ICICI etc. The entire banks
have the common functionalities. Make an interface and put all these common
functionalities inside. Each bank implements all these functionalities in their class.
Filename : Test.java

interface Bank
{
Bank Interface int
double ROI = 14.5;
period = 4;
}

class SBI implements Bank


{
SBI()
{
System.out.println("SBI ROI "+ ROI + " with " + period +"yrs");
}
}

class HDFC implements Bank


{
HDFC()
{
System.out.println("HDFC ROI "+ ROI + " with " + period +"yrs");
}
}

public class Test


{
public static void main(String[] args) Output:
{ SBI ROI 14.5 with 4yrs
Bank b = new SBI(); HDFC ROI 14.5 with 4yrs
Bank h = new HDFC();
}
}

Interfaces support Multiple Inheritance

Multiple inheritance is not supported in java because of ambiguity. With interface,


multiple inheritance is possible.
Syntax:

Interface 1 Interface 2 Class child Test class

ℎ ,

{ { { {

… … … ℎ = ℎ ();

} } } }

Simple example:

Interface : Father Interface : Mother


dad_amount = 500000 mom_amount = 500000

class child implements Father, Mother


total_amount = dad_amount + mom_amount;

Filename : Test.java

interface Father
{
int dad_amount = 500000; First interface - Father
}

interface Mother
{ Second interface - Mother
int mom_amount = 300000;
}

class child implements Father, Mother


{
class child which
int total_amount;
child() implements both
{ total_amount = dad_amount + mom_amount; father and mother
}
}

public class Test


{
public static void main(String[] args)
{
child c = new child(); object for child class is created

System.out.println("Child's amount :" + c.total_amount);


}
}
Output:
Child's amount :800000
Name conflict:
Variable names conflicts can be resolved by interface name. Same variable name can be used
in different interfaces. They can be accessed with the dot operator. Syntax: .

Filename : Test.java

interface Father
{
int amount = 500000;
} Same variable name in both
interfaces, Father and Mother
interface Mother
{
int amount = 300000;
}

class child implements Father, Mother


{
int total_amount;
child()
Name conflict
{ total_amount = Father.amount + Mother.amount;
is avoided
}
}

public class Test


{
public static void main(String[] args)
{
child c = new child();

System.out.println("Child's amount :" + c.total_amount);


}
}
Key Differences between Class and Interface in Java

Description CLASS INTERFACE


A class is instantiated to create An interface cannot create
Basic
objects. objects.
Keyword class interface

Syntax
{

ℎ ;

Access Data members in the class can Data members in the interface
specifier be private, public or protected. are always public.
Members of the interface are
Members of the class need to
Members always constants. Either static
be always constants.
or final.
Methods inside the class are Methods in the interface are
Methods defined to perform a specific purely abstract. They are not
action. defined.

Supports only multilevel and Supports all types of


Inheritance hierarchical inheritances but inheritance – multilevel,
not multiple inheritances. hierarchical and multiple

A class can implement any An interface can extend


Implement/
number of interfaces and can multiple interfaces but cannot
Extend
extend only one class. implement any interface.

An interface can never have a


A class can have constructors
Constructor constructor as there is hardly
to initialize the variables.
any variable to initialize.

Representati
on
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be instantiated.

Description Abstract class Interface

Keyword abstract interface

Representation

Syntax
;

ℎ ;

ℎ ;

Access Members may be public, Members of a Java interface are


Specifier private, protected. public by default.
Both abstract and non-abstract Interface can have only abstract
Methods
methods. methods.
Abstract class doesn't support Interface supports multiple
Inheritance
multiple inheritances. inheritances.
Abstract class can have final,
Interface has only static and
Members non-final, static and non-static
final members.
members.
Interface can't provide the
Abstract class can provide the
implements implementation of abstract
implementation of interface.
class.
An abstract class can extend
another Java class and An interface can extend another
extends
implement multiple Java Java interface only.
interfaces.
abstract class Shape interface one
{ {
Example
abstract void draw(); void draw();
} }
Extending Interfaces
An interface can extend another interface in the same way that a class can
extend another class. The keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface. Java class can extend only one parent
class. Interfaces are not classes, and an interface can extend more than one interface.
Syntax: 1, 2, …
{ }

Example program for extending interface:

Filename : Test.java

interface i1 Parent interface i1.


{ Method f1() is only declared in the
public void f1(); interface and it’s NOT defined.
}

interface i2 extends i1
Since interface i1 extends i1, both i1 methods
{
and i2 methods are accessible via i2
public void f2();
}

class cla implements i2 Class cla implements interface i2.


{ It means, class cla implements
both i1 and i2
public void f1()
{
Method f1() definition of
System.out.println("Interface1");
interface i1
}

public void f2()


{ Method f2() definition of
System.out.println("Interface2"); interface i2
}

void f3()
{
Method f3() definition of class cla
System.out.println("Class");
}
}

public class Test


{ public static void main(String[] args)
{
i2 obj = new cla(); Reference variable of interface i2

obj.f1();
obj.f2();
Output:
Interface1
cla c = new cla();
Interface2
c.f3();
Class
}
Object Cloning in Java
Already in Java copy constructor, we have seen the ways to copy the values of
one object into another in java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class

Clone() method in Java


clone() is a method in the Java programming language for object
duplication. Object cloning refers to creation of exact copy of an object. It creates a new
instance of the current object and initializes all its fields with exactly the same contents
of the corresponding fields. By default, java cloning is ‘field by field copy.
The 𝑗𝑎𝑣𝑎.𝑙𝑎𝑛𝑔.𝐶𝑙𝑜𝑛𝑒𝑎𝑏𝑙𝑒 interface must be implemented by the class whose object clone we want to
create. If we don't implement Cloneable interface, clone() method generates
𝐶𝑙𝑜𝑛𝑒𝑁𝑜𝑡𝑆𝑢𝑝𝑝𝑜𝑟𝑡𝑒𝑑𝐸𝑥𝑐𝑒𝑝𝑡𝑖𝑜𝑛.

Syntax of the clone() method:


𝑝𝑟𝑜𝑡𝑒𝑐𝑡𝑒𝑑 𝑂𝑏𝑗𝑒𝑐𝑡 𝑐𝑙𝑜𝑛𝑒() 𝑡ℎ𝑟𝑜𝑤𝑠 𝐶𝑙𝑜𝑛𝑒𝑁𝑜𝑡𝑆𝑢𝑝𝑝𝑜𝑟𝑡𝑒𝑑𝐸𝑥𝑐𝑒𝑝𝑡𝑖𝑜𝑛

Types of cloning:
Java supports two type of cloning.

 Deep cloning

 Shallow cloning.

By default shallow clone is used in Java. Object class has a method clone() which does
shallow cloning.

Shallow copy is method of copying an object and is followed by default in cloning. In this
method the fields of an old object X are copied to the new object Y. While copying,
object Y will point to same location as pointed out by X.

Fig. Original Java object obj


Fig. Shallow copy object obj1

If the field value is a primitive data type it copies the value of the primitive type.
Therefore, any changes made in referenced objects in object X or Y will be reflected in
other object.

Deep copy is to create a copy of object X and place it in a new object Y. New copies of
referenced objects fields are created and these references are placed in object Y. This
means any changes made in referenced object fields in object X or Y will be reflected
only in that object and not in the other. A deep copy copies all fields, and makes copies
of dynamically allocated memory pointed to by the fields.

Fig. Original Java object obj

Fig. Deep copy object obj1


Filename : Student.java

public class Student implements Cloneable


{
int rollno;
Output:
s1 object rollno: 1901
Student(int r)
s2 object rollno: 1901
{ s1 object rollno after updation: 1401
rollno = r; s2 object rollno after updation: 1401
}

public Object clone()throws CloneNotSupportedException


{
return super.clone();
}

public static void main(String args[])


{
try
{
Student s1 = new Student(1901); Student s2 =
(Student)s1.clone(); System.out.println("s1 object
rollno: " + s1.rollno); System.out.println("s2 object
rollno: " + s1.rollno);

s1.rollno = 1401;
System.out.println("s1 object rollno after updation: " + s1.rollno);
System.out.println("s2 object rollno after updation: " + s1.rollno);
}

catch(CloneNotSupportedException c){}
}
}

34 | U n i t I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
35 | U n i t I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Advantages of clone method:
 If we use assignment operator to assign an object reference to another reference
variable then it will point to same address location of the old object and no new
copy of the object will be created. Due to this any changes in reference variable
will be reflected in original object.

 If we use copy constructor, then we have to copy all of the data over explicitly i.e.
we have to reassign all the fields of the class in constructor explicitly. But in clone
method this work of creating a new copy is done by the method itself. So extra
processing is avoided in object cloning.

Java Inner Classes:


Writing a class within another class is allowed in Java. The class written
within is called the nested class, and the class that holds the inner class is called the
outer class.

Syntax for Nested class:

𝒄𝒍𝒂𝒔𝒔 𝑶𝒖𝒕𝒆𝒓
{
//𝑐𝑙𝑎𝑠𝑠 𝑂𝑢𝑡𝑒𝑟 𝑚𝑒𝑚𝑏𝑒𝑟𝑠
𝒄𝒍𝒂𝒔𝒔 𝑰𝒏𝒏𝒆𝒓
{
//𝑐𝑙𝑎𝑠𝑠 𝐼𝑛𝑛𝑒𝑟 𝑚𝑒𝑚𝑏𝑒𝑟𝑠
}
}
//𝑐𝑙𝑜𝑠𝑖𝑛𝑔 𝑜𝑓 𝑐𝑙𝑎𝑠𝑠 𝑂𝑢𝑡𝑒𝑟

There are two types of nested classes: non-static and static nested classes. The non-
static nested classes are also known as inner classes.

36 | U n i t I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Type Description

Inner Class A class created within another class.

A class created for implementing interface or


Anonymous Inner
extending class. Its name is decided by the java
Class
compiler.

Local Inner Class A class created within method.


Static Nested Class A static class created within class.

Inner class:
A Nested inner class can access any private instance variable in java which
can be of any outer class. We can also define the access of this Java inner class, i.e.
private, public or protected.
Syntax:
=

𝑂𝑢𝑡𝑒𝑟𝐶𝑙𝑎𝑠𝑠 𝑜𝑢𝑡𝑒𝑟𝑂𝑏𝑗𝑒𝑐𝑡 = 𝑛𝑒𝑤 𝑂𝑢𝑡𝑒𝑟𝐶𝑙𝑎𝑠𝑠();


𝑂𝑢𝑡𝑒𝑟𝐶𝑙𝑎𝑠𝑠.𝐼𝑛𝑛𝑒𝑟𝐶𝑙𝑎𝑠𝑠 𝑖𝑛𝑛𝑒𝑟𝑂𝑏𝑗𝑒𝑐𝑡 = 𝑜𝑢𝑡𝑒𝑟𝑂𝑏𝑗𝑒𝑐𝑡.𝑛𝑒𝑤 𝐼𝑛𝑛𝑒𝑟𝐶𝑙𝑎𝑠𝑠();

In this example, we are creating msg() method in member inner class that is
accessing the private data member of outer class.
Filename : Outer.java

Output:
public class Outer Data is 100

{
private int data = 100;
public class Inner
Inner Class
{
void msg(){System.out.println("Data is "+data);}
}
public static void main(String args[])
{
Outer obj = new Outer();
Inner Class
Outer.Inner in = obj.new Inner(); object is
in.msg(); created

}
}

Note:
Outer.Inner in = new Outer().new Inner(); can also be used.

37 | U n i t I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Method Local Inner class
A Method local inner class is a Java inner
class defined within a method of
an outer class in java. In Java, we can write a class
within a method and this will be a
local type. Like local variables, the scope of the inner
class is restricted within the
method.
Syntax:
𝑐𝑙𝑎𝑠𝑠 𝑜𝑢𝑡𝑒𝑟
{
𝑣𝑜𝑖𝑑 𝑚𝑒𝑡ℎ𝑜𝑑()
{ ……..
𝑐𝑙𝑎𝑠𝑠 𝑖𝑛𝑛𝑒𝑟
{}
}
}

Filename : Student.java

class Outer
{
int count;
public void display() Method display()
{
for(int i=0;i<5;i++)
{
class Inner
{
Inside method
public void show() there is a class ,
{ Inner
System.out.println("Inside inner "+(count++));
}
}
Inner in=new Inner();
in.show();
}
}
}

public class Test


{
public static void main(String[] args) Output:
{ Inside inner 0
Inside inner 1
Outer obj = new Outer(); Inside inner 2
obj.display(); Inside inner 3
} Inside inner 4
}
38 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Anonymous Inner Class
A local inner class without name is known as anonymous inner class. An
anonymous class is defined and instantiated in a single statement. Anonymous inner
class always extend a class or implement an interface. Since an anonymous class has no
name, it is not possible to define a constructor for an anonymous class. Syntax:

𝐴𝑛𝑜𝑛𝑦𝑚𝑜𝑢𝑠 𝑜𝑏𝑗 = 𝑛𝑒𝑤 𝐴𝑛𝑜𝑛𝑦𝑚𝑜𝑢𝑠 ()


{
𝑝𝑢𝑏𝑙𝑖𝑐 𝑣𝑜𝑖𝑑 𝑚𝑦_𝑚𝑒𝑡ℎ𝑜𝑑()
{ ........ }
};
Java anonymous inner class example using class

File: Test.java
class Demo
{
void show()
{
System.out.println("i am in show method of super class");
}
}

public class Test


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

Demo d = new Demo()


{
void show() An anonymous
class with Demo as
{
base class
super.show();
System.out.println("i am in anonymous inner class");
}
};

d.show(); Output:
} i am in show method of super class
} i am in anonymous inner class

39 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Java anonymous inner class example using interface

File: Demo.java
public class Demo
{
public static void main(String[] args)
{

Hello h = new Hello()


{
An anonymous class
public void show() that implements
{ Hello interface
System.out.println("i am in anonymous class");
}
};

h.show();
}
}

interface Hello
Output:
{
i am in anonymous class
void show();
}

Static nested class


A static class i.e. created inside a class is called static nested class in java.
It cannot access non-static data members and methods. It can be accessed by outer
class name.
 It can access static data members of outer class including private.

 Static nested class cannot access non-static (instance) data member or methods

Syntax

𝑐𝑙𝑎𝑠𝑠 𝑂𝑢𝑡𝑒𝑟 {
𝑠𝑡𝑎𝑡𝑖𝑐 𝑐𝑙𝑎𝑠𝑠 𝐼𝑛𝑛𝑒𝑟
{ }
}
}
}

40 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Java static nested class example

File: Outer.java

public class Outer Outer class


{
static data is accessed both in
static int data = 100;
outer class and inner class
String str = "APEC";
void display()
{
System.out.println("Given String is APEC");
}
static class Inner
{
void msg()
Static Inner class
{
System.out.println("Given data : "+ data);
}
}

public static void main(String args[])


{
Outer out = new Outer(); Object for outer class

out.display();

Outer.Inner obj = new Outer.Inner(); Object for Inner class

obj.msg();
}
Output:
Given String is APEC
Given data : 100

41 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are:
 Nested classes represent a special type of relationship that is it can access all
the members (data members and methods) of outer class including private.

 Nested classes are used to develop more readable and maintainable code
because it logically group classes and interfaces in one place only.
 Code Optimization: It requires less code to write.

Array Lists in Java


ArrayList is a part of collection framework and is present in java.util
package. It provides us dynamic arrays in Java. Standard Java arrays are of a fixed
length. After arrays are created, they cannot grow or shrink, which means that you
must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded,
the collection is automatically enlarged. When objects are removed, the array may
be shrunk.
 ArrayList inherits AbstractList class and implements List interface.

 ArrayList is initialized by a size; however the size can increase if collection
grows or shrunk if objects are removed from the collection.

 Java ArrayList allows us to randomly access the list.

 ArrayList cannot be used for primitive types, like int, char, etc. We need a
wrapper class for such cases.

Array Lists are like Rubber bands Arrays are like ropes. They are fixed.

Constructors in Java ArrayList:


 ArrayList(): This constructor is used to build an empty array list

42 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
 ArrayList(Collection c): This constructor is used to build an array list
initialized with the elements from collection c

 ArrayList(int capacity): This constructor is used to build an array list with
initial capacity being specified.
Methods in Java ArrayList:

Method Description

clear() Remove all the elements from the list.


add(int index, Object
Insert a specific element at a specific position index in a
element) list.

trimToSize() Trim the capacity of the instance of the ArrayList to the


list’s current size.

indexOf(Object O) Index the first occurrence of a specific element is either


returned, or -1 in case the element is not in the list.

lastIndexOf(Object O) Index the last occurrence of a specific element is either


returned, or -1 in case the element is not in the list.

clone() Return a shallow copy of an ArrayList.

isEmpty() Check if the list is empty or not.

contains(Object o) Returns true if this list contains the specified element

get(int index) Returns the element of a specified position within the list.

toArray() Return an array containing all of the elements in the list in


correct order.

toArray(Object[] O) Returns an array containing all of the elements in this list


in the correct order same as the previous method.

Append all the elements from a specific collection to the


addAll(Collection C) end of the mentioned list, in such a order that the values
are returned by the specified collection’s iterator.

add(Object o) Append a specified element to the end of a list.

addAll(int index,
Insert all of the elements starting at the specified position
Collection C) from a specific collection into the mentioned list.

remove(int index) Remove an element at a specified index from ArrayList

43 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Syntax:

𝐴𝑟𝑟𝑎𝑦𝐿𝑖𝑠𝑡 𝑎𝑙 = 𝑛𝑒𝑤 𝐴𝑟𝑟𝑎𝑦𝐿𝑖𝑠𝑡();  Old method


New Generic way of creating Arraylists is:
𝑨𝒓𝒓𝒂𝒚𝑳𝒊𝒔𝒕 < 𝑺𝒕𝒓𝒊𝒏𝒈 > 𝒂𝒍 = 𝒏𝒆𝒘 𝑨𝒓𝒓𝒂𝒚𝑳𝒊𝒔𝒕 < 𝑺𝒕𝒓𝒊𝒏𝒈 > ();

Methods in the arraylist are invoked using:


𝑨𝒓𝒓𝒂𝒚𝑳𝒊𝒔𝒕.𝑴𝒆𝒕𝒉𝒐𝒅𝒏𝒂𝒎𝒆()

Pictorial representations of some methods in arraylists:

Syntax: ArrayList.clear() Syntax: ArrayList.add(int index, E ele)

Syntax: ArrayList. trimToSize() Syntax: ArrayList. indexOf(Object o)

44 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Syntax: Syntax: ArrayList.clone()
ArrayList.lastIindexOf(Object o)

Syntax: ArrayList.isEmpty() Syntax: ArrayList.contains(Object o)

Syntax: ArrayList.get() Syntax: ArrayList.addAll()

45 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Syntax: ArrayList. remove(index) Syntax: ArrayList.toArray(T[] a)

46 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Filename : Test.java
import java.util.*;
public class Test {
Create an empty
public static void main(String[] args) {
array list, color_list

ArrayList<String> color_list = new ArrayList<String>(10);

color_list.add("White");
Use add() method to

color_list.add("Black"); add values in the list


color_list.add("Red");

System.out.println("Given List:");
Print out the colors
for (int i = 0; i < 3; i++) in the ArrayList
System.out.println(color_list.get(i));
Append Green color
color_list.add(1,"Green"); at 2nd position
System.out.println("Green color is inserted:");
for (int i = 0; i < 4; i++)
System.out.println(color_list.get(i));
Index of the Black color
int i = color_list.indexOf("Black"); is determined
System.out.println("Black color is at
position :" +(i+1));
Black color is removed from the list

color_list.remove("Black");

System.out.println("After removing Black from the list"); Create another array


for (i = 0; i < 3; i++) list, animal_list
System.out.println(color_list.get(i));

ArrayList<String> animal_list = new ArrayList<String>(5);


animal_list.add("Lion");
animal_list.add("Tiger");
animal_list.add("Dog");
Combine color_list
and animal_list
color_list.addAll(animal_list);
System.out.println("Combining color_list and animal_list");
for (i = 0; i < 6; i++)
System.out.println(color_list.get(i));

String[] str = new String[10]; New array, str is created.


str = color_list.toArray(str); Arraylist is converted to array
System.out.println("Array is printed");
for (String s : str)
Array is printed
System.out.println(s);

}
}

Output:
Given List:
White
Black
Red
Green color is inserted:
White
Green
Black
Red
Black color is at position :3
After removing Black from the list
White
Green
Red
Combining color_list and animal_list
White
Green
Red
Lion
Tiger
Dog
Array is printed
White
Green
Red
Lion
Tiger
Dog
null
null
null
null

Java Strings
String is a sequence of characters. In Java programming language, strings are treated as objects.
The 𝒋𝒂𝒗𝒂.𝒍𝒂𝒏𝒈.𝑺𝒕𝒓𝒊𝒏𝒈 class is used to create string object. There are two ways to create a String object:

 Implicit construction using string literal : Java String literal is created by using
double quotes.
o Example:= 𝑺𝒕𝒓𝒊𝒏𝒈 𝒔 = “𝑾𝒆𝒍𝒄𝒐𝒎𝒆”;

 Explicit construction using new keyword : Java String is created by using a
keyword “new”.
o Example:= 𝑺𝒕𝒓𝒊𝒏𝒈 𝒔 = 𝒏𝒆𝒘 𝑺𝒕𝒓𝒊𝒏𝒈(“𝑾𝒆𝒍𝒄𝒐𝒎𝒆”);
Difference between string literal and new operator:

String s1 = "Hello"; // String literal


String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object

Java has provided a special mechanism for keeping the String literals - in a so-
called string common pool. If two string literals have the same contents, they will
share the same storage inside the common pool. This approach is adopted to
conserve storage for frequently-used strings. On the other hand, String objects
created via the new operator and constructor are kept in the heap. Each String object
in the heap has its own storage just like any other object. There is no sharing of
storage in heap even if two String objects have the same contents.
Defining and initializing Strings:
Simple example
String s1 = "Welcome to Java!";
String s2 = new String("Welcome to Java!"); //same as s1
Numbers as strings
String s3 =“12345”;
String s4 = new String(s3); //s4 will hold same value as s3
Char array as strings
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'
}; String s5= new String(helloArray);

49 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Simple Example for Defining and initializing Strings
Filename : Test.java
public class Test
{ public static void main(String args[])
{
String s1 = "Welcome to Java!";
Creating string by
System.out.println("Using String Literal : " + s1); java string literal

String s2 = new String("Welcome to Java!"); Creating java string


by new keyword
System.out.println("Using new operator : " + s2);

String s3 ="12345"; Numbers as a string

String s4 = new String(s3);


System.out.println("Printing numbers as a string : " + s3);
System.out.println(s4);
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; Converting char
array to string
String s5 = new String(helloArray);
System.out.println("Character Array converted to string : " + s5);
}}
Output:
Using String Literal : Welcome to Java!
Using new operator : Welcome to Java!
Printing numbers as a string : 12345
12345
Character Array converted to string : hello.

Java String class implements three interfaces, namely – Serializable, Comparable and
CharSequence. The CharSequence interface is used to represent sequence of
characters. It is implemented by String, StringBuffer and StringBuilder classes. It
means, we can create string in java by using these 3 classes.

50 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
In Java, Strings are immutable. By immutable means, Strings are constant;
their values cannot be changed after they are created. For mutable string, you can
use StringBuffer and StringBuilder classes.

Java String Methods:

Method Description Example


It tells the length of the string by counting the String s1="hello";
length()
total number of characters present in the String. s1.length() = 5
String s1="hello";
Compares the given string with current string.
String s2="hello";
compareTo() If s1 > s2, it returns a positive number String s3="hai";
if s1 < s2, it returns a negative number
s1.compareTo(s2) = 0
if s1 == s2, it returns 0
s1.compareTo(s3) = 4
String s1="Hi";
Combines a specific string at the end of another String s2 =”Hello”;
concat()
string. It is like appending another string. s1.concat(" hru!") = Hi hru!
s1.concat(s2) = HiHello
String s1="hello";
Checks whether the String contains anything or s1.isEmpty() = false
IsEmpty()
not. String s1="";
s1.isEmpty() = true
String s1="Hi ";
String s2="hru";
Trim() Removes the leading and trailing spaces. s1 + s2 = Hi hru
s1.trim() + s2 = Hihru

Converts all the characters of the String to lower String s1="H R You?”;
toLowerCase()
case. s1.toLowerCase() = h r you?
Converts all the characters of the String to upper String s1="H R You?”;
toUpper()
case. s1.toUpperCase() = H R YOU?

int value=20;
String s1;
ValueOf() Converts different types of values into string.
s1=String.valueOf(value);
s1+18 = 2018

String s1="hello hai hi”;


replace() s1 = s1.replace('h','t');
Replace all the old characters with the new s1= tello tai ti
characters.
String s1="Hi, welcome";
s1=s1.replace("Hi","CSE");
s1 = CSE, welcome

51 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Method Description Example
String s1 =" hello hai hi!";
Searches the sequence of characters in the s1.contains("hi") = true
contains()
string. If found, return true else return false s1.contains("helloo") = false
s1.contains("hru") = false

Compares the two given strings. If matched, String s1="hello";


return true else return false. String s2="Hello";
equals()
equalsIgnoreCase -> Ignore the cases and
s1.equals(s2) = false
campare the strings. s1.equalsIgnoreCase(s2)= true

String s1="hello how are you”;


s1.endsWith("u") = true
endsWith() Checks if this string ends with the given suffix.
s1.endsWith("you") = true
s1.endsWith("how") = false

Java program to sort the string in alphabetical order:

Filename : Test.java
Import the utility arrays to use
import the sort function in the program
java.util.Arrays; public
class Test {
public static void main(String[] args)
{
String str = "javaprogramming";
Given string is converted to
char a[] = str.toCharArray(); character array and then it is sorted

System.out.println("Input String : " + str);

Arrays.sort(a); Sort the character array using sort function

System.out.print("Sorted String : " );


for (int i = 0; i < str.length(); i++)
System.out.print(a[i]);
}
}

Output:
Input String : javaprogramming
Sorted String : aaaggijmmnoprrv

52 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Java program to sort the numbers in alphabetical order:

Filename : Test.java
Output:
import java.util.Arrays; Input Array Elements: 100 67 89 32 65 75
Sorted Array : 32 65 67 75 89 100

public class Test


{ public static void main(String[] args)
{
int num[] = {100,67,89,32,65,75};

System.out.print("Input Array Elements: ");


for (int i = 0; i < num.length; i++) Finding the array size using
length

System.out.print(num[i] + " ");

Arrays.sort(num);
Sorting the Integer array

System.out.println();
System.out.print("Sorted Array : " );
for (int i = 0; i < num.length; i++)
System.out.print(num[i] + " ");
} }

Java program to sort the strings in alphabetical order:


Filename : Test.java
import java.util.Arrays;

public class Test


{
Declaring the string array and
public static void main(String[]
args) { initialized with the values

String str[] = {"thankyou", "hai", "every", "babuji", "god"};


System.out.print("Input Strings : "); for (int i = 0; i < str.length;
i++)
System.out.print(str[i] + " ");

Arrays.sort(str); Sort the string array

System.out.println();
System.out.print("Sorted strings
: " );
for (int i = 0; i < str.length; i++) Output:
System.out.print(str[i] + " "); Input Strings: thankyou hai every babuji god
Sorted strings : babuji every god hai thankyou
}
}

53 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s

You might also like