0% found this document useful (0 votes)
32 views39 pages

Java Object-Oriented Programming Basics

java

Uploaded by

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

Java Object-Oriented Programming Basics

java

Uploaded by

rashmiprasad217
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PCA25C01J - Object Oriented Programming Using Java

UNIT II: Introducing Classes - Class fundamentals - Declaring Objects - Assigning


object reference variables- Method – Constructors – Characteristics of Constructors
-Types of Constructors - this Keyword - Introduction to Garbage Collection - Using
Class
Finalize() method - Overloading methods - Overloading Constructors - Using
objects as parameters - Argument Passing - Returning Objects - Recursion –
Introducing Access Control - Understanding static variables and methods-
Understanding final variables and methods – Working with Nested Class –
Understanding Inner Class - Introduction to String Class – Working with String
Handling Methods.

Class Fundamentals
In Java, everything is encapsulated under classes. Class can be defined as a template/blueprint
that describes the behaviors/states of a particular entity. A class defines new data type. Once
defined, this new type can be used to create object of that type. Object is an instance of class.
You may also call it as physical existence of a logical template class.
A class is declared using class keyword. A class contains both data and code that operate on that
data. The data or variables defined within a class are called instance variables and the code that
operated on this data is known as methods.
The General Form of a Class
class classname [ extends baseclass implements interface1, interface2 ]
{
type instance-variable1;
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
}
}
Rules for Java Class
 A Class can have only public or default(no modifier) access specifier.
 It must have the class keyword, and class must be followed by a legal identifier.
 It may optionally extend one parent class. By default, it will extend [Link]
 It may optionally implement any number of comma-separated interfaces.
 The class’s variables and methods are declared within a set of curly braces {}
 Each .java source file may contain only one public class.
 Finally the source file name must match the public class name and it must have a .java
suffix.
Objects
Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
There are three steps when creating an object from a class:
 Declaration: A variable declaration with a variable name and object type.
 Instantiation: The 'new' key word is used to create the object.
 Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
The general syntax for declaring object
classname ref_var;
ref_var = new classname ( );
Here, ref_var is a variable of the class type being created. The classname is the name of the class
that is being instantiated. After the first line executes, ref_var contains the value null, which
indicates that it does not yet point to an actual object. The next line allocates an actual object and
assigns a reference to it to ref_var.
The new operator dynamically allocates memory for an object. The class name followed by
parentheses specifies the constructer for the class. A constructer defines what occurs when an
object of a class is created.
Assigning object reference variables
When you assign one object reference variable to another object reference variable, you are not
creating a copy of the object; you are only making a copy of the reference.

Methods
• A method is a collection of statements that are grouped together to perform an operation.
• A method is a block of code which only runs when it is called.
The general form of a method is
type methodname (parameter-list) {
// body of method
}
Every method should specify the type of data to be returned. This can be any valid type,
including class types that you create. If the method does not return a value, its return type must
be void. The name of the method can be any valid identifier. The parameter-list is a sequence of
type and identifier pairs separated by commas. Parameters are variables that receive the value of
the arguments passed to the method when it is called.

Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:
return value;
Accessing Instance Variables and Methods:
Instance variables and methods are accessed via created objects. To access an instance variable
the fully qualified path should be as follows:
/* First create an object */
ObjectReference = new Constructor ();
/* Now call a variable as follows */
[Link];
/* Now you can call a class method as follows */
[Link]()
Example1
class Pencil
{
private String color = "red";

public void setColor (String newColor) {


color = newColor;
}
public String getColor(){
return color;
}
public static void main(String[] args)
{
Pencil p = new Pencil(); //Object creation
[Link]("red");
[Link]("Pencil color is "+[Link]());
}
}
Example2
package javalab;
import [Link].*;
public class Circle
{
double radius;
void setRadius(double r)
{
radius=r;
}
double displayArea()
{
return [Link]*radius*radius;
}
double displayPeri()
{
return 2*[Link]*radius;
}
public static void main(String [] args)
{
Scanner in=new Scanner([Link]);
double r;
[Link]("Enter Radius: ");
r=[Link]();
Circle obj=new Circle ();
[Link](r);
[Link]("Area of Circle: "+[Link]());
[Link]("Perimeter of Circle:"+[Link]());
}
}
Constructors
 A constructor is a special method that is used to initialize an object upon creation.
 Constructors have the same name as class name in which it resides.
 They have zero or more parameters.
Characteristics of Constructors
 Constructors cannot be private.
 Constructor in java cannot be abstract, static, final or synchronized. These modifiers are
not allowed for constructors.
 Constructors cannot be inherited.
 Constructors are automatically called when an object is created.
 A constructor does not have any return type, not even void.
 Constructors can be overloaded. (i.e) A class can have more than one constructors
 Every class has a constructor. If you don’t explicitly declare a constructor for a java class,
the compiler builds a default constructor for that class.
Types of Constructors
 Default constructor - Constructor with no argument is called default constructor.
Example1
class Point
{
int x, y;
Point( ){ //Default Constructor
x = y = 0;
}

}
Example2
class NoteBook
{
/*This is default constructor. A constructor does
not have a return type and it's name
should exactly match with class name */
NoteBook(){
[Link]("Default constructor");
}
public void mymethod()
{
[Link]("Void method of the class");
}
public static void main(String args[]){
/* new keyword creates the object of the class
and invokes constructor to initialize object*/
NoteBook obj = new NoteBook();
[Link]();
}
}
Output
Default constructor
Void method of the class

 Parameterized Constructors - Constructor with parameter is called parameterized


constructor.
Example
class Point
{
int x, y;
Point(int i,int j){ //Parameterized Constructor
x = i;
y = j;
}

}
Example2
class Student{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){[Link](id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student s1 = new Student(101,"Kavya");
Student s2 = new Student(102,"Surya");
//calling method to display the values of object
[Link]();
[Link]();
}
}
Output
101 Kavya
102 Surya

Overloading Constructors
Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated
on the basis of their type of parameters or number of parameters. Constructor overloading is not
much different than method overloading.
Example
class Point
{
private int x,y;
Point() //default constructor
{
x = y = 0;
}
Point(int i, int j) //parameterized constructor with 2 argument
{
x = i;
y = j;
}
public void display()
{
[Link](x+" , "+y);
}
public static void main(String[] args)
{
Point p1 = new Point();
Point p2 = new Point(10,20);
[Link]();
[Link]();
}
}
Output
0, 0
10, 20
this keyword
this keyword in java can be used inside any method to refer to the current object. (i.e.) ‘this’ is
always a reference to the object on which the method was invoked.
Instance variable hiding
When a local variable has the same name as an instance variable, the local variable hides the
instance variable. As the keyword ‘this’ lets you refer directly to the object, you can use it to
resolve any name space collisions that might occur between instance variables and local
variables.
Usage of this keyword

 ‘this’ can be used to refer current class instance variable.


 It can be used to invoke current class method (implicitly)
 It can be used to invoke current class constructor.
 It can be passed as an argument in the method call.
 It can be passed as argument in the constructor call.
 It can be used to return the current class instance from the method.
Example1
class Point
{
int x, y;
Point(int x,int y)
{
this.x = x; //this.x refers to instance variable x
this.y = y;
}

}
Example2
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(101,"Raj",8000f);
Student s2=new Student(102,"Sundar",7000f);
[Link]();
[Link]();
}
}
Output
101 Raj 8000
102 Sundar 7000

Introduction to Garbage Collection


In Java, destruction of object from memory is done automatically by the JVM. When there is no
reference to an object then that object is assumed to be no longer needed and memory occupied
by the object is released. This technique is known as Garbage Collection.
Advantage of Garbage Collection
 Programmer doesn’t need to worry about dereferencing an object
 Increases Memory efficiency and decreases the chance of memory leak
 It is done automatically by JVM
There are many ways to deference an object:
 By nulling the reference
 By assigning a reference to another
 By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes.
public static void gc(){}
Example
public class TestGarbage1{
public void finalize(){[Link]("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
[Link]();
}
}
Output
object is garbage collected
object is garbage collected

Using finalize() Method


Sometimes an object will need to perform some clean up task (such as closing an open
connection or releasing any resources held) before it is destroyed. By using finalization, we can
define specific actions to occur, just before it is garbage collected.
To add a finalizer to a class, simply define finalize() method as follow
protected void finalize()
{
//code
}
Example
public class JavafinalizeExample {
public static void main(String[] args)
{
JavafinalizeExample obj = new JavafinalizeExample();
[Link]([Link]());
obj = null;
// calling garbage collector
[Link]();
[Link]("end of garbage collection");
}
protected void finalize()
{
[Link]("finalize method called");
}
}

Output
2018699554
end of garbage collection
finalize method called

Overloading Methods
If two or more method in a class has same name but different parameter list, it is known as
method overloading. Java implements static polymorphism using method overloading. Method
overloading can be done by changing number of argument or by changing the data type of
argument. If two or more methods have same name and same parameter list, but differs in return
type are not said to be overloaded method.
When an overloaded method is called, java look for match between the arguments to call the
method and method’s parameters. This match need not always be exact. Sometimes when exact
match is not found, Java automatic type conversion plays a vital role.
Example
class Calculate
{
public void sum(int a, int b){
[Link]("Sum = "+(a+b));
}
public void sum(double a, double b){
[Link]("Sum = "+(a+b));
}
public void sum(int a, int b, int c){
[Link]("Sum = "+(a+b+c));
}
public static void main(String[] args){
Calculate c = new Calculate();
[Link](3,4); //sum(int a, int b) is called
[Link](1,2,3); //sum(int a, int b, int c) is called
[Link](10.23,23.3); // sum(double a, double b) is called
}
}
Output
Sum = 7
Sum = 6
Sum = 33.53
Using Objects as Parameters
In Java, objects can be passed as parameters to methods, just like primitive data types. When an
object is passed as a parameter, the reference to the object is passed, not the actual object itself.
This means that changes made to the object inside the method will affect the original object.
Example: Passing Objects as Parameters
class Person {
String name;
// Constructor
Person(String name) {
[Link] = name;
}

// Method to modify the name


void changeName(String newName) {
[Link] = newName;
}
}

public class Main {


public static void modifyPerson(Person p) {
[Link]("John Doe"); // Modifies the original object
}

public static void main(String[] args) {


Person person = new Person("Alice");
[Link]("Before modification: " + [Link]);
modifyPerson(person); // Passing object as parameter
[Link]("After modification: " + [Link]);
}
}

Output:
Copy codeBefore modification: Alice
After modification: John Doe

Argument Passing
There are two ways that java can pass an argument to a method.
 Call by value
 This method copies the value of an argument into formal parameter of the method.
Changes made to the parameter of the method have no effect on the argument used to
call it.
 In Java, when you pass a simple type to a method, it is passed by value.
 Call by Reference
 In this method, a reference to an argument (not the value of the argument) is passed to
the parameter. Changes made to the parameter will affect the argument used to call
the method.
 In java, objects are always passed by reference.

Example
Call by value
public class SwapByValue {
public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
[Link]("After swap method: a = " + a + ", b = " + b);
}
public static void main(String[] args) {
int a = 5;
int b = 10;
[Link]("Before swap: a = " + a + ", b = " + b);
swap(a, b);

}
}
OUTPUT

Before swap: a = 5, b = 10
After swap method: a = 10, b = 5

Call by reference

class Number {
int value;

Number(int value) {
[Link] = value;
}
}

public class SwapByReference {


public static void swap(Number a, Number b) {
int temp = [Link];
[Link] = [Link];
[Link] = temp;
}

public static void main(String[] args) {


Number a = new Number(5);
Number b = new Number(10);
[Link]("Before swap: a = " + [Link] + ", b = " + [Link]);
swap(a, b);
[Link]("After swap: a = " + [Link] + ", b = " + [Link]);
}
}
OUTPUT

Before swap: a = 5, b = 10
After swap: a = 10, b = 5
Returning Objects
A method can have any type of data, including class types that you create, as argument and can
return any type including objects.
Example
public class Point {
int x,y;
Point()
{
x = y = 0;
}
Point(int i,int j)
{
x = i;
y = j;
}
static Point addPoint(Point p1, Point p2 ) //Object as argument and return value
{
Point p3 = new Point();
p3.x = p1.x+p2.x;
p3.y = p1.y+p2.y;
return p3;
}
void display()
{
[Link](x+" , "+y);
}
public static void main(String[] args)
{
Point p1 = new Point(10,20);
Point p2 = new Point(1,2);
Point p3 = addPoint(p1, p2);
[Link]();
[Link]();
[Link]();

}
}
Output
10 , 20
1,2
11 , 22

Recursion
Recursion is the process of defining something in terms of itself. In java programming, recursion
is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.
Example
public class FactNo {
static int Fact(int n) //Recursive Function
{
if(n <=1)
return 1;
else
return n*Fact(n-1);
}
public static void main(String[] args)
{
[Link](Fact(5));
}
}
Output
120
Introducing Access Control
We can control the access level for class member variables and methods through access
specifiers.
The four access levels are:
Visible to the package. No modifiers are needed.
Visible to the class only- private.
Visible to the world- public.
Visible to the package and all subclasses- protected.
Default Access Modifier - No keyword: Default access modifier means we do not explicitly
declare an access modifier for a class, field, method, etc. A variable or method declared without
any access control modifier is available to any other class in the same package. The fields in an
interface are implicitly public static final and the methods in an interface are by default public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

Private Access Modifier - private: Methods, Variables and Constructors that are declared
private can only be accessed within the declared class itself. Private access modifier is the most
restrictive access level. Class and interfaces cannot be private. Variables that are declared private
can be accessed outside the class if public getter methods are present in the class. Using the
private modifier is the main way that an object encapsulates itself and hides data from the outside
world.
Example
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class, so
there is a compile-time error.
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
Public Access Modifier - public: A class, method, constructor, interface etc declared public can
be accessed from any other class. Therefore fields, methods, blocks declared inside a public class
can be accessed from any class belonging to the Java Universe. However if the public class we
are trying to access is in a different package, and then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its
subclasses.
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
Example
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output
Hello

Protected Access Modifier - protected: Variables, methods and constructors which are declared
protected in a super class can be accessed only by the subclasses in other package or any class
within the package of the protected members' class. The protected access modifier cannot be
applied to class and interfaces. Methods, fields can be declared protected, however methods and
fields in an interface cannot be declared protected. Protected access gives the subclass a chance
to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Example
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}
Output
Hello

Understanding Static Variables and Methods


We may apply static keyword with variables, methods, blocks and nested class. The static
keyword belongs to the class rather than instance of the class. Static variables and methods are
also called as class variables and class methods. When a member is declared static, it can be
accessed before any objects of its class are created, and without reference to any object
Static Variables(Static Fields)
 If you declare a variable as static, it is known static variable.
 The static variable can be used to refer the common property of all objects (that is not
unique for each object)
 Suppose there are 100 employees in a company. All employees have its unique name and
id but company name will be same for all 100 employees. Here company name is the
common property
 The static variable gets memory only once in class area at the time of class loading.
 Advantage of static field
 Saves memory
 Example
class Emp
{
int id;
String name;
static String companyName="ABC Company";
}

Static methods
 If you apply static keyword with any method, it is known as 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.
 main() method is the most common example of static method. Main() method is declared
as static because it is called before any object of the class is created
 Limitations of static method
 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in anyway
Example using Static variable and static method
class Circle
{
static double PI = 3.1416; //Static variable
static int area(int r){ //Static method
return PI*r*r;
}
}
class Test
{
public static void main(String args[]){
[Link](" Area of Circle = " +[Link](5));
}
}

Static Variable v Instance Variable


Static Variable Instance Variable

Represent common property Represent unique property

Accessed using class name Accessed using object

Get memory only once Get new memory each time a new object is
created

Understanding final variables and methods


final keyword is used with variable, method and class. It is used for three purposes namely
 It is used to define Named Constant.
If a variable is declared as final, its value cannot be changed (ie) final variable becomes
constant.
class Circle
{
final double PI = 3.1415;

}
 It is used to prevent Method Overriding.
If a method is declared final, it cannot be overridden. Methods of Math Class in [Link]
package are examples of final methods.

class A
{
final void print()
{
[Link](" base class");
}
}
class B extends A
{
// error ! final methods cannot be overridden
void print()
{
[Link](" sub class ");
}
}
 It is used to prevent Inheritance.
If a class is declared final, it cannot be inherited. String class in [Link] package is an
example of final class.
final class A
{
// methods and variables of a class
}
// error , A cannot be inherited
class B extends A
{
// methods and variables of a class
}
Program using final and static keywords
import [Link].*;
public class AreaOfShapes
{

public static final double Area(double side)


{
double square=side*side;
return square;
}
public static final double Area(double l, double b)
{
double rectangle=l*b;
return rectangle;
}
public static final double Area(double a, double b, double c)
{
double s = (a+b+c)/2;
return [Link](s*(s-a)*(s-b)*(s-c));
}
public static void main(String args[])
{
double a,b,c,length,breadth,s;
Scanner in = new Scanner([Link]);
[Link]("Enter side of the Square : ");
s = [Link]();
[Link]("Area of Sqaure = "+Area(s));
[Link]("Enter Length of the Rectangle : ");
length = [Link]();
[Link]("Enter Breadth of the Rectangle : ");
breadth = [Link]();
[Link]("Area of Rectangle = "+Area(length,breadth));
[Link]("Enter Side1 of triangle : ");
a = [Link]();
[Link]("Enter Side2 of triangle : ");
b = [Link]();
[Link]("Enter Side3 of triangle : ");
c = [Link]();
[Link]("Area of Triangle = "+Area(a,b,c));
}
}

Nested and Inner Classes


Defining a class within another class is known as nested class. The scope of a nested class is
bounded by the scope of its enclosing class. A nested class has access to the members, including
private members, of the class in which it is nested. The enclosing class does not have access to
the members of the nested class.
Types of nested classes

 Static nested classes


A static nested class must access the members of its enclosing class through an object. It
cannot refer to members of its enclosing class directly.

/ Program to demonstrate accessing


// a static nested class

// outer class
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;

// private member
private static int outer_private = 30;

// static nested class


static class StaticNestedClass
{
void display()
{
// can access static member of outer class
[Link]("outer_x = " + outer_x);
// can access display private static member of outer class
[Link]("outer_private = " + outer_private);

// The following statement will give compilation error


// as static nested class cannot directly access non-static membera
// [Link]("outer_y = " + outer_y);

}
}
}
// Driver class
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
[Link] nestedObject = new [Link]();

[Link]();

}
}

Output
outer_x=10
outer_private=30

 Non-static nested classes


An inner class is a non-static nested class. It has access to all of the variables and
methods of its outer class and may refer to them directly. Thus, an inner class is fully
within the scope of its enclosing class.
// Program to demonstrate accessing
// a inner class

// outer class
class OuterClass
{
// static member
static int outer_x = 10;

// instance(non-static) member
int outer_y = 20;

// private member
private int outer_private = 30;

// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
[Link]("outer_x = " + outer_x);

// can also access non-static member of outer class


[Link]("outer_y = " + outer_y);

// can also access a private member of the outer class


[Link]("outer_private = " + outer_private);

}
}
}

// Driver class
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
[Link] innerObject = [Link] InnerClass();

[Link]();

}
}
Output
outer_x=10
outer_y=20
outer_private=30

Example
class outer //Enclosing class
{
int outer_x =10;

class inner //Inner Class


{
void display()
{
[Link]("outer_x = "+outer_x);
}
}
void test()
{
inner i = new inner();
[Link]();
}
public static void main(String[] args)
{
outer o = new outer();
[Link]();
}
}
Introduction to String class
String is a sequence of characters. In java, objects of String are immutable which means a
constant and cannot be changed once created.
Creating a String
There are two ways to create string in Java:
 String literal
String s = “Hello”;
 Using new keyword
String s = new String (“Hello”);
Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}
}

Output
java
strings
example

Constructors of String Class


String(byte[] byte_arr) – Construct a new String by decoding the byte array. It uses the
platform’s default character set for decoding.
String(byte[] byte_arr, Charset char_set) – Construct a new String by decoding the byte
array. It uses the char_set for decoding.
String(byte[] byte_arr, String char_set_name) – Construct a new String by decoding the byte
array. It uses the char_set_name for decoding.
It looks similar to the above constructs and they appear before similar functions but it takes
the String(which contains char_set_name) as parameter while the above constructor
takes CharSet.
String(byte[] byte_arr, int start_index, int length) – Construct a new string from the bytes
array depending on the start_index(Starting location) and length(number of characters from
starting location).
String(byte[] byte_arr, int start_index, int length, Charset char_set) – Construct a new string
from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).Uses char_set for decoding.
String(byte[] byte_arr, int start_index, int length, String char_set_name) – Construct a new
string from the bytes array depending on the start_index(Starting location) and length(number of
characters from starting location).Uses char_set_name for decoding.
String(char[] char_arr) – Allocates a new String from the given Character array
String(char[] char_array, int start_index, int count) – Allocates a String from a
given character array but choose count characters from the start_index.
String(int[] uni_code_points, int offset, int count) – Allocates a String from
a uni_code_array but choose count characters from the start_index.
String(StringBuffer s_buffer) – Allocates a new string from the string in s_buffer
String(StringBuilder s_builder) – Allocates a new string from the string in s_builder
Working with String Handling Methods
int length(): Returns the number of characters in the String.
char charAt(int i): Returns the character at ith index.
String substring (int i): Return the substring from the ith index character to end.
String substring (int i, int j): Returns the substring from i to j-1 index.
String concat( String str): Concatenates specified string to the end of this string.
int indexOf (String s): Returns the index within the string of the first occurrence of the
specified string.
int indexOf (String s, int i): Returns the index within the string of the first occurrence of
the specified string, starting at the specified index.
int lastIndexOf( String s): Returns the index within the string of the last occurrence of
the specified string.
boolean equals( Object otherObj): Compares this string to the specified object.
boolean equalsIgnoreCase (String anotherString): Compares string to another string,
ignoring case considerations.
int compareTo( String anotherString): Compares two string lexicographically.
int out = [Link](s2); // where s1 ans s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
int compareToIgnoreCase( String anotherString): Compares two string
lexicographically, ignoring case considerations.
int out = [Link](s2);
// where s1 and s2 are
// strings to be compared

This returns difference s1-s2. If :


out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
String toLowerCase(): Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = [Link](); // returns “hello"
String toUpperCase(): Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = [Link](); // returns “HELLO”
String trim(): Returns the copy of the String, by removing whitespaces at both ends. It
does not affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = [Link](); // returns “Learn Share Learn”
String replace (char oldChar, char newChar): Returns new string by replacing all
occurrences of oldChar with newChar.
Example:
public class StringHandlingExample {
public static void main(String[] args) {
// Creating a string
String str = "Hello, World!";
String str2 = "hello, world!";

// 1. Length of the string


[Link]("Length: " + [Link]());

// 2. Character at a specific index


[Link]("Character at index 7: " + [Link](7));

// 3. Substring
[Link]("Substring (7 to 12): " + [Link](7, 12));

// 4. String comparison
[Link]("Equals: " + [Link](str2));
[Link]("Equals Ignore Case: " + [Link](str2));

// 5. Concatenation
[Link]("Concatenation: " + [Link](" How are you?"));

// 6. Replace characters
[Link]("Replace 'World' with 'Java': " + [Link]("World", "Java"));

// 7. Convert to uppercase and lowercase


[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());

// 8. Trim whitespace
String str3 = " Trim me! ";
[Link]("Trimmed: '" + [Link]() + "'");

// 9. Split string
String[] words = [Link](", ");
[Link]("Split:");
for (String word : words) {
[Link](word);
}

// 10. Check if string contains a substring


[Link]("Contains 'World': " + [Link]("World"));
}
}

OUTPUT
Length: 13
Character at index 7: W
Substring (7 to 12): World
Equals: false
Equals Ignore Case: true
Concatenation: Hello, World! How are you?
Replace 'World' with 'Java': Hello, Java!
Uppercase: HELLO, WORLD!
Lowercase: hello, world!
Trimmed: 'Trim me!'
Split:
Hello
World!
Contains 'World': true

StringBuffer Class
StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in
java is same as String class except it is mutable i.e. it can be changed.
Mutable String
A string that can be modified or changed is known as mutable string. StringBuffer is used for
creating mutable string.
Constructors of StringBuffer class
StringBuffer()-creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str)- creates a string buffer with the specified string.
StringBuffer(int capacity)- creates an empty string buffer with the specified capacity as
length.
Methods of StringBuffer class
append(String s)- is used to append the specified string with this string. The append()
method is overloaded like append(char), append(boolean), append(int), append(float),
append(double) etc.
Example
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
insert(int offset, String s)-is used to insert the specified string with this string at the
specified position. The insert() method is overloaded like insert(int, char), insert(int,
boolean), insert(int, int), insert(int, float), insert(int, double) etc.
Example
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}

replace(int startIndex, int endIndex, String str)- is used to replace the string from specified
startIndex and endIndex.
Example
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
delete(int startIndex, int endIndex)- is used to delete the string from specified startIndex
and endIndex.
Example
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}

reverse()-is used to reverse the string.


Example
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link]();
[Link](sb);//prints olleH
}
}
capacity()-is used to return the current capacity.
Example
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
charAt(int index)- is used to return the character at the specified position.
length()-is used to return the length of the string i.e. total number of characters.
substring(int beginIndex)-is used to return the substring from the specified beginIndex.
substring(int beginIndex, int endIndex)- is used to return the substring from the specified
beginIndex and endIndex.

You might also like