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

Java - Module 2 PPT

The document discusses Object-Oriented Programming concepts, specifically focusing on inheritance, interfaces, and the use of keywords like 'this' and 'super'. It explains various types of inheritance (single, multilevel, hierarchical), the structure of abstract classes, method overriding, and the significance of the 'final' keyword. Additionally, it provides examples and quizzes to reinforce understanding of these concepts.

Uploaded by

chandru m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java - Module 2 PPT

The document discusses Object-Oriented Programming concepts, specifically focusing on inheritance, interfaces, and the use of keywords like 'this' and 'super'. It explains various types of inheritance (single, multilevel, hierarchical), the structure of abstract classes, method overriding, and the significance of the 'final' keyword. Additionally, it provides examples and quizzes to reinforce understanding of these concepts.

Uploaded by

chandru m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111

Object Oriented Programming

Unit - II
Inheritance and Interfaces
Inheritance

● Inheritance is a mechanism in which one class acquires the property of


another class.
● For example, a child inherits the traits of his/her parents
● With inheritance, we can reuse the fields and methods of the existing class
● It provide the reusability of code
● Class inherits the properties of other is known as subclass
● Class whose properties are inherited is known as superclass
is-a relationship

● Inheritance is an is-a relationship


● Use inheritance only if an is-a relationship is present between the two classes
● Examples
○ A car is a vehicle.

○ Orange is a fruit.
○ A surgeon is a doctor
○ A dog is an animal
What is inherited?
● Public and protected fields and methods are inherited

● Fields and methods with default access modifiers can be accessed by


subclasses

● Private fields and methods of the superclass can never be referenced directly
by subclasses

● Constructors are not inherited by subclasses

● Subclass constructor must call a constructor in the superclass


Terms used in inheritance

● Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
● Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
● Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
● Reusability: It is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class
protected modifier

● Protected members are accessible

○ From within the class

○ Within its sub class

○ Within the same package


Syntax

class Superclass-name{

//methods and fields

class Subclass-name extends Superclass-name{

//methods and fields

}
Single Inheritance
Single Inheritance - Syntax

class Parent {
// methods
// fields
}
class Child extends Parent {
// already supports the methods and fields in Parent class
// additional features
}
Example
class Parent {
public void p1() {
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1() {
System.out.println("Child method");
}
public static void main(String[] args) {
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}
Multilevel Inheritance
Multilevel Inheritance - Syntax
class GrandParent {
// methods
// fields
}
class Parent extends GrandParent {
// already supports the methods and fields in Parent class
// additional features
}
class Child extends Parent {
// already supports the methods and fields in Parent class
// additional features
}
Multilevel Inheritance - Example
class GrandParent {
public void gp1() {
System.out.println(“Grand Parent method");
}
}
class Parent extends GrandParent {
public void p1() {
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1() {
System.out.println("Child method");
}
public static void main(String[] args) {
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
cobj.gp1(); //method of GrandParent class
}
}
Hierarchical Inheritance
Hierarchical Inheritance - Syntax
class Parent {
// methods
// fields
}
class Son extends Parent {
// already supports the methods and fields in Parent class
// additional features
}
class Daughter extends Parent {
// already supports the methods and fields in Parent class
// additional features
}
Hierarchical Inheritance - Example
class Parent {
public void p1() {
System.out.println(“Parent method");
}
}
class Son extends Parent {
public void s1() {
System.out.println(“Son method");
}
}
public class Daughter extends Parent {
public void d1() {
System.out.println(“Daughter method");
}
public static void main(String[] args) {
Child cobj = new Child();
cobj.d1(); //method of Daughter class
cobj.s1(); //method of Son class
cobj.p1(); //method of Parent class
}
}
this keyword

● this is a reference variable that refers to the current object inside a method
or a constructor.

● The most common use of the this keyword is to eliminate the confusion
between class attributes and parameters with the same name

● It can be used to refer to any member of the current object from within an
instance method or a constructor.
Usage of „this‟ keyword
● to refer current class instance variable

● to invoke current class method (implicitly)

● to invoke current class constructor

● passed as an argument in the method call

● passed as argument in the constructor call

● to return the current class instance from the method


to refer current class instance variable
class ThisDemo{
int x;
void setValue(int x){
this.x=x;
}
void showValue(){
System.out.println(x);
}
public static void main(String[] args){
ThisDemo td=new ThisDemo();
td.setValue(5);
td.showValue();
}
}
to invoke current class method (implicitly)
class ThisDemo{
void show(){
System.out.println("show method");
}
void callShow(){
show(); //replaced by this.show()
}
public static void main(String[] args){
ThisDemo td=new ThisDemo();
td.callShow();
}
}
to invoke current class constructor

class ThisDemo{
ThisDemo(){
System.out.println(“Default Constructor”);
}
ThisDemo(int x){
this();
System.out.println(“x=“+x);
}
public static void main(String[] args){
ThisDemo td=new ThisDemo(5);
}
}
to pass as an argument in a method
class ThisDemo{
void show(ThisDemo td){
System.out.println("show method");
}
void callShow(){
show(this);
}
public static void main(String[] args){
ThisDemo td=new ThisDemo();
td.callShow();
}
}
to pass as argument in the constructor call
class Demo{
int y;
Demo(ThisDemo t1){
y=t1.x;
System.out.println("y="+y);
}
}
class ThisDemo{
int x=5;
ThisDemo(){
Demo d1=new Demo(this);
}
public static void main(String[] args){
ThisDemo td=new ThisDemo();
}
}
this keyword can be used to return current class instance
class Demo{
int y=5;
Demo retun(){
return this;
}
void show(){
System.out.println(y);
}
public static void main(String[] args){
new Demo().retun().show();
}
}
Super keyword
● It is a reference variable, used to refer immediate parent class object
● It is used to call superclass methods, and to access the superclass
constructor.
● The most common use of the super keyword is to eliminate the confusion
between superclasses and subclasses that have methods with the same
name
Optional
● Syntax
super([arguments]);
Rules of Super Keyword

● super() must be the first statement in the body of subclass constructor when
call the superclass constructor
● A superclass constructor can only be called from a subclass constructor.
Any other subclass method cannot call it.
● A superclass constructor call requires the use of super. It is illegal to specify
the actual name of the class.
● From outside the class, a constructor is always called with a new keyword, it
may be called from another constructor with this or super.
● “this” operator is used to call another constructor of the same class while
super is used to call the constructor of its superclass
Usage of “super” keyword

● to refer immediate parent class instance variable

● to invoke immediate parent class method

● to invoke immediate parent class constructor


To refer immediate parent class instance variable
class First{
int x=10;
}
class Second extends First{
void show(){
System.out.println(super.x+5);
}
}
class SuperDemo{
public static void main(String[] args){
Second s1=new Second();
s1.show();
}
}
To invoke immediate parent class method
class First{
int x;
void setValue(int y){
x=y;
}
}
class Second extends First{
void setValue(int y){
x=y;
}
void show(){
super.setValue(5);
System.out.println(super.x+5);
}
}
class SuperDemo{
public static void main(String[] args){
Second s1=new Second();
s1.show();
}
}
to invoke immediate parent class constructor
class First{
int x;
First(){
System.out.println(" First default");
}
First(int y){
x=y;
}
}
class Second extends First{
Second(){
super(5);
}
void show(){
System.out.println("x="+x);
}
}
class SuperDemo{
public static void main(String[] args){
Second s1=new Second();
s1.show();
}
}
Constructors in Inheritance
● No constructors in base and derived classes
○ Compiler allocate constructor both base and derived classes
● Constructor only in the base class
○ Accesses base constructor
● Constructor only in the derived class
○ Access derived class constructor
● Constructor both in base and derived classes
○ Access both constructors
● Multiple constructor in base class and a single constructor in derived class
○ Access base class default constructor and derived specific constructor
● Constructor in base and derived classes without default constructor
○ Compiler generate error
Quiz
class First{
First(){
System.out.print(“First ”);
}
}
class Second extends First{
Second(){
a. First
System.out.print(“Second ”);
b. Second
}
c. Third
}
d. First Second Third
class Third extends Second{
Third(){
System.out.println(“Third”);
}
}
class Test{
public static void main(String[] args){
new Third();
}
}
Quiz
class A{
public A(String s) {
System.out.print("A");
}
} a. AB
public class B extends A{ b. ABC
c. BA
public B(String s) { d. Compiler Error
System.out.print("B");
}
public static void main(String[] args) {
new B("C");
System.out.println(" ");
}
}
Object class

● Object class is the parent class of all the classes in java by default. ie it is the
topmost class of java
● Object class is beneficial if you want to refer any object whose type you don't
know
● parent class reference variable can refer the child class object, know as
upcasting
● getObject() method that returns an object but it can be of any type like
Employee,Student etc. Object obj=getObject();
● Object class is present in java.lang package
Object class methods
● toString() - public String toString()
● hashCode() - public int hashCode()
● equals(Object obj) - public boolean equals(Object obj)
● getClass() - public final Class getClass()
● finalize() - protected void finalize()throws Throwable
● clone() - protected Object clone() throws CloneNotSupportedException
● wait() - public final void wait(long timeout)throws InterruptedException
● notify() - public final void notify()
● notifyAll() - public final void notifyAll()
Abstract class

● Abstraction is the process of hiding certain details and showing only


essential information to the user
● Abstraction can be achieved by two ways
○ abstract class (0 to 100%)
○ Interfaces (100%)
● abstract keyword is a non-access modifier, used for classes and methods
● A class declared with the abstract keyword is known as an abstract class
● Abstract class is a restricted class that cannot be used to create objects
● Abstract method can only be used in an abstract class, and it does not have a
body
○ The body of abstract method is provided by the subclass
Syntax for abstract class
keyword Name of the class

method without body


abstract class ClassName{
//abstract method method with body

//non-abstract method
method name same as
//constructors
class name
//static methods
//final methods method with static keyword
}
method with final keyword
Example for abstract class

abstract class Shape {

int color;

abstract void draw(); // abstract method

}
Using abstract class
abstract class Shape {
abstract void draw();
}
class Square extends Shape {
void draw() {
System.out.println(“Square shape");
}
}
class ShapeDemo {
public static void main(String args[]) {
Shape s1=new Shape(); X
Shape s1 = new Square(); // references of Base type.
s1.draw();
}
}
Quiz

Which of these method of Object class can generate duplicate copy of the object
on which it is called?
a) clone()
b) copy()
c) duplicate()
d) dito()
Abstract class with constructor
abstract class Base {
Base() {
System.out.println("Base Constructor Called");
}
Output
abstract void fun();
Base Constructor Called
} Derived Constructor Called
class Derived extends Base {
Derived(){
System.out.println("Derived Constructor Called");
}
void fun(){
System.out.println("Derived fun() called");
}
}
class Main {
public static void main(String[] args) {
Derived d = new Derived();
}
}
abstract class without any abstract method
abstract class Base {
void fun() {
System.out.println("Base fun() called");
}
} Output
class Derived extends Base { Base fun() called
}
class Main {
public static void main(String[] args) {
Derived d = new Derived();
d.fun();
}
}
abstract class with a final method
abstract class Base {
final void fun(){
System.out.println("Derived fun() called");
}
} Output
class Derived extends Base{ Derived fun() called
}
class Main{
public static void main(String[] args){
Base b = new Derived();
b.fun();
}
}
Method overriding

● Both sub class and the super class have the same method

● Implementation is differ both in sub class and super class

● Used to achieve run time polymorphism

● The method to be executed is determined during run time

● If the object belongs to super class then super class method will be invoked

● If an object belongs to sub class then sub class method will be invoked
Rules for Java Method Overriding

● The method must have the same name, same parameter and same return
type as in the parent class

● There must be an IS-A relationship (inheritance)

● Cannot override the method declared as final and static

● We should always override abstract methods of the superclass

● Both super class and sub class can have different access specifier
Example for method overriding
class Super{
void show(){
System.out.println("Super class method");
}
}
class Sub extends Super{
void show(){
System.out.println("Sub class method");
}
}
class OverRide{
public static void main(String[] args){
Super s1=new Super();
s1.show(); //Super class method
s1=new Sub();
s1.show(); //Sub class method
}
}
Quiz

Which of the following is FALSE about abstract classes in Java

(A) If we derive an abstract class and do not implement all the abstract methods,
then the derived class should also be marked as abstract using „abstract‟
keyword

(B) Abstract classes can have constructors

(C) A class can be made abstract without any abstract method

(D) A class can inherit from multiple abstract classes.


final keyword

● It is a non-access modifier

● It is used for finalizing the implementations of


○ Variables and Parameters

■ Stop value change

○ Methods

■ Stop method overriding

○ Classes

■ Stop inheriting
final variable
● Variable declared with final keyword
● It‟s value can‟t be modified ie. it is a constant
● It must be initialized
● If it is not initialized then it is called as blank final variable
● Blank final variable can be initialized by
○ Initializer block
○ constructor
● It can be static
● It can be a reference
○ Cannot be re-bound to reference another object
○ It can be updated
final variable

// declaring a final variable

class FinalVariable {

final int var = 50;

var = 60; //This line would give an error

}
final reference
class Reference{
public int value = 5;
}
class FinalRefVariable {
public static void main( String args[] ) {
final Reference example = new Reference(); //declaration
example.value = 6; // Modifying the object creates no disturbance
Reference another = new Reference();
// Attempting to change the object it refers to, creates an error
example = another;
}
}
final parameter

class FinalParameter {

//final parameter

public static void main( final int parameter ) {

parameter = 4; //attempting to reassign a value to a parameter throws an error

}
final method
// declaring a final method
class Base{
public final void finalMethod(){
System.out.print("Base");
}
}
class Derived extends Base{
public final void finalMethod() { //Overriding the final method throws an error
System.out.print("Derived");
}
}
final class

// declaring a final class


final class FinalClass {
//...
}
//attempting to inherit a final class throws an error
class Subclass extends FinalClass{
//...
}
Interfaces

● It is a blueprint of a class

● It has static constants and abstract methods.

● It is a mechanism to achieve abstraction

● It is used to achieve abstraction and multiple inheritance in Java

● It also represents the IS-A relationship

● It cannot be instantiated like abstract class


Interfaces
An interface is similar to a class in the following ways −

● An interface can contain any number of methods.

● An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.

● The byte code of an interface appears in a .class file.

● Interfaces appear in packages, and their corresponding bytecode file must be


in a directory structure that matches the package name
Interfaces
An interface is different from a class in several ways, including −
● We cannot instantiate an interface.
● An interface does not contain any constructors.
● All of the methods in an interface are abstract.
● An interface cannot contain instance fields. The only fields that can appear in
an interface must be declared both static and final.
● An interface is not extended by a class; it is implemented by a class.
● An interface can extend multiple interfaces
Interfaces

Syntax

public interface NameOfInterface {

// Any number of final, static fields

// Any number of abstract method declarations

}
Example

interface Shape {

int radius=3;

double getArea();

}
Interfaces

Interfaces have the following properties

● An interface is implicitly abstract.

● Each method in an interface is also implicitly abstract

● Methods in an interface are implicitly public

● Interface without members are called as marker or tagged interface (Ex.


Serializable, Clonable, Remote etc.)
Quiz

Which of these is not a correct statement?


a) Every class containing abstract method must be declared abstract
b) Abstract class defines only the structure of the class not its implementation
c) Abstract class can be initiated by new operator
d) Abstract class can be inherited
Key points about Interfaces
● we cannot create the object of an interface
● Interface provides full abstraction as none of its methods have body
● implements keyword is used by classes to implement an interface
● Class that implements any interface must implement all the methods of that interface, else the class should be declared
abstract
● Interface cannot be declared as private, protected or transient
● All the interface methods are by default abstract and public
● Variables declared in interface are public, static and final by default
● Interface variables must be initialized at the time of declaration otherwise compiler will throw an error
● Inside any implementation class, we cannot change the variables declared in interface
● An interface can extend any interface but cannot implement it
● A class can implement any number of interfaces
● If there are two or more same methods in two interfaces and a class implements both interfaces, implementation of the
method once is enough
● A class cannot implement two interfaces that have methods with same name but different return type
● Variable names conflicts can be resolved by interface name
● Since Java 8, you can also create default methods
Implementing an interface
interface Shape{
int radius=3;
double getArea();
}
class Circle implements Shape{
public double getArea(){
return 3.14*radius*radius;
}
public static void main(String[] args){
Circle c1=new Circle();
System.out.println(“Area of circle :” +c1.getArea());
}
}
Instance of an interface
● Interface cannot contain constructor, therefore we cannot create an instance
● Create an instance of an interface by the implemented class
● Example
interface Shape{
}
class Circle implements Shape{
public static void main(String[] args){
Shape s1=new Shape(); X
Shape s2=new Circle(); √
}
}
Multiple interfaces
● Can implement multiple interfaces for a class
● All the methods of all the interfaces must be defined by the class

interface HemiSphere{
double volumeHS();
}
interface Cone{
double volumeC();
}
class Shape implements HemiSphere, Cone{
public volumeHS(){
}
public volumeC(){
}
public static void main(String[] args){
}
}
“default” methods in interface
● default method can contain its own implementation directly within the interface
● If no body for a default method then compiler generate an error
interface Shape{
default double area(){
return 3.14*3*3;
}
}
class Circle implements Shape{
public static void main(String[] args){
System.out.println(“Area of circle: ”+new Circle().area());
}
}
static method in interfaces
● Java 8 is the ability to add static methods to interfaces

● Static methods in interfaces are almost identical to static methods in


concrete classes

● The only big difference is that static methods are not inherited in the classes
that implement the interface

● This means that the interface is referenced when calling the static method
not the class that implements it
static method in interfaces
interface Shape{
static void show(){
System.out.println(“Static method”);
}
}
class InterDemo implements Shape{
public static void main(String[] args){
InterDemo id=new InterDemo();
id.show(); //Error
Shape.show();
}
}
Inheritance in interfaces
Multiple inheritance
Difference between class and interface
CLASS INTERFACE
The keyword used to create a class is “class” The keyword used to create an interface is “interface”
A class can be instantiated i.e, objects of a class can An Inteface cannot be instantiated i.e, objects cannot
be created. be created.
Classes does not support multiple inheritance. Inteface supports multiple inheritance.
It can be inherit another class. It cannot inherit a class.
It can be inherited by a class by using the keyword
It can be inherited by another class using the keyword
„implements‟ and it can be inherited by an interface
„extends‟.
using the keyword „extends‟.
It can contain constructors. It cannot contain constructors.
It cannot contain abstract methods. It contains abstract methods only.
Variables and methods in a class can be declared
All variables and methods in a interface are declared as
using any access specifier(public, private, default,
public.
protected)
Variables in a class can be static, final or neither. All variables are static and final.
Object cloning

● It is a way to create an exact copy of an object


● It is a way of creating a new object by copying all the data and attributes
from the original object
● This is only possible by implementing clone() method of
the java.lang.Object class
● The clone method creates an exact copy of an object for which it has
been invoked in a field-by-field assignment order and will return the new
object reference
Advantage of Object cloning

● Helps in reducing the lines of code.

● The most effective and efficient way of copying objects.

● The clone() is considered to be the fastest method to copy an array


Steps to follow object cloning

● Cloning class must implements Cloneable interface

● Override the clone() method and it must invoke super class clone() method

● Clone() method must throws CloneNotSupportedException


Two types

● Shallow cloning

○ Copying only primitive type values

● Deep cloning

○ Copying primitive and non-primitive type values


Example
class Numbers implements Cloneable{
int val;
public Object clone()throws CloneNotSupportedException{
return super.clone();
} try{
void show(){ Numbers n2=(Numbers)n1.clone();
System.out.println("val="+val); n2.val=20;
} n1.show();
} n2.show();
class CloneDemo{ }
public static void main(String[] args){ catch(CloneNotSupportedException cn){}
Numbers n1=new Numbers(); }
n1.val=10; }
n1.show();
Nested classes
● Define a class within another class
● Logically group classes that are only used in one place
● It increases the use of encapsulation
● It creates more readable and maintainable code

● Syntax
class Outer_Class{
//…
class Inner_Class{
//…
}
}
Types of Nested classes

Nested Classes

Non-static Nested Static


Classes (inner classes) Nested Classes

Nested Method local Anonymous


Inner Classes inner Classes inner Classes
Inner classes

● It is defined inside the body of another class or an interface

● It can have access modifier or even can be marked as abstract and final

● It is used to logically group classes and interfaces in one place

● it can access all the members of outer class including private data members
and methods

● To access the inner class, create an object of the outer class, and then
create an object of the inner class

● An inner class can be private or protected


Nested/Member inner class
● Created inside a class but outside a method
● It can be declared as private
● It cannot be accessed outside the class if private
class Outer{
class NestedInner{
int x=5;
public static void main(String[] args){
class Inner{
Outer o1=new Outer();
int x=10;
System.out.println("outer x="+o1.getOuter());
int getInner(){
Outer.Inner oi=o1.new Inner();
return x;
System.out.println("inner x="+oi.getInner());
}
}
}
}
int getOuter(){
return x;
}
}
Local inner class
● Class declared inside a method
● If we want to invoke the methods of local inner class, we must instantiate
this class inside the method
class Inner{
void show(){ class LocalInner{
class Local{ public static void main(String[] args){
void show(){ Inner i1=new Inner();
System.out.println("Local Inner"); i1.show();
}
}
}
}
Local li=new Local();
li.show();
}
}
Anonymous inner class
● Anonymous classes are nested classes without class name
● Declared with classes or with interfaces
class Inner{
void show(){ interface Inner{
System.out.println("Inner show"); void show();
} }
} class AnonymousInterface{
class AnonymousInner{ public static void main(String[] args){
public static void main(String[] args){ Inner i1=new Inner(){
Inner i1=new Inner(){ public void show(){
void show(){ System.out.println("inner interface");
System.out.println("Anonymous class"); }
}
};
i1.show();
};
}
i1.show();
}
}
}
Anonymous inner as argument
interface Message{
String show();
}
class AnonymousArgs{
void print(Message m1){
System.out.println(m1.show());
}
public static void main(String[] args){
AnonymousArgs aa=new AnonymousArgs();
aa.print(new Message(){
public String show(){
return "Anonymous inner";
}
});
}
}
static nested class

● A static class created inside a class is called static nested class

● 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
class Outer{
static class Inner{
void show(){
System.out.println("Inner show");
}
}
void show(){
System.out.println("Outer show");
}
}
class StaticInner{
public static void main(String[] args){
Outer.Inner oi=new Outer.Inner();
oi.show();
}
}
ArrayList
● ArrayList is a part of collection framework
● It is present in java.util package.
● It provides dynamic arrays in Java.
● It may be slower than standard arrays
● ArrayList class can contain duplicate elements
● ArrayList class maintains insertion order
● ArrayList allows random access because array works at the index basis
Adding elements in ArrayList
Removing element from ArrayList
Syntax for creating ArrayList

Predefined or user-
defined object

ArrayList<Object-Type> arraylist=new ArrayList<Object-Type>();

Name of the list

Example

ArrayList<String> namelist=new ArrayList<String>()


Methods in ArrayList
Method Description

void add(int index, E element) It is used to insert the specified element at the specified position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
void clear() It is used to remove all of the elements from this list.
E get(int index) It is used to fetch the element from the particular position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified
element, or -1 if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in the correct
order.
Object clone() It is used to return a shallow copy of an ArrayList.
boolean contains(Object o) It returns true if the list contains the specified element
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified
element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
E set(int index, E element) It is used to replace the specified element in the list, present at the specified
position.
int size() It is used to return the number of elements present in the list.
Creating ArrayList

ArrayList<String> namelist=new ArrayList<String>();

namelist.add(“Ganesh”);

namelist.add(“Mahesh”);

namelist.add(“Gukesh”);

namelist.add(“Rupesh”);

namelist.add(“Rajesh”);
Print the elements of an ArrayList
System.out.println(namelist);
or
for(String s1:namelist){
System.out.println(s1);
}
or
for(i=0;i<namelist.size();i++){
System.out.println(namelist.get(i);
}
Insert an element in a list
add( index, value )

Example
Insert element in third location

namelist.add(2, “Rakesh”);
Delete an element from a list

remove(index)
or
remove(element)

Example

namelist.remove(2);

or

namelist(“Rakesh”);
Retrieve and Modify an element
get(index)

Example

String name=namelist.get(2); //get third element from the list

set(index, value)

Example

namelist.set(2, “Suresh”); //modify the third element


Sort a list
Collection.sort(list);

Example

Collection.sort(namelist);

for(String name:namelist){

System.out.println(name);

}
String
● Strings are a sequence of characters
● Strings are treated as objects that are backed internally by a char array
● Strings are immutable
● Syntax
String variable = “sequence of string”;
or
String variable=new String(“sequence of string”);
● Example
String s1=“String value”; //by literal
String s1=new String(“String value”); //by object
Strings

● String literal

○ While creating string literal, JVM checks in the string constant pool, if already available, it
won‟t create the literal

○ Example

■ String s1=“Java”;

■ String s2=“Java”;
String length

● int length()

○ Returns the number of characters in the string object


● Example

String s1=“Java Programming”;

s1.length() – returns 16
String compare
● Comparing two string
○ Comparison based on reference (==), content (equals and compareTo)

● equals
○ boolean equals(String)

○ boolean equalsIgnoreCase(String)

String s1=“Java”

String s2=“Java”

String s3=„java”;

boolean b1=s1.equals(s2); //true

boolean b1=s2.equals(s3); //false


String compare
● Using == operator

● Example

String s1=“Java”;

String s2=“Java”;

String s3=“java”;

boolean b1=s1==s2; //true

boolean b2=s2==s3 //false


String compare
● compareTo() method
○ Compares the values lexicographically and return an integer value
○ Suppose s1 and s2 are two string
■ s1==s2 return 0 if true
■ s1<s2 return –ve value if true
■ s1>s2 return +ve value if true
○ Example
String s1=“Java”;
String s2=“Java”;
String s3=“java”;
int i=s1.compareTo(s2); //0
int j=s1.compareTo(s3); //-ve
int k=s3.compareTo(s2); //+ve
String concatenation
● Using + operator

String s1=“Java”;

String s2=“Programming”;

String s3=s1+s2; //Java Programming

String s4=10+20+”Java”; //30Java

String s5=10+20+”Java”+10+20; //30Java1020


String concatenation

● Using concat() method

String s1=“Java”;

String s2=“Programming”;

String s3=s1.concat(s2); //Java Programming


Substring
● Retrieving the substring from a string
● Two methods

○ public String substring(int startIndex)

○ public String substring(int startIndex, int endIndex)

String s="hello";
System.out.println(s.substring(2)); //llo
System.out.println(s.substring(0,2)); //he
String class method
● toUpperCase() – change the case into uppercase
● toLowerCase() – change the case into lowercase
● trim() – elliminate white space before and after string
● startsWith(String) and endsWith(String)
String s1=“Hello”;
System.out.println(s1.startsWith(“H”); //true
System.out.println(s1.endsWith(“o”); //true
● charAt(index) – Character at the specified index (index-1)
● valueOf(value) – convert int, long, float, double, boolean, char and char array
into string
● replace(source, target) - replaces all occurrence of source sequence of
character with target sequence of character.
String methods
● contains(CharSequence) - searches the sequence of characters in this string,
returns boolean value, if available true else false
String s1=“Hello how are you”;
System.out.println(s1.contains(“how”)); //true
● getBytes() – returns byte array of the string
String s1="ABCDEFG";
byte[] barr=s1.getBytes();
System.out.println(barr); 65666768697071
● isEmpty() - checks if this string is empty or not. It returns true, if length of
string is 0 otherwise false
split() method

● splits the string against given regular expression and returns a char array
● Example
public class SplitExample{
public static void main(String args[]){
String s1=“this is the example for spilt string";
String[] words=s1.split(“\\s"); //splits the string based on whitespace
for(String w:words){
System.out.println(w);
}
}
}
indexOf() method
● returns index of given character value or substring
○ int indexOf(int ch)

■ returns index position for the given char value

○ int indexOf(int ch, int fromIndex)

■ returns index position for the given char value and from index

○ int indexOf(String substring)

■ returns index position for the given substring

○ int indexOf(String substring, int fromIndex)

■ returns index position for the given substring and from index

You might also like