[go: up one dir, main page]

0% found this document useful (0 votes)
8 views30 pages

OOP Through Java - UNIT-2

The document provides an overview of classes, methods, constructors, and strings in Java. It explains the concepts of classes and objects, the syntax for declaring classes, and the different ways to create objects. Additionally, it covers constructors, method overloading, parameter passing techniques, recursion, and nested classes, highlighting their usage and examples.

Uploaded by

revanthsrinu6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views30 pages

OOP Through Java - UNIT-2

The document provides an overview of classes, methods, constructors, and strings in Java. It explains the concepts of classes and objects, the syntax for declaring classes, and the different ways to create objects. Additionally, it covers constructors, method overloading, parameter passing techniques, recursion, and nested classes, highlighting their usage and examples.

Uploaded by

revanthsrinu6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Unit2: Classes, Methods, Constructors and Strings

Class
A class is a collection of member data and member functions (OR)
A class is a group of similar objects. It is a template or blueprint from which objects are
created.
A class in java can contain:
– member data
– member method/functions
– constructor
– block
– class and interface

Syntax to declare a class:


class <class_name>
{
Member data;
Member methods/functions;
}
Example:
class sample
{
int a,b;
String s1;
void display()
{
System.out.println(“display method”);
}
}

Object
An runtime entity that have state and behavior is called as object.
Ex: Chair, TV, table, pen, etc..
Characteristics of Object:
– State : represents the data of an object. (value)
– Behavior : represents the behavior of an object (Functionality)
– Identity: Object identity is typically implemented via a unique ID.
Example:
pen is an object
color is white etc., known as state,
Used for writing is its behavior,
name is Reynolds.

Object is instance of the class. Class is a template or blueprint from which objects are created.
Syntax of class:
class classname
{
type instance-variable1;
Page1
Unit2: Classes, Methods, Constructors and Strings
type instance-variable2;
//....
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}

type methodname2(parameter-list)
{

// body of method
}
// ...

type methodnameN(parameter-list)
{
// body of method
}
}

Program
public class sample
{
int x = 0;
int y = 0;

void display()
{
System.out.println(x+ " " + y);
}

public static void main(String args[])


{
Sample s1; // declaration
s1 = new sample(); // allocation of memory to an object
s1.x=10; //access data member using object.
s1.y=20;
s1.display(); // calling a member method
}
}

There are different ways to create an object in Java:

Page2
Unit2: Classes, Methods, Constructors and Strings

o Java new Operator


o Java Object.clone() method
o Anonymous object

1) Java new Operator

This is the most popular way to create an object in Java. A new operator is also followed by a call
to constructor which initializes the new object. While we create an object it occupies space in the
heap.

Syntax
class_name object_name = new class_name()

Program 1
public class A
{
String str="hello";
public static void main(String args[])
{
A a1=new A(); //creating object using new keyword
System.out.println(a1.str);
}
}

2) Clone method

3) Anonymous Object
Anonymous means nameless. An object that have no reference is known as anonymous object. If
you want to use the object only once, anonymous object is a good approach.

Program
class Calculation
{
void fact(int n)
{
int fact=1;
for(inti=1;i<=n;i++)
{
fact=fact*i;
}
Page3
Unit2: Classes, Methods, Constructors and Strings

System.out.println("factorial is"+fact);
}
public static void main(String args[])
{
new Calculation().fact(5);
}
}

Constructor
Constructor in java is a special type of method that is used to initialize the object automatically.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
– Constructor name must be same as its class name
– Constructor must have no explicit return type even void

Default Constructor
A constructor that have no parameter is known as default constructor.
Purpose:
– Default constructor provides the default values to the object like 0, null etc. depending on
the type.
Syntax of default constructor: <class_name>(){}

Program
class sample
{
int x;
int y;
sample() //constructor of class
{
x = 10;
y = 20;
}
void display()
{
System.out.println( x + " " + y);
Page4
Unit2: Classes, Methods, Constructors and Strings
}
}
class sampledemo
{
public static void main(String args[])
{
sample s1 = new sample(); // constructor will be call automatically from here
s1.display();
}
}

Parameterized Constructor
A constructor that have parameters is known as parameterized constructor.
Purpose:
– Parameterized constructor provides the values at runtime when the object is created
depending on the type.
Syntax of default constructor: <class_name>(datatype parameter1,….){}

Program
import java.util.Scanner;
class sample
{
int x,y;
sample(int a,int b) //constructor of class
{
x = a;
y = b;
}
void display()
{
System.out.println( x + " " + y);
}
}
class sampledemo
{
public static void main(String args[])
{
sample s1 = new sample(10,20); // constructor will be call automatically from here
s1.display();
}
}

This Keyword
In java, this is a reference variable that refers to the currently calling object.
Usage of java this keyword (4 usage of java this keyword)
– this keyword can be used to refer current class instance variable.

Page5
Unit2: Classes, Methods, Constructors and Strings
– this() can be used to invoke current class constructor.
– this keyword can be used to invoke current class method (implicitly)
– this can be passed as an argument in the method call.

this keyword can be used to refer current class instance variable.

class student
{
int id;
String name;
student(int id, String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
student s1 = new student(101, "srk");
student s2 = new student(102, "lbrce");
s1.display();
s2.display();
}
}

this() can be used to invoke current class constructor.

class Student{
int id;
String name;
Student()
{
System.out.println("default constructor is invoked");
}

Student(int id,String name)


{
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}

void display(){
Page6
Unit2: Classes, Methods, Constructors and Strings
System.out.println(id+" "+name);
}

public static void main(String args[]){


Student e1 = new Student(111,"kiran");
Student e2 = new Student(222,"Aryan");
e1.display();
e2.display();
}
}

this keyword can be used to invoke current class method (implicitly)

class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}

void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}

this can be passed as an argument in the method call.

class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}

Page7
Unit2: Classes, Methods, Constructors and Strings
Method Overloading
Class have multiple methods with same name but different parameters and definitions, it is
known as Method Overloading.
Advantage of method overloading
– It increases the readability of the program.
Different ways to overload the method:
– By Changing number of arguments
– By changing the data type

Program1
class Calculation
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}

Program2
class Calculation
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(double a, double b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Page8
Unit2: Classes, Methods, Constructors and Strings

p1.display();
}
}

Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.

Program
class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}

Page9
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Constructor Vs Method

Parameter Passing Techniques


The two most used and common mechanisms are pass by value and pass by reference
Pass by Value: In the pass by value concept, the method is called by passing a value. So, it is called pass
by value. In this formal parameters does not affect the actual parameters.
Program:
class cbr
{
int a,b;
void getdata(int x, int y)
{
a=x;
b=y;
}
void swap()
{
int t;
t=a;
a=b;
b=t;
}
public static void main(String args[])
{
cbr c1=new cbr();
c1.getdata(10,20);
System.out.println("Before Swapping ");
System.out.println(c1.a+" "+c1.b);
Page10
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
c1.swap();
System.out.println("After Swapping ");
System.out.println(c1.a+" "+c1.b);
}
}

Pass by Reference: In the pass by reference concept, the method is called using an alias or reference of the actual
parameter. So, it is called pass by reference. It forwards the unique identifier of the object to the method. In this
formal parameters will affect the actual parameters.
Program:
class cbr
{
int a,b;
void getdata(int x, int y)
{
a=x;
b=y;
}
void swap(cbr c1)
{
int t;
t=c1.a;
c1.a=c1.b;
c1.b=t;
}
public static void main(String args[])
{
cbr c1=new cbr();
c1.getdata(10,20);
System.out.println("Before Swapping ");
System.out.println(c1.a+" "+c1.b);
c1.swap(c1);
System.out.println("After Swapping ");
System.out.println(c1.a+" "+c1.b);
}
}

Returning objects from methods


Method can return an object in a similar manner as that of returning a variable of primitive types from
methods. When a method returns an object, the return type of the method is the name of the class to
which the object belongs and the normal return statement in the method is used to return the object.

Program
//Add two times and display information in proper time format
classTime
{
privateint hours,mins,secs;
Time()//Constructor with no parameter
Page11
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
{
hours = mins = secs =0;
}
Time(inthh,int m,intss)//Constructor with 3 parameters
{
hours =hh;
mins = m;
secs =ss;
}
Timeadd(Time tt2)
{
TimeTemp=newTime();
Temp.secs= secs + tt2.secs ;//add seconds
Temp.mins= mins + tt2.mins; //add minutes
Temp.hours= hours + tt2.hours;//add hours
if(Temp.secs>59) //seconds overflow check
{
Temp.secs=Temp.secs-60;//adjustment of minutes
Temp.hours++;//carry hour
}
returnTemp;

}
void display()
{
System.out.println(hours +" : "+ mins +" : "+ secs);
}
}
classReturningObjectsfromMethods
{
publicstaticvoid main(String[]args)
{

Time t1 =newTime(4,58,55);
Time t2 =newTime(3,20,10);
Time t3;
t3 = t1.add(t2);
System.out.print("Time after addition (hh:min:ss) ---->");
t3.display();
}
}

Recursion
Recursion is a process in which a method calls itself continuously. A method in java that calls itself is
called recursive method.

It makes the code compact but complex to understand.

Page12
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Syntax

returntype methodname(){
//code to be executed
methodname();//calling same method
}

Program

public class RecursionFactorial {


static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}

public static void main(String[] args) {


System.out.println("Factorial of 5 is: "+factorial(5));
}
}

Nested and Inner Classes in Java

Java inner class or nested class is a class that is declared inside the class or interface. (OR) class inside
a class or interface.

We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.

Additionally, it can access all the members of the outer class, including private data members and
methods.

Syntax

class Java_Outer_class{
//code
class Java_Inner_class{

Page13
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings

//code
}
}

Types of Nested Classes

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

o Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class

Member Inner Class


A non-static class that is created inside a class but outside a method is called member inner class. It is
also known as a regular inner class. It can be declared with access modifiers like public, default,
private, and protected.

Program
class outer{
private int data=30;
class inner{
void display(){
System.out.println("data is "+data);
}
}
public static void main(String args[]){
outer obj=new outer();
outer.inner in=obj.new inner();
in.display();
}
}
Output
Data is: 30

Page14
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings

Anonymous Inner Class

In simple words, a class that has no name is known as an anonymous inner class in Java. It should be
used if you have to override a method of class or interface. Java Anonymous inner class can be created in
two ways:

1. Class (may be abstract or concrete).


2. Interface

Program
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
}
}
Output
Nice fruits

Local Inner Class

A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are the inner
classes that are defined inside a block. Generally, this block is a method body. If you want to invoke the
methods of the local inner class, you must instantiate this class inside the method.

Program
public class A{
private int data=30;//instance variable
void display(){
class B{
void msg(){System.out.println(data);}

Page15
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings

}
B b1=new B();
b1.msg();
}
public static void main(String args[]){
A obj=new A();
obj.display();
}
}

Output
30

Static Keyword

• The static keyword is used in java mainly for memory management.


• Static keyword applied with Variables, methods and blocks. Static keyoword belongs to the class
than instance of the class.
• Static members are not a part of an object. These are part of a class.
• So we can access static members using Class name instead of object name.
• The static variable can be used to refer the common property of all object(it is not unique for each
object).
Advantage of Static variable
• It makes your program memory efficient (ie., it saves memory)

Program on static variable

class Student
Page16
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
{
int rollno;
String name;
static String college="ITS";
Student(int r, String n)
{
rollno = r;
name = n;
}
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Abinav");
Student s2 = new Student(222,"Harshitha");
s1.display();
s2.display();
}
}

Static Method

• A static method belongs to the class rather than object of a class.


• A static method can be invoked without the need for creating an instance of a class.
• Static method can access static data member and can change the value of it.

Program

class Student1
{
introllno;
String name;
static String college=“VITB";
static void change()
{
college = “VIT";
}

Student1(int r, String n)
{
rollno = r;
name = n;
}

Page17
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings

void display()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student1.change();
Student1 s1 = new Student1(111,"Abinav");
Student1 s2 = new Student1(222,"Harshitha");
Student1 s3 = new Student1(333,"Aadharsh");

s1.display();
s2.display();
s3.display();
}
}

Static Block
Static block is used to initialize the static data member.
It is executed before main method at the time of class loading

Static Inner (Nested) Class

A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access
non-static data members and methods. It can be accessed by outer class name.

o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members

Program1
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}

Page18
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Output
Data is 30

Java static nested class example with a static method

If you have the static member inside the static nested class, you don't need to create an instance of the
static nested class.

Program2
public class TestOuter2{
static int data=30;
static class Inner{
static void msg(){System.out.println("data is "+data);} }
public static void main(String args[]){
TestOuter2.Inner.msg();//no need to create the instance of static nested class
}
}

Output
Data is 30

Command-Line Arguments in Java

The java command-line argument is an argument i.e. passed at the time of running the java program.

The arguments passed from the console can be received in the java program and it can be used as an
input.

So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Program
class cmddemo{
public static void main(String args[]){
int n=args.length();
for(i=0;i<n;i++)
System.out.println("Your"+i+" first argument is: "+args[i]);
}
}

Output
Page19
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
C:\>javac cmddemo.java
C:\>java cmddemo this is lbrce
Your 0 argument is: this
Your 1 argument is: is
Your 2 argument is: lbrce

Final Keyword
• The final keyword in java is used to restrict the user.
• The final keyword can be used in many context. Final can be:
– variable,
– method
– Class
• The final keyword can be applied with the variables, that have no value it is called blank final
variable.
• It can be initialized in the constructor only.
• The blank final variable can be static also which will be initialized in the static block only.

Final Variable
• If you make any variable as final, you cannot change the value of the final variable(it will be
constant).

Program

class fvdemo
{
final int speedlimit=90;

void run()
{
speedlimit=400;
}

public static void main(String args[])


{
fvdemo obj=new fvdemo();
obj.run();
}
}

Output: Compile time error

Final Method
• If you make any method as final in super class, you cannot redefine it by its subclass.

Page20
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
class fmd
{
final void display()
{
System.out.println("Final method");
}
}
class fmddemo extends fmd
{
void display()
{
System.out.println("Final method");
}
public static void main(String args[])
{
fmddemo f1=new fmddemo();
f1.display();
}
}

Output: Compile time error

Final class
• If you make any class as final, that cannot be inherited.

final class fcd


{
final void display()
{
System.out.println("Final method");
}
}
class fcddemo extends fcd
{
void display()
{
System.out.println("Final method");
}
public static void main(String args[])
{
fmddemo f1=new fmddemo();
f1.display();
}
}

Output: Compile time error


Page21
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings

Access modifiers
in Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used with
the element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
5. Private protected

Access Location \ Public Protected default Private protected private


Access Specifier
Same class Yes Yes Yes Yes Yes
Sub class in same
Yes Yes Yes Yes No
package
Non subclass in
Yes Yes Yes No No
same package
Sub class in other
Yes Yes No Yes No
package
Non subclass in
Yes No No No No
other package

Note: Refer examples


Strings
String is a group of characters (OR) sequence of characters.
In JAVA language, string is implemented as object of type String.
String is a one of the pre defined class available in java.lang package.
To create a string object, String class provides several methods.
Some of the those are as follows:
1. By string literal
2. By new keyword

Examples:
String s1=”lbrce”;
String s2=new String(“Mylavaram”);
char x[]={‘a’, ’b’, ’c’, ’d’};
String s1=new String(x);

Reading a string as input from the keyboard


In order to read a string asinput from the keyboard, Scanner class provides two methods.
1.next()
2.nextLine()
next() method reads a string without white spaces.

Page22
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Example: String s1=new String();
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a string”);
s1=sc.next();

nextLine() method accepts a string with white spaces.


Example: String s1=new String();
Scanner sc=new Scanner(System.in);
System.out.println(“Enter a string”);
s1=sc.nextLine();

NOTE: String objects are immutable objects. That means, once a value is assigned to a string object it
cannot be modified.

String Handling Methods


Java language provides various String Handling methods to perform operations on strings.
1.int length(): This method returns number of characters available in a string.
Example:
String s1=new String(“LBRCE”);
int n=s1.length();

2.char charAt(int index): This method returns a character at a specified index value.
Example:
String s1=new String(“LBRCE”);
int n=s1.charAt(3);

3.char[] getChars(intstart,intend,char target[],inttargetindex): This method returns a group of characters


in a string starting from start and up to end-1.
Group of characters will be stored in array called as target.
target index represents the starting index in target array.
Example:
String s1=”LakireddyBaliReddy College of Engineering”;
int start=10, end=19;
char x[]=new char[end- start];
s1.getChars(start,end,x,0);
System.out.println(x);

4.boolean equals(String str): This method is used to check whether the two strings are identical or not.
This method returns true if strings are identical, otherwise returns false.
Example:
String s1=new String(“LBRCE”);
String s2=new String(“LBRCE”);
if(s1.equals(s2)) System.out.println(“equal”)
else System.out.println(“not equal”);

5.boolean equalsIgnoreCase(String str): This method is used to check whether the two strings are
identical or not by ignoring sensitive letters.

Page23
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Example
String s1=new String(“LBRCE”);
String s2=new String(“Lbrce”);
if(s1.equalsIgnoreCase(s2))
System.out.println(“equal”);
else System.out.println(“not equal”);

6.int indexOf(char ch): This method gives the index of first occurrence of given character in a string.
Example:
String s1=new String(“LakireddyBaliReddy College of Engineering”);
System.out.println(s1.indexOf(‘i’));

7.int lastIndexOf(char ch): This method returns the index of last occurrence of given character in a
string.
Example:
String s1=new String(“LakireddyBaliReddy College of Engineering”);
System.out.println(s1.lastIndexOf(‘i’)) ;

8.int indexOf(String str): This method returns the index of first occurrence of specified string in the
invoked string.
Example:
String s1=new String(“This is Java class”);
System.out.println(s1.indexOf(“is”));

9.int lastIndexOf(String str): This method returns the index of last occurrence of specified string in the
invoked string.
Example:
String s1=new String(“This is Java class”);
System.out.println(s1.indexOf(“is”));

10.boolean startsWith(String str): This method determines whether the invoking string starts with the
specified string or not.
This method returns true, if the invoking string starts with the specified string otherwise false.
Example:
String s1=new String(“This is Java class”);
System.out.println(s1.startsWith(“This”));

11.boolean endsWith(String str): This method determines whether the invoking string ends with the
specified string or not.
This method returns true, if the invoking string ends with the specified string otherwise false.
Example:
String s1=new String(“This is Java class”);
System.out.println(s1.endsWith(“Java”));

12.string substring(intstartindex): This method extracts a substring from the invoking string starting from
start index to till the end of the string.

Page24
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Example:
String s1=new String(“LakireddyBaliReddy College of Engineering”);
System.out.println(s1.substring(9));

13.string substring(intstartindex,intendindex): This method also extracts the substring from the invoking
string starting from start index to end index-1.
Example:
String s1=new String(“LakireddyBaliReddy College of Engineering”);
System.out.println(s1.substring(9,19));

14.int compareTo(string str): This method is used to compare two strings.This method returns integer
values such as positive or negative or zero value.
Return Value Meaning
<0 Invoking string is lesser than str
>0 Invoking string is greater than str
=0 Equal

Example:
String s1=”LBRCE”;
String s2=”Lbrce”;
System.out.println(s1.compareTo(s2));

15.int compareToIgnoreCase(String str): This method is used to compare the two strings by ignoring
case sensitive letters.
This method also gives integer values such as positive or negative or zero values.
Example:
String s1=”LBRCE”;
String s2=”Lbrce”;
System.out.println(s1.compareToIgnoreCase(s2));

16.string concat(String str): This method is used to concatenate the specified string with invoking string
and returns a string object.
Example:
String s1=”LBRCE”;
String s2=s1.concat(“college”);
System.out.println(s2);

17.string replace(char original,char replacement): This method is used to replace a character in a string
object with new character and returns a string object.
Example:
String s1=”hello”;
System.out.println(s1.replace(‘e’, ’a’));

18.string replace(string replace, string original): This method replaces a group of characters in a string
object with another group of characters and returns a string object.
Page25
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
Example:
String s1=”lbrCE”;
System.out.println(s1.replace(“lbr”, “LBR”));

19.string join(charSequence delimiter, charSequence String): This method concatenates two or more
strings with specified delimiter.
Example:
String s1=new String();
System.out.println(s1.join(“ ”, ”This”, “is”, “Java”, “class”));

20.string toLowerCase(): This method is used to convert all the characters in the given string into
lowercase letters.
Example:
String s1=new String(“LBRCE”);
System.out.println(s1.toLowerCase());

21.string toUpperCase(): This method is used to convert all the characters in the given string into
uppercase letters.
Example:
String s1=new String(“lbrce”);
System.out.println(s1.toUpperCase());

22.string trim(): This method is used to remove any leading or trailing white spaces in the string object.
Example:
String s1=new String(“ LBRCE “);
System.out.println(s1.trim());

StringBuffer Class
String objects are always fixed length and are immutable objects.
 In order to modify the string objects, we use StringBuffer class.
StringBuffer class provides string objects as growable and mutable objects.
StringBuffer class is one of the pre defined class in java.lang package.
StringBuffer class provides the following constructors.

1.StringBuffer(): This constructor is used to create StringBuffer object with capacity of 16 characters
without any reallocation.
Example:
StringBuffersb=new StringBuffer();

2.StringBuffer(int size): This constructor is used to create StringBuffer object with specified size as
capacity.
Example:
StringBuffersb=new StringBuffer(30);

3.StringBuffer(string str): This constructor is used to create StringBuffer object from string object and it
reserves 16 more characters without reallocation.
Example:
Page26
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
StringBuffersb=new StringBuffer(“hello”);

Methods
1.int length(): This method returns the length of the StringBuffer object.
Example:
StringBuffersb=new StringBuffer(“LBRCE”);
System.out.println(sb.length());

2.int capacity(): This method returns the capacity of the StringBuffer object.
Example:
StringBuffersb=new StringBuffer(“LBRCE”);
System.out.println(sb.capacity());

3.char charAt(int index): This method returns a character at a specified index value.
Example:
StringBuffersb=new StringBuffer(“Vishnu”);
int n=sb.charAt(5);

4.void getChars(intstartindex,intendindex,char target[],char targetstart)


Used to copy the characters from this sequence into a destination character array. The copied of
characters takes place from the index srcBegin to srcEnd-1 of this sequence. The copied subarray starts
from index dstBegin and ends at (dstBegin + (srcEnd - srcBegin) - 1).
Example:
char[] dst = new char[] {'s','t','r','i','n','g','b','u','f','f','e','r'};
StringBuffersb=new StringBuffer(“Java Program”);
System.out.println(sb.getChars(2,5,dst,2));

5.void setCharAt(intindex,charch) This method is used to set a new character at the specified index
value.
Example:
StringBuffersb=new StringBuffer(”hello”);
sb.setChar(1,’a’);
System.out.println(sb);

6.StringBuffer append(String str): This method is used to append the specified string to the invoking
StringBufferobject.
Example:
StringBuffersb=new StringBuffer(“Hello”);
sb.append(“ Java”);
System.out.println(sb);

7.StringBuffer append(intnum): This method appends string representation of integer type to the
StringBuffer object.
Example :
StringBuffersb=new StringBuffer(“hello”);
sb.append(123);
System.out.println(sb);

Page27
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings

8.StringBuffer insert(int index, char ch): This method is used to insert a character at the specified index
value.
Example:
StringBuffersb=new StringBuffer(“hello”);
sb.insert(1,’a’);
System.out.println(sb);

9.StringBuffer insert(int index, string str): This method is used to insert a string in StringBuffer at the
specified index value.
Example:
StringBuffersb=new StringBuffer(“I Java”);
sb.insert(2,”like”);
System.out.println(sb);

10.StringBuffer reverse(): This method reverses all the characters in the invoking StringBuffer object.
Example:
StringBuffersb=new StringBuffer(“hello”);
sb.reverse();
System.out.println(sb);

11.StringBuffer replace(intstartindex,intendindex,stringstr): This method replaces the characters from


startindex to endindex-1 with the specified str.
Example:
StringBuffersb=new StringBuffer(“This is test”);
sb.replace(5,7, ”was”);
System.out.println(sb);

12.StringBuffer delete(intstartindex, intendindex): This method deletes the characters from startindex to
endindex-1.
Example:
StringBuffersb=new StringBuffer(“hello JAVA”);
sb.delete(0,5); System.out.println(sb);

13.StringBuffer deleteCharAt(int index): This method deletes a single character available at the specified
index value.
Example: StringBuffersb=new StringBuffer(“hello JAVA”);
System.out.println(sb.deleteCharAt(4));

14.String substring(intstartindex): This method returns the subsequence from start index to end.
Example:
StringBuffersb=new StringBuffer(“stringbuffer”);
System.out.println(sb.substring(6));

15.String substring(intstartindex, intendindex): This method retirns the subsequence from start index to
end index exclusive.
Example:

Page28
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings
StringBuffersb=new StringBuffer(“Hello this is a java program”);
System.out.println(sb.substring(6,20));

Programs
1. Write a program to check whether the given string is palindrome or not.
//Program to check the string is palindrome or not
import java.util.*;
class Palindrome {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String s1=new String(); System.out.println(“Enter a string”);
s1=sc.next();
String s2=new String();
for(inti=s1.length()-1;i>=0;i--) {
s2=s2+s1.charAt(i);
}
if(s1.equals(s2))
System.out.println(“Given string is palindrome”);
else
System.out.println(“Given string is not a palindrome”);
}
}

2.Write a program for sorting a list of names in ascending order.


//Program for sorting a list of names in ascending order
import java.util.*;
class Sorting {
static String names[]={“ccc”,”eee”,”aaa”,”ddd”,”bbb”};
public static void main(String args[]) {
System.out.println(“Before Sorting strings are:”);
for(int i=0;i<n;i++)
System.out.println(names[i]);
int n=names.length();
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++)
if(s1[i].compareTo(s1[j])>0) {
String temp=s1[i];
s1[i]=s1[j];
s1[j]=temp;
}
}
}
System.out.println(“After Sorting strings are:”);
for(int i=0;i<n;i++)
System.out.println(names[i]);
}
}

Page29
Unit2: Classes, Inheritance, Polymorphism, Abstraction, Strings

Page30

You might also like