0% found this document useful (0 votes)
15 views8 pages

String

The document explains the differences between the String and StringBuffer classes in Java, highlighting that String is immutable while StringBuffer is mutable. It details various methods available in both classes, providing examples of their usage. Additionally, it covers concepts of final variables and blank final variables in Java, illustrating their behavior with examples.

Uploaded by

rishavthakkar02
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)
15 views8 pages

String

The document explains the differences between the String and StringBuffer classes in Java, highlighting that String is immutable while StringBuffer is mutable. It details various methods available in both classes, providing examples of their usage. Additionally, it covers concepts of final variables and blank final variables in Java, illustrating their behavior with examples.

Uploaded by

rishavthakkar02
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/ 8

String and StringBuffer

String
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. For
example:

String s="Welcome";

String s2="Welcome";//It doesn't create a new instance

Java String class methods


The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
Method Description

char charAt(int index) returns char value for the particular index

int length() returns string length

String substring(int beginIndex) returns substring for given begin index.

String substring(int beginIndex, int returns substring for given begin index and end index.
endIndex)

boolean contains(CharSequence s) returns true or false after matching the sequence of char value.

boolean equals(Object another) checks the equality of string with the given object.

boolean isEmpty() checks if string is empty.

String concat(String str) concatenates the specified string.

String replace(char old, char new) replaces all occurrences of the specified char value.

static String compares another string. It doesn't check case.


equalsIgnoreCase(String another)

int compareTo(String Compares two strings lexicographically.


anotherString)

int indexOf(int ch) returns the specified char value index.

int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index.
String toLowerCase() returns a string in lowercase.

String toUpperCase() returns a string in uppercase.

String trim() removes beginning and ending spaces of this string.

static String valueOf(int value) converts given type into string. It is an overloaded method.

Example

class Program
{

public static void main(String args[])


{
String s=new String("hello");

System.out.println(s);
System.out.println("concatenation "+s.concat("hii"));
System.out.println("character at particular index "+s.charAt(2));
System.out.println("check equals to "+s.equals("hello"));
System.out.println("ignoring case check equality
"+s.equalsIgnoreCase("HELLO"));
System.out.println("index of e "+s.indexOf('e'));
System.out.println("upper case "+s.toUpperCase());
System.out.println("is empty "+s.isEmpty());
System.out.println("substring "+s.substring(1,4));
System.out.println("compare to "+s.compareTo("hello"));

}
}
Output

hello
concatenation -hellohii
character at particular index -l
check equals to -true
ignoring case check equality -true
index of e -1
upper case -HELLO
is empty -false
substring -ell
compare to --4
Example-String class is immutable

class Test

public static void main(String args[]){

String s="HII";

s.concat(" Hello"); //concat() method appends the string at the end

System.out.println(s);//will print HII because strings are immutable objects -op-HII

StringBuffer class
Java 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.

Constructor Description

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 creates an empty string buffer with the specified capacity as


capacity) length.

Methods

Method Description

StringBuffer append(String s) appends the specified string with this string. The append()
method is overloaded like append(char),append(int),
append(double) etc.
StringBuffer insert(int offset, inserts the specified string in a string at the specified position.
String s) The insert() method is also overloaded .

StringBuffer replace(int replace the string from specified startIndex and endIndex.
startIndex, int endIndex,
String str)

StringBuffer delete(int deletes the string from specified startIndex and endIndex.
startIndex, int endIndex)

StringBuffer reverse() reverse the string.

int capacity() returns the current capacity.

void ensureCapacity(int ensures the capacity at least equal to the given minimum.
minimumCapacity)

char charAt(int index) returns the character at the specified position.

int length() returns the length of the string i.e. total number of characters.

String substring(int returns the substring from the specified beginIndex.


beginIndex)

Substring substring(int returns the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex. this method is overloaded to work with only begin
index.

Example
class Program2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("kolkata");
System.out.println(sb);
System.out.println("reverse the string: "+sb.reverse());
System.out.println("length of the string :"+sb.length());
System.out.println("capacity :"+sb.capacity());
System.out.println("reverse :"+sb.reverse());
System.out.println("append :"+sb.append("city"));
System.out.println("delete substring :"+sb.delete(7,11));
System.out.println("delete from particular index :
"+sb.deleteCharAt(1));
sb.ensureCapacity(30);
System.out.println("after increasing capacity :"+sb.capacity());
System.out.println("inser a char:" +sb.insert(1,'o'));
System.out.println("append:" +sb.append(" is city"));
System.out.println("replace : "+sb.replace(11,14,"c"));
System.out.println("finding a substring: "+sb.substring(1,4));
sb.setCharAt(5,'r');
System.out.println("USING SETCHARAT :"+sb);
StringBuffer s=new StringBuffer();
s.setLength(5);
System.out.println(s.length());
}
}

Output
kolkata
reverse the string: ataklok
length of the string :7
capacity :23
reverse :kolkata
append :kolkatacity
delete substring :kolkata
delete from particular index : klkata
after increasing capacity :48
inser a char:kolkata
append:kolkata is city
replace : kolkata is cy
finding a substring: olk
USING SETCHARAT :kolkara is cy
5

Array of objects
public class Employee
{
static int count=0;
int id;
String name;
Employee(String n)
{
id=++count;
name=n;
}

public static void main(String args[]) {


Employee emp[] = new Employee[4];
emp[0] = new Employee("A");
emp[1] = new Employee("B");
emp[2] = new Employee("C");
emp[3] = new Employee("D");

for(Employee e : emp)
System.out.println("Employee "+e.id+" name "+e.name);

}
}

Output
Employee 1 name A
Employee 2 name B
Employee 3 name C
Employee 4 name D

Final Variable
If you make any variable as final, you cannot change the value of final variable-It will be
constant.

class Car{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; //Compilation error
}
public static void main(String args[]){
Car obj=new Car();
obj.run();
}
}
Blank Final variable

A final variable that is not initialized at the time of declaration is known as blank final
variable.If you want to create a variable that is initialized at the time of creating object and
once initialized may not be changed, it is useful. For example PAN CARD number of an
employee.It can be initialized only in constructor.

class Employee{
int id;
String name;
final String PAN_CARD_NUMBER; //initialized in constructor
...
}

Example

public class Car{


final int speedlimit;//final variable
Car(int l)
{
speedlimit=l;
}
void run(){
//speedlimit=200; //Compilation error
System.out.println("Running with speed"+speedlimit);
}
public static void main(String args[]){
Car obj=new Car(100);
Car obj1=new Car(110);
obj.run();
obj1.run();

}
}
Output

Running with speed100


Running with speed110

You might also like