String Handling in Java


String Handling provides a lot of concepts that can be performed on a string such as concatenating string, comparing string, substring etc.

Let’s first understand what is string and how we can create the string object.

Strings

which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.
String

Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.

 

Creating Strings:

 

How to create String object?

There are two ways to create String object:

1. By string literal
2. By new keyword

 

1) String literal

String literal is created by double quote.For Example:

1. String s=”Hello”;

 

Each time when we 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 returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example:

 

1. String s1=”Java”;
2. String s2=”Java”;//no new object will be created

 

In the above example only one object will be created.First time JVM will find no string object with the name “Welcome” in string constant pool,so it will create a new object.Second time it will find the string with the name “Welcome” in string constant pool,so it will not create new object whether will return the reference to the same instance.

 

Note: String objects are stored in a special memory area known as string constant pool inside the Heap memory.
The most direct way to create a string is to write:
String str = “Hello world!”;

 

Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, “Hello world!’.

 

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.e.g.

 

public class Str{
public static void main(String args[]){
char[] hArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’};
String s1 = new String(hArray);
System.out.println(s1);
}}

 

output :
hello.

 

Note: The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.

 

Why java uses concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

 

2) By new keyword

String s=new String(“Java”);//creates two objects and one reference variable

In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal “Welcome” will be placed in the string constant pool.The variable s will refer to the object in Heap(nonpool).

public class StringDemo{
public static void main(String args[])
{
char[] helloArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’};
String helloString = new String(helloArray);
System.out.println( helloString );
}}

String Methods in java:

String method cannot manipulate the string.

1. Concat( )

This method is used to concatenate two string e.g

Java String concat() method example

public class SC{

public static void main(String args[]){

String s1=”Java string”;

s1.concat(“is immutable”);

System.out.println(s1);

s1=s1.concat(” is immutable so assign it explicitly”);

System.out.println(s1);

}}

output:

java string is immutable

java string is immutable so assign it explicitly

2.isEmpty( )

The java string isEmpty() method checks if this string is empty. It returns true, if length of string is 0 otherwise false.

Java String isEmpty() method example

public class SIE{

public static void main(String args[]){

String s1=””;

String s2=”JavaLanguage”;

System.out.println(s1.isEmpty());

System.out.println(s2.isEmpty());

}}

output :

true

false

3.equals()

The Java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

The String equals() method overrides the equals() method of Object class.

Java String equals() method example

public class SEqu{

public static void main(String args[]){

String s1=”javalanguage”;

String s2=”javalanguage”;

String s3=”JAVALANGUAGE”;

String s4=”python”;

System.out.println(s1.equals(s2));//true because content and case is same

System.out.println(s1.equals(s3));//false because case is not same

System.out.println(s1.equals(s4));//false because content is not same

}}

output :

true

false

false

4.trim( )

The Java string trim() method eliminates leading and trailing spaces. The unicode value of space character is ‘\u0020’. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

Note : The string trim() method doesn’t omits middle space

Java String trim() method example

public class StringTrimExample{

public static void main(String args[]){

String s1=”  welcome java   “;

System.out.println(s1+”javalanguage”);//without trim()

System.out.println(s1.trim()+”javalanguage”);//with trim()

}}

output :

welcome java   javalanguage

welcome javajavalanguage

5.toLowerCase()

The java string toLowerCase() method returns the string in lowercase letter. In other words, it converts all characters of the string into lower case letter.

The toLowerCase() method works same as toLowerCase(Locale.getDefault()) method. It internally uses the default locale.

Java String toLowerCase() method example

public class StringLowerExample

{

public static void main(String args[])

{

String s1=”JAVALANGUAGE stRIng”;

String s1lwr=s1.toLowerCase();

System.out.println(s1lwr);  }}

Output:

javalanguage string

6. toUpperCase()

The java string toUpperCase() method returns the string in uppercase letter. In other words, it converts all characters of the string into upper case letter.The toUpperCase() method works same as toUpperCase(Locale.getDefault()) method. It internally uses the default locale.There are two variant of toUpperCase() method. The signature or syntax of string toUpperCase() method is given below:

  1. public String toUpperCase()
  2. public String toUpperCase(Locale locale)

The second method variant of toUpperCase(), converts all the characters into uppercase using the rules of given Locale.

Java String toUpperCase( ) method example

 

public class StringUpperExample

{

public static void main(String args[])

{

String s1=”javalanguage stRIng”;

String s1upr=s1.toLowerCase();

System.out.println(s1upr);  }}

Output:

JAVALANGUAGE STRING

 

7. split()

The java string split() method splits this string against given regular expression and returns a char array.There are two signature for split() method in java string.

public String split(String regex)

OR

public String split(String regex, int limit)

Java String split() method example

The given example returns total number of words in a string excluding space only. It also includes special characters.

public class SplitExample{

public static void main(String args[]){

String s1=”java string split method by javalanguage”;

String[] words=s1.split(“\\s”);//splits the string based on string

//using java foreach loop to print elements of string array

for(String w:words){

System.out.println(w);  }  }}

output:java

string

split

method

by

javalanguage

Java String split() method with regex and length example

public class SplitExample2{

public static void main(String args[]){

String s1=”welcome to split world”;

System.out.println(“returning words:”);

for(String w:s1.split(“\\s”,0)){

System.out.println(w);  }

System.out.println(“returning words:”);

for(String w:s1.split(“\\s”,1)){

System.out.println(w);

}

System.out.println(“returning words:”);

for(String w:s1.split(“\\s”,2)){

System.out.println(w);  }    }}

 

output :

returning words:

welcome

to

split

world

returning words:

welcome to split world

returning words:

welcome

to split world

8.indexOf( )

The java string indexOf() method index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero.

There are 4 types of indexOf method in java. The signature of indexOf methods are given below:

No. Method Description
1 int indexOf(int ch) returns index position for the given char value
2 int indexOf(int ch, int fromIndex) returns index position for the given char value and from index
3 int indexOf(String substring) returns index position for the given substring
4 int indexOf(String substring, int fromIndex) returns index position for the given substring and from index

Java String indexOf() method example

public class IndexOfExample{

public static void main(String args[]){

String s1=”this is index of example”;

//passing substring

int index1=s1.indexOf(“is”);//returns the index of is substring

int index2=s1.indexOf(“index”);//returns the index of index substring

System.out.println(index1+”  “+index2);//2 8

 

//passing substring with from index

int index3=s1.indexOf(“is”,4);//returns the index of is substring after 4th index

System.out.println(index3);//5 i.e. the index of another is

 

//passing char value

int index4=s1.indexOf(‘s’);//returns the index of s char value

System.out.println(index4);//3  }}

output:

2      8

5

3

StringBuffer class and its Methods in Java :

The StringBuffer class is used to represent characters that can be modified. This is simply used for concatenation or manipulation of the strings. StringBuffer is mainly used for the dynamic string concatenation which enhances the performance. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. There are some functions used in the given example. All the functions have been explained below with example :

1.append( )

This is the append() function used for the concatenate the string in string buffer. This is better to use for dynamic string concatenation. This function works like a simple string concatenation such as : String str = str + “added string”;.

class SA{

public static void main(String args[]){

StringBuffer s1=new StringBuffer(“Java “);

s1.append(“Language”);//now original string is changed

System.out.println(“String is :”+s1);//prints  Java Language

}  }

 

output:

 

String is: java language

 

2.insert( )

 

This is the insert() function used to insert any string or character at the specified position in the given string.e.g.

 

class SI{

public static void main(String args[]){

StringBuffer s1=new StringBuffer(“Java “);

s1.isert(1,”Language”);//now original string is changed

System.out.println(s1);//prints  JLanguageava

}  }

output :

JLanguageava

 

3.reverse( )

 

This is the reverse() function used to reverse the string present in string buffere.e.g.

 

class SA{

public static void main(String args[]){

StringBuffer s1=new StringBuffer(“Java “);

s1.reverse();

System.out.println(s1);//prints  avaJ

}  }

output :

avaJ

  1. setCharAt()

 

This is the setCharAt() function which is used to set the specified character in buffered string at the specified position of the string in which you have to set the given character.e.g

 

class SCA{
public static void main(String args[]){
StringBuffer s1=new StringBuffer(“Java language “);
s1.setCharAt(5,’L’); // Change l to L:
System.out.println(s1);//prints Java Language
} }

output :

java Language

 

 

5.charAt()

 

This is the charAt() function which is used to get the character at the specified position of the given string.e.g

public class SCA {

public static void main(String[] args) {

String str = “This is Computernotes”;

// prints character at 1st location

System.out.println(str.charAt(0));//prints C

// prints character at 5th location i.e white-space character

System.out.println(str.charAt(4));//prints nothing

// prints character at 8th location

System.out.println(str.charAt(7));//prints n

}}
6.substring()

 

This is the substring() function which is used to get the sub string from the buffered string from the initial position to end position (these are fixed by you in the program).e.g

 

Class SSS{
public static void main(String args[]){
String Str = new String(“Welcome to Java Language”);

System.out.print(“Result :” );
System.out.println(Str.substring(10) );//prints Java language

System.out.print(“Result :” );
System.out.println(Str.substring(10, 15) );}}//prints Java

output:

Result : Java Language
Result : Java

 

7.deleteCharAt()

 

This is the deleteCharAt() function which is used to delete the specific character from the buffered string by mentioning that’s position in the string.e.g

public class SDCA{
public static void main(String[] args) {
StringBuilder str = new StringBuilder(“Java lang package”);
System.out.println(“string = ” + str);

// deleting character from index 4 to index 9
str.delete(4, 9);
System.out.println(“After deletion = ” + str);//prints Java package

str = new StringBuilder(“JAVA”);
System.out.println(“string = ” + str);
// deleting character at index 2
str.deleteCharAt(2);
System.out.println(“After deletion = ” + str);//prints JAA
}}

output :

string = Java lang package
After deletion = Java package
string = JAVA
After deletion = JAA

 

 

8.length()

 

This is the length() function is used to finding the length of the buffered string.e.g

 

public class SL{
public static void main(String args[]) {
String s1 = “Man saw a mad Dog”;
int len = s1.length();
System.out.println( “String Length is : ” + len );
}}
output:

String Length is : 17

 

9.delete()

 

This is the delete() function is used to delete multiple character at once from n position to m position (n and m are will be fixed by you.) in the buffered string.e.g.

 

class SD{

public static void main(String args[]){

StringBuffer s1=new StringBuffer(“Java “);

S1.delete(1,2);

System.out.println(s1);//prints  Ja}  }

 

10.capacity()

 

This is the capacity() function is used to know about the current characters kept which is displayed like : number of characters + 6.e.g.

 

class SC{

public static void main(String args[]){

StringBuffer s1=new StringBuffer();

System.out.println(sb.capacity());//default 16

s1.append(“Javaa”);

System.out.println(s1.capacity());//now 16

s1.append(“java is my favourite language”);

System.out.println(s1.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2

}  }

 

11.replace()

 

The replace() method replaces the given string from the specified beginIndex and endIndex. e.g.

 

class SR{

public static void main(String args[]){

StringBuffer s1=new StringBuffer(“Javaa “);

S1.replace(1,3,”language”);

System.out.println(s1);//prints  Jlanguagea

}  }

output :

Jlanguage

Difference Between String , StringBuilder and StringBuffer Classes with Example in Java

String

String is immutable object  . Immutalble means once created cannot change.The object created as a String is stored in the  Constant String Pool  .

Every immutable object in Java is thread safe ,that implies String is also thread safe .

String can not be used by two threads simultaneously.String  once assigned can not be changed .

String  str = ” Java ” ;
// The above object is stored in constant string pool and its value can not be modified.

str=”Language” ;     //new “Language” string is created in constant pool and referenced by the str variable

// “Java” string still exists in string constant pool and its value is not overrided but we lost reference to the  “Java”string

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap .  StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .
Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.

StringBuffer s1 = new StringBuffer(“Java”) ;// The above object stored in heap and its value can be changed .

s1=new StringBuffer(“Language”);
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuffer

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe .

StringBuilder s2= new StringBuilder(“Java”);
// The above object too is stored in the heap and its value can be modified
s2=new StringBuilder(“Language”);
// Above statement is right as it modifies the value which is allowed in the StringBuilder

Comments are closed.