Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Oops Unit-2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

UNIT II

INHERITANCE AND INTERFACES

Inheritance – Super classes- sub classes –Protected members – constructors in sub


classes- the Object class – abstract classes and methods- final methods and
classes – Interfaces – defining an interface, implementing interface, differences
between classes and interfaces and extending interfaces - Object cloning -inner
classes, Array Lists – Strings
Contents
• Inheritance
– Super classes
– sub classes
– Protected members
– constructors in sub classes
• The Object class
• Abstract classes and methods
• Final methods and classes
• Interfaces
– defining an interface
– implementing interface
– differences between classes and interfaces
– extending interfaces
• Object cloning
• inner classes
• Array Lists
• Strings
CS8392 OBJECT ORIENTED PROGRAMMING 5
Inheritance
• Inheritance is one of the key features of Object-oriented
Programming that allows us to define a new class from
an existing class
• Syntax:
class Base-class-name
{
// Members definition
}
class Derived-class-name extends Base-class-name
{
// Members definition
}
CS8392 OBJECT ORIENTED PROGRAMMING 6
Types of Inheritance
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
• Hybrid Inheritance

CS8392 OBJECT ORIENTED PROGRAMMING 7


Types of Inheritance

CS8392 OBJECT ORIENTED PROGRAMMING 8


Inheritance
• Super classes

• Sub classes

• Protected members

• Constructors in sub classes

CS8392 OBJECT ORIENTED PROGRAMMING 9


Superclass and Subclass
• Superclass
– A class that is inherited is called a super class
– Base class is also called super class
• Subclass
– The class that does the inheriting is called a subclass
– Subclass is a specialized version of a superclass
– It inherits all of the instance variables and methods
defined by the superclass and adds its own, unique
elements
– A derived class is also called subclass

CS8392 OBJECT ORIENTED PROGRAMMING 10


Single Inheritance Example
//Single Inheritance Demo
class A
{
int a=10;
void showA()
{
System.out.println("This is a:"+a);
}
}
class B extends A
{
int b=20;
void showB()
{
a=40;
System.out.println("This is b:"+b); E:\javapgm>javac B.java
}
public static void main(String args[])
{
E:\javapgm>java B
B obj=new B(); This is a:20
obj.a=20; This is b:20
obj.showA(); This is a:40
obj.showB();
obj.showA();
} CS8392 OBJECT ORIENTED PROGRAMMING 11
}
CS8392 OBJECT ORIENTED PROGRAMMING 12
//Access Modifiers in Inheritance class AccessSpecifier
class Base {
{ public static void main(String args[])
private int a; {
protected int b; Derived1 obj=new Derived1();
public int c; obj.c=30;
Base() obj.sum();
{ }
a=10; }
}
void show()
{
System.out.println("Value of a is:"+a);
}
}
class Derived1 extends Base
{
Derived1()
{
b=20;
} E:\javapgm>java AccessSpecifier
void sum() b+c=50
{
System.out.println("b+c="+(b+c));
} CS8392 OBJECT ORIENTED PROGRAMMING 13
}
//Multilevel Inheritance class MultilevelDemo
class A {
{ public static void main(String args[])
void displayA() {
{ C c1=new C();
System.out.println("This is class A"); c1.displayA();
} c1.displayB();
} c1.displayC();
class B extends A }
{ }
void displayB()
{
System.out.println("This is class B");
}
}
class C extends B
{
void displayC()
{
System.out.println("This is class C");
} E:\javapgm>java MultilevelDemo
} This is class A
This is class B
This is class C
CS8392 OBJECT ORIENTED PROGRAMMING 14
//Hierarchical Inheritance class HierarchicalDemo
class A {
{ public static void main(String args[])
void displayA() {
{
System.out.println("This is class A"); B b1=new B();
} b1.displayA();
} b1.displayB();
class B extends A
{ C c1=new C();
void displayB() c1.displayA();
{ c1.displayC();
System.out.println("This is class B");
}
}
}
}
class C extends A
{
void displayC() E:\javapgm>java HierarchicalDemo
{
System.out.println("This is class C"); This is class A
} This is class B
} This is class A
This is class C

CS8392 OBJECT ORIENTED PROGRAMMING 15


Constructors in sub classes

• First, the Base/Super class constructor is


executed
• Then, the Derived/Sub class constructor is
executed

CS8392 OBJECT ORIENTED PROGRAMMING 16


Constructors in sub classes
class Base
{
Base()
{
System.out.println("This is base class constructor");
}
}
class Derived2 extends Base
{
Derived2()
{
System.out.println("This is derived class constructor");
}
public static void main(String args[])
{
Derived2 obj=new Derived2();
}
} E:\javapgm>java Derived2
CS8392 OBJECT ORIENTED PROGRAMMINGThisis base class constructor17
This is derived class constructor
super keyword
1. It can be used to access immediate parent class instance
variable
Syntax:
super.variable-name;
2. It can be used to invoke immediate parent class method
Syntax:
super.method-name();
3. It can be used to invoke immediate parent class constructor
Syntax:
super(arg-list);
CS8392 OBJECT ORIENTED PROGRAMMING 18
super keyword invokes base class
variable
class Base class Derived4 extends Base
{
{
int a;
int a; Derived4()
Base() {
{ a=20;
a=10; }
void display()
}
{
} System.out.println(“From Derived, a="+a);
System.out.println(“From Base, a="+super.a);
}
public static void main(String args[])
{
Derived4 d=new Derived4();
d.display();
}
}

E:\javapgm>java Derived4
From Derived, a=20
CS8392 OBJECT ORIENTED PROGRAMMING 19
From Base, a=10
super keyword invokes base class
method
class A class Derived5 extends B
{ {
void display() void display()
{ {
super.display();
System.out.println("This is class A");
System.out.println("This is class Derived5");
} }
} public static void main(String args[])
class B extends A {
{ Derived5 d=new Derived5();
d.display();
void display()
}
{ }
super.display();
System.out.println("This is class B");
}
}
E:\javapgm>java Derived5
This is class A
This is class B
CS8392 OBJECT ORIENTED PROGRAMMING 20
This is class Derived5
Super() Method
• It is used to invoke super or base class
constructor explicitly from derived class

• Note:
– If a subclass constructor does not explicitly
invoke a superclass constructor, the Java
compiler automatically inserts a call to the no-
argument constructor of the superclass.

CS8392 OBJECT ORIENTED PROGRAMMING 21


super() Method
class Base
{
int a;
Base()
{
System.out.println("This is Base class constructor");
}
Base(int x)
{
a=x;
System.out.println("This is Base class parameterized constructor");
System.out.println("The instance variable a is initialized with "+a);
}
}
class Derived3 extends Base
{
Derived3()
{
super(10);
System.out.println("This is derived class constructor");
}
public static void main(String args[])
{
Derived3 d=new Derived3();
}
}
E:\javapgm>java Derived3
This is Base class parameterized constructor
The instance variable a is initialized with10
CS8392 OBJECT ORIENTED PROGRAMMING 22
This is derived class constructor
Method Overriding
• When both base class and derived class are having
same method definition, then the derived class method
overrides its based class method.

• This is called method overriding

• Run-time polymorphism

E:\javapgm>javac Derived1.java

E:\javapgm>java Derived1
This is base class constructor
This is derived class constructor 23
CS8392 OBJECT ORIENTED PROGRAMMING
This is base class method
Method Overriding
//Method overriding
class Base
{
void display()
{
System.out.println("This is base class");
}
}
class Derived6 extends Base
{
void display()
{
System.out.println("This is derived class");
}
public static void main(String args[])
{
Derived6 d=new Derived6();
d.display();
} E:\javapgm>java Derived6
This is derived class
}
CS8392 OBJECT ORIENTED PROGRAMMING 24
ABSTRACT CLASSES AND
METHODS

CS8392 OBJECT ORIENTED PROGRAMMING 25


Abstract classes and Methods
• Any class that contains one or more abstract methods
must also be declared abstract is said to be an Abstract
Class
• To declare a class abstract, the abstract keyword is
used in front of the class keyword at the beginning of the
class declaration
• There can be no objects of an abstract class
• cannot declare abstract constructors, or abstract static
methods
• Any subclass of an abstract class must either implement
all of the abstract methods in the superclass

CS8392 OBJECT ORIENTED PROGRAMMING 26


Abstract classes and Methods
• There are situations in which to define a superclass that
declares the structure of a given abstraction without
providing a complete implementation of every method.

• a superclass that only defines a generalized form that


will be shared by all of its subclasses, leaving it to each
subclass to fill in the details

• Such a class determines the nature of the methods that


the subclasses must implement.

• Such methods be overridden by subclasses by


specifying the abstract
CS8392 OBJECTtype modifier
ORIENTED PROGRAMMING 27
Abstract classes and Methods
• Syntax:
abstract class class-name
{
abstract return-type method-name(arg-list)
{
//
}
//no abstract methods definition
}

CS8392 OBJECT ORIENTED PROGRAMMING 28


Example-01
// A Simple demonstration of abstract.
abstract class A class AbstractDemo
{ {
abstract void callme(); public static void main(String args[])
void callmetoo() {
B b = new B();
{
b.callme();
System.out.println("This is from class A"); b.callmetoo();
} }
} }
class B extends A
{
void callme()
{
System.out.println(“This is from class B"); E:\javapgm>java AbstractDemo
} This is from class B
} This is from class A

CS8392 OBJECT ORIENTED PROGRAMMING 29


Example-01 class Triangle extends Shape
{
abstract class Shape Triangle(double a, double b)
{ {
super(a, b);
double dim1;
}
double dim2; double area()
Shape(double a, double b) {
{ System.out.println("Inside Area for Triangle.");
dim1 = a; return dim1 * dim2 / 2;
}
dim2 = b;
}
} class AbstractAreas
abstract double area();//abstract method {
} public static void main(String args[])
class Rectangle extends Shape {
// Shape f = new Shape(10, 10); // illegal now
{
Rectangle r = new Rectangle(9, 5);
Rectangle(double a, double b) Triangle t = new Triangle(10, 8);
{ Shape sha1; // this is OK, no object is created
super(a, b); sha1 = r;
} System.out.println("Area is " + sha1.area());
sha1 = t;
double area()
System.out.println("Area is " + sha1.area());
{ }
System.out.println("Inside Area for Rectangle."); }
return dim1 * dim2; E:\javapgm>java AbstractAreas
} Inside Area for Rectangle.
Area is 45.0
}
CS8392 OBJECT ORIENTED PROGRAMMING Inside Area for Triangle. 30
Area is 40.0
FINAL METHODS AND
CLASSES

CS8392 OBJECT ORIENTED PROGRAMMING 31


Final methods
• A method which is declared using final keyword is called
final method
• It disallows a method from being overridden by
specifying final as a modifier at the start of its
declaration.
• So, Methods declared as final cannot be overridden

• since final methods cannot be overridden, a call to one


can be resolved at compile time. This is called early
binding.

“Prevents Method Overriding”


CS8392 OBJECT ORIENTED PROGRAMMING 32
Preventing Method Overriding
//final keyword prevents Method overriding
class Base
{
final void display()
{
System.out.println("This is base class");
}
}
class Derived6 extends Base
{
void display() // ERROR! Can't override.
{
System.out.println("This is derived class");
}
public static void main(String args[])
E:\javapgm>javac Derived6.java
{ Derived6.java:11: error: display() in Derived6
Derived6 d=new Derived6(); cannot override display() in Base
d.display(); void display()
^
} overridden method is final
CS8392 OBJECT ORIENTED PROGRAMMING 33
} 1 error
Final Classes
• A class which is declared using final keyword is called
final class
• It disallows a class from being inherited by specifying
final as a modifier at the start of its declaration
• So, Classes declared as final cannot be inherited

• Declaring a class as final implicitly declares all of its


methods as final, too

“Prevents Inheritance”
CS8392 OBJECT ORIENTED PROGRAMMING 34
Final Classes
final class A
{
// ...
}
// The following class is illegal.
// ERROR! Can't subclass A
class B extends A
{
// ...
}

CS8392 OBJECT ORIENTED PROGRAMMING 35


//final keyword prevents Inheritance
final class Base
{
void display()
{
System.out.println("This is base class");
}
}
class Derived7 extends Base
{
void display()
{
System.out.println("This is derived class");
}
public static void main(String args[])
{ E:\javapgm>javac Derived7.java
Derived7 d=new Derived7(); Derived7.java:9: error: cannot inherit
from final Base
d.display(); class Derived7 extends Base
} ^
CS8392 OBJECT ORIENTED PROGRAMMING 36
} 1 error
INTERFACE

CS8392 OBJECT ORIENTED PROGRAMMING 37


Interfaces
• Defining an interface
• Implementing interface
• Differences between classes and interfaces
• Extending interfaces

CS8392 OBJECT ORIENTED PROGRAMMING 38


Interfaces
Definition
• An interface is a group of related methods with empty
bodies(abstract methods)
• Interfaces form a contract between the class and the
outside world
• No object will be created for an interface.

CS8392 OBJECT ORIENTED PROGRAMMING 39


Interfaces Features
• Interfaces are syntactically similar to classes, but they
lack instance variables, and their methods are declared
without any body
• It specifies “what a class must do, but not how to do”
• Any number of classes can implement an interface
• One class can implement any number of interfaces
• A class which implements an interface must define the
complete set of methods defined by the interface
• Interfaces are designed to support dynamic method
resolution at run time

CS8392 OBJECT ORIENTED PROGRAMMING 40


Why and When to Use Interfaces?
• To achieve security
– hide certain details and only show the important
details of an object (interface)
• To support "multiple inheritance"
– a class can only inherit from one superclass
– But interface can inherit any number of classes
– because the class can implement multiple interfaces

CS8392 OBJECT ORIENTED PROGRAMMING 41


Defining an Interface
• An interface is defined much like a class.
• The general form:
access-specifier interface interface-name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
CS8392 OBJECT ORIENTED PROGRAMMING 42
Defining an Interface
• Variables can be declared inside of interface
declarations
• They are implicitly final and static, meaning they cannot
be changed by the implementing class.
• They must also be initialized
• All methods and variables are implicitly public
• Example:
interface Calculator
{
int add(int a, int b);
int mul(int a, int b);
int sub(int a, int b);
} CS8392 OBJECT ORIENTED PROGRAMMING 43
Implementing an Interface
• Once an interface has been defined, one or more classes
can implement that interface
• To implement an interface, include the implements clause
in a class definition, and then create the methods defined
by the interface
• General Form:

class classname [extends superclass] [implements interface


[,interface...]]
{
// class-body
}

CS8392 OBJECT ORIENTED PROGRAMMING 44


Implementing an Interface
• If a class implements two interfaces that declare the same
method, then the same method will be used by clients of
either interface
• The methods that implement an interface must be
declared public
• The type signature of the implementing method must
match exactly the type signature specified in the interface
definition

CS8392 OBJECT ORIENTED PROGRAMMING 45


Interface Example
interface Calculator
{ class InterfaceDemo
int add(int a, int b); {
int mul(int a, int b); public static void main(String args[])
int sub(int a, int b); {
Arithmetic ar=new Arithmetic();
}
System.out.println(ar.add(2,3));
class Arithmetic implements Calculator System.out.println(ar.mul(2,3));
{ System.out.println(ar.sub(3,1));
public int add(int a, int b) }
{ }
return(a+b);
}
public int mul(int a, int b)
{
return(a*b);
} E:\javapgm>java InterfaceDemo
5
public int sub(int a, int b)
6
{ 2
return(a-b);
}
CS8392 OBJECT ORIENTED PROGRAMMING 46
}
interface A
Multiple Inheritance using Interface
{
void displayA();
}
interface B
{
class MultipleInheritance
void displayB();
{
} public static void main(String args[])
class C implements A,B {
{ C c1=new C();
public void displayA() c1.displayA();
c1.displayB();
{
c1.displayC();
System.out.println("This is displayA method"); }
} }
public void displayB()
{
System.out.println("This is displayB method");
} E:\javapgm>javac
MultipleInheritance.java
void displayC()
{ E:\javapgm>java MultipleInheritance
System.out.println("This is displayC method"); This is displayA method
} This is displayB method
CS8392 OBJECT ORIENTED PROGRAMMING
This is displayC method 47
}
Differences between classes and interfaces
Sr.
Key Class Interface
No.
Interface can have only abstract
A class can have both an abstract as well
1 Supported Methods methods. Java 8 onwards, it can have
as concrete methods.
default as well as static methods.

2 Multiple Inheritance Multiple Inheritance is not supported. Interface supports Multiple Inheritance.

final, non-final, static and non-static Only static and final variables are
3 Supported Variables
variables supported. permitted.

Interface can not implement an interface,


4 Implementation A class can implement an interface.
it can extend an interface.

Interface is declared using interface


5 Keyword A class is declared using class keyword.
keyword

A class can inherit another class using


6 Inheritance extends keyword and implement an Interface can inherit only an interface.
interface.

A class can have any type of members


7 Access Interface can only have public members.
like private, public.

8 Constructor A class can have constructor methods. Interface can not have a constructor.

CS8392 OBJECT ORIENTED PROGRAMMING 48


Extending interfaces
• One interface can inherit another by use of the keyword
extends
• The syntax is the same as for inheriting classes
interface interface-1
{
//
}
interface interface-2 extends interface-1
{
//
}
CS8392 OBJECT ORIENTED PROGRAMMING 49
Extending Interface Example
interface A
{ public void method3()
void method1(); {
void method2(); System.out.println("Implement method3().");
} }
}
interface B extends A
class InterfaceDemo
{ {
void method3(); public static void main(String args[])
} {
class MyClass implements B Arithmetic ar=new Arithmetic();
System.out.println(ar.add(2,3));
{
System.out.println(ar.mul(2,3));
public void method1() System.out.println(ar.sub(3,1));
{ }
System.out.println("Implement method1()."); }
}
public void method2() E:\javapgm>java ExtendInterface
Implement meth1().
{
Implement meth2().
System.out.println("Implement method2()."); Implement meth3().
}

CS8392 OBJECT ORIENTED PROGRAMMING 50


The Object class
• Object is a superclass of all other classes

• This means that a reference variable of type Object can


refer to an object of any other class.

• Class Object is the root of the class hierarchy

• Every class has Object as a superclass.

• All objects, including arrays, implement the methods of


this class

CS8392 OBJECT ORIENTED PROGRAMMING 51


Methods of the Object class

CS8392 OBJECT ORIENTED PROGRAMMING 52


getClass()
class GetClassDemo
{
public static void main(String args[])
{
Integer i=new Integer(10);
System.out.println(i.getClass());
}
}

E:\javapgm>java GetClassDemo
class java.lang.Integer

CS8392 OBJECT ORIENTED PROGRAMMING 53


hashCode()
class HashCodeDemo
{
public static void main(String args[])
{
String str=new String("Welcome");
System.out.println(str.hashCode());
}
}
E:\javapgm>java HashCodeDemo
-1397214398

CS8392 OBJECT ORIENTED PROGRAMMING 54


toString()
class Student class ObjectDemo
{
{
public static void main(String args[])
static int last_roll; {
int roll_no; Object ob=new Object();
Student() Student s = new Student();
{ ob=s;
System.out.println(ob);
roll_no = last_roll;
System.out.println(s.toString());
last_roll++; System.out.println(s.hashCode());
} Class c=s.getClass();
/*@Override System.out.println(c);
public int hashCode()
}
{
}
return roll_no;
} */ E:\javapgm>java ObjectDemo
} Student@15db9742
Student@15db9742
366712642
CS8392 OBJECT ORIENTED PROGRAMMING 55
class Student
Object cloning
• Object cloning in Java is the process of creating an exact
copy of the original object

• It is a way of creating a new object by copying all the


data and attributes from the original object.

• Steps:

– implement Cloneable interface

– override clone() method from Object class

– Invoke clone() method

CS8392 OBJECT ORIENTED PROGRAMMING 56


class Student2 implements Cloneable
{
int rollno;
String name;
Student2(int rollno,String name)
{
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException
{
return super.clone();
}
public static void main(String args[])
{
try
{
Student2 s1=new Student2(101,"Raja");
Student2 s2=(Student2)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException c)
{} E:\javapgm>java Student2
} 101 Raja
CS8392 OBJECT ORIENTED PROGRAMMING 57
} 101 Raja
Inner Classes
• A class within another class is called inner class
• It has access to all of the variables and methods of its
outer class
• An instance of Inner can be created only within the
scope of class Outer
// Demonstration of an inner class
class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner
{
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test(); E:\javapgm>javac InnerClassDemo.java
}
}
E:\javapgm>java InnerClassDemo
display: outer_x = 100
Drawbacks of Arrays
• Once the size of an array is declared, it's
hard to change it
• It is hard to add or remove elements
to/from an array

CS8392 OBJECT ORIENTED PROGRAMMING 60


Array Lists
• The ArrayList class present in the java.util package
allows us to create resizable arrays
• Unlike arrays, ArrayList can automatically adjust its
capacity when we add or remove elements from it.
• Hence, array lists are also known as dynamic arrays.
• Creating an ArrayList:
ArrayList<Type> arrayList= new ArrayList<>();
Example:
// create Integer type arraylist
ArrayList<Integer> arrayList = new ArrayList<>();

// create String type arraylist


ArrayList<String> arrayList = new ArrayList<>();
CS8392 OBJECT ORIENTED PROGRAMMING 61
Operations on ArrayList
• Add Elements • Remove ArrayList Elements
– add(value) – remove()
– add(index, value) – removeAll()
– addAll() – clear()
– Arrays.asList() • Sort Elements of an ArrayList
• Access ArrayList Elements – Collections.sort()
– get()
– Iterator.iterator()
• Modify ArrayList Elements
– set()

CS8392 OBJECT ORIENTED PROGRAMMING 62


//Adding elements
import java.util.ArrayList;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.add(2,"Honda");
System.out.println(cars);
ArrayList<String> newcars = new ArrayList<>();
newcars.add("Baleno");
newcars.addAll(cars);
System.out.println(newcars);
}
}

CS8392 OBJECT ORIENTED PROGRAMMING 63


// Initialize an ArrayList Using asList()
import java.util.ArrayList;
import java.util.Arrays;
class ArrayList1
{
public static void main(String[] args)
{
// Creating an array list
ArrayList<String> animals = new ArrayList<>(Arrays.asList("Cat", "Cow", "Dog"));
System.out.println("ArrayList: " + animals);
// Access elements of the array list
String element = animals.get(1);
System.out.println("Accessed Element: " + element);
}
}

CS8392 OBJECT ORIENTED PROGRAMMING 64


//Accessing Elements using get() and iterator()
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo1
{
public static void main(String[] args)
{
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
System.out.println(“Elements at 2”+cars.get(2));
Iterator<String> iterate = cars.iterator();
while(iterate.hasNext())
{
System.out.print(iterate.next());
}
} E:\javapgm>java ArrayListDemo1
} Element at 2:Ford
Element in ArrayList
Note: Volvo
hasNext() returns true if there is a next element in the array list. BMW 65
next() returns the next element in the array list* Ford
//Modifying Elements
import java.util.ArrayList;
public class ArrayListModify
{
public static void main(String[] args)
{
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
System.out.println("Before Change:"+cars);
cars.set(1,"Honda");
System.out.println("After Change:"+cars);
}
}

E:\javapgm>java ArrayListModify
Before Change:[Volvo, BMW, Ford]
66
After Change:[Volvo, Honda, Ford]
//Removing Elements using remove() and removeAll()
import java.util.ArrayList;
public class ArrayListRemove
{
public static void main(String[] args)
{
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
System.out.println("Before Remove:"+cars);
cars.remove(1);
System.out.println("After Remove:"+cars);
cars.removeAll(cars);
System.out.println("After RemoveAll:"+cars);
}
}
E:\javapgm>java ArrayListRemove
Before Remove:[Volvo, BMW, Ford]
After Remove:[Volvo, Ford]
67
After RemoveAll:[]
//Sorting Elements
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListSort
{
public static void main(String[] args)
{
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
System.out.println("Before Sorting:"+cars);
Collections.sort(cars);
System.out.println("After Sorting:"+cars);
}
}
E:\javapgm>java ArrayListSort
Before Sorting:[Volvo, BMW, Ford] 68
After Sorting:[BMW, Ford, Volvo]
//Length of ArrayList
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListSize
{
public static void main(String[] args)
{
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
System.out.println("Length of ArrayList:"+cars.size());
}
}

E:\javapgm>java ArrayListSize
Size of ArrayList:3 69
Converting ArrayList
import java.util.ArrayList;
import java.util.Arrays;
class ArrayListConvert
{
public static void main(String args[])
{
String[] names={"raja","kumar","senthil"};
ArrayList<String> names1=new ArrayList<>(Arrays.asList(names));
System.out.println("Elements of ArrayList:"+names1);
String names2=names1.toString();
System.out.println("Elements of String:"+names2);
}
} E:\javapgm>java ArrayListConvert
Elements of ArrayList:[raja, kumar, senthil]
Elements of String:[raja, kumar, senthil]
CS8392 OBJECT ORIENTED PROGRAMMING 70
Difference between Arrays and ArrayList
Arrays ArrayList
Array is static in size. ArrayList is dynamic in size.
ArrayList is a variable-length data
An array is a fixed-length data
structure. It can be resized itself when
structure.
needed.
It is mandatory to provide the size of
We can create an instance of ArrayList
an array while initializing it directly or
without specifying its size
indirectly.
We cannot store primitive type in
An array can store
ArrayList. It automatically converts
both objects and primitives type.
primitive type to object.
Array provides a length variable which ArrayList provides the size() method to
denotes the length of an array. determine the size of ArrayList.

Array can be multi-dimensional. ArrayList is always single-dimensional.

CS8392 OBJECT ORIENTED PROGRAMMING 71


Strings
• In java, a string is an object that represents a sequence
of characters
• The java.lang.String class is used to create string object
• There are two ways to create a String object:
1. By string literal :
Java String literal is created by using double quotes.
Example:
String s=“Welcome”;
2. By new keyword :
Java String is created by using a keyword “new”.
Example:
String s=new String(“Welcome”);
• Strings are immutable(constants)

CS8392 OBJECT ORIENTED PROGRAMMING 72


Java String Methods
1. length() 11. endsWith()
2. compareTo() 12. split()
3. concat() 13. indexOf()
4. isEmpty()
5. trim()
6. toLowerCase() and toUpperCase()
7. replace()
8. contains()
9. equals() and equalsIgnoreCase()
10. substring()

CS8392 OBJECT ORIENTED PROGRAMMING 73


//1. length() method demo
class StringLength
{
public static void main(String args[])
{
String s1="Java";
String s2=new String("Programming“);
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}

E:\javapgm>java StringLength
string length is: 4
string length is: 11

CS8392 OBJECT ORIENTED PROGRAMMING 74


//2. compareTo function Demo
class StringCompare
{
public static void main(String args[])
{
String s1="Java";
String s2=new String("Programming“);
System.out.println("Result of Comparison: "+s1.compareTo(s2));
}
}

E:\javapgm>java StringCompare
Result of Comparison: -6

if s1 > s2, it returns a positive number


if s1 < s2, it returns a negative number
if s1 == s2, it returns 0
CS8392 OBJECT ORIENTED PROGRAMMING 75
//3. concat() method demo
class StringConcat
{
public static void main(String args[])
{
String s1="Java";
String s2=new String(" Programming");
System.out.println("After of Concatenation: "+s1.concat(s2));
}
}

E:\javapgm>java StringConcat
After of Concatenation: Java Programming

CS8392 OBJECT ORIENTED PROGRAMMING 76


//4. isEmpty() method demo
class StringTrim
{
public static void main(String args[])
{
String s1=“Java";
String s2=new String(“ Programming");
System.out.println(s1+s2);
}
}

E:\javapgm>java StringEmpty
Result of empty check on S1: true
Result of empty check on S2: false

CS8392 OBJECT ORIENTED PROGRAMMING 77


//5. trim() method demo
class StringTrim
{
public static void main(String args[])
{
String s1="Java";
String s2=new String(" Programming");
System.out.println("Without trim:"+s1+s2);
System.out.println("With trim:"+s1+s2.trim());
}
}

E:\javapgm>java StringTrim
Without trim:Java Programming
With trim:JavaProgramming

CS8392 OBJECT ORIENTED PROGRAMMING 78


//6. toLowerCase() and toUpperCase() methods demo
class StringLowerUpper
{
public static void main(String args[])
{
String s1="JAVA";
String s2=new String("Programming");
System.out.println(s1.toLowerCase());
System.out.println(s2.toUpperCase());
}
}

E:\javapgm>java StringLowerUpper
java
PROGRAMMING

CS8392 OBJECT ORIENTED PROGRAMMING 79


//7. equals() and equalsIgnoreCase() methods demo
class StringEqual
{
public static void main(String args[])
{
String s1="JAVA";
String s2="Java";
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
}
}

E:\javapgm>java StringEqual
false
true

CS8392 OBJECT ORIENTED PROGRAMMING 80


//8. contains() method demo
class StringContains
{
public static void main(String args[])
{
String s1="Java Programming";
System.out.println(s1.contains("Java"));
System.out.println(s1.contains(“java"));
}
}

E:\javapgm>java StringContains
true
false

CS8392 OBJECT ORIENTED PROGRAMMING 81


//9. replace() method demo
class StringReplace
{
public static void main(String args[])
{
String s1="Java Programming";

//Replacing String
String s2=s1.replace("Java","Python");

//Replacing character
String s3=s2.replace("P","p");
System.out.println(s3);
}
}
E:\javapgm>java StringReplace
python programming
CS8392 OBJECT ORIENTED PROGRAMMING 82
//10. substring(int beginIndex, int endIndex)
//return a substring from beginIndex to endIndex-1 position
class SubString
{
public static void main(String args[])
{
String s1="Programming";
System.out.println(s1.substring(0,4));
}
}

E:\javapgm>java SubString
Prog

CS8392 OBJECT ORIENTED PROGRAMMING 83


//11. endsWith() method demo
class StringEndsWith
{
public static void main(String args[])
{
String s1="Programming";
System.out.println(s1.endsWith("ing"));
}
}

E:\javapgm>java StringEndsWith
true

CS8392 OBJECT ORIENTED PROGRAMMING 84


//split() method demo
class StringSplit
{
public static void main(String args[])
{
String s1="Java is a Platform Independent Language";
String[] s2=s1.split(" ");
for(String str:s2)
{
System.out.println(str);
}
}
} E:\javapgm>java StringSplit
Java
is
a
Platform
Independent
CS8392 OBJECT ORIENTED PROGRAMMING 85
Language
//indexOf() method demo
class StringIndexof
{
public static void main(String args[])
{
String s1="Java is a Platform Independent Language";
System.out.println(s1.indexOf("Platform"));
}
}

E:\javapgm>java StringIndexof
10

CS8392 OBJECT ORIENTED PROGRAMMING 86

You might also like