You are on page 1of 14

Advanced String methods

charAt() method 
This method is used to look at a String as a sequence of characters and return the
character which is present at a particular position input by the user.

Example:

Try It

public class CharAt

public static void main(String[] args)

String a = "Welcome To Java";

int charAtPosition = 5;

char charValue = a.charAt(charAtPosition);

System.out.println("Char At " + charAtPosition + " is :: " +


charValue);

Click "Try It" button to execute above code. Output will be:

Char At 5 is :: m

Explanation:
Clearly, the character at position 5 is: m

trim() method
trim() method is used to remove any space characters at the start or the end of a String.
This method also very widely used.

Example:

Try It

public class Trim

public static void main(String[] args)

String a = "Welcome To Java ";

System.out.println("Before Trimming :: \""+a+"\"");

String output = a.trim();

System.out.println("Before Trimming :: \""+output+"\"");

Before Trimming :: "Welcome To Java "


Before Trimming :: "Welcome To Java"

toUpperCase(), toLowerCase() method 


toUpperCase() method is used to convert a string into uppercase, whereas toLowerCase()
is used to convert whole string in lower case. 
Example:

Try It

public class UpperLowerCase

public static void main(String[] args)

String a = "Welcome To Java";

String upper_String = a.toUpperCase();

System.out.println(upper_String);

String lower_String = a.toLowerCase();

System.out.println(lower_String);

WELCOME TO JAVA
welcome to java

isEmpty() method 
This method returns Boolean value after checking if there anything exists in a String
variable. If the variable contains some value (except blank string), it returns false, else it
returns true.

Example:

Try It

public class IsEmpty

{
public static void main(String[] args)

String a = "Welcome To Java";

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

String b= "";

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

false
true

toCharArray() method 
This method takes String as an input and converts it into a character array.

Example:

Try It

public class ToCharArray

public static void main(String[] args)

String a = "Welcome To Java";

char c[] = a.toCharArray();

System.out.println(c);

System.out.println(c[0]);

Welcome To Java
W
split() method 
split() method splits a String when it encounters a particular string (we can call it delimiter)
mentioned by the user.

And, if the delimiter doesn’t exist in the input string, the method will return the input string as
the first element of the destination array.

Example:

Try It

public class Split

public static void main(String[] args)

String a = "Welcome To Java";

String[] b = a.split("o");

System.out.println(b[0]);

String[] c = a.split("z");

System.out.println(c[0]);

Welc
Welcome To Java

endsWith(), startsWith(), contains() method 


As the name suggests, these methods confirms existence of a particular string at a
specified position inside a string. The return type is a Boolean (true or false)

endsWith(arg0) – checks if the input string ends with the string provided in arg0.
startsWith(arg0) – checks if the input string starts with the string provided in arg0.

startsWith(arg0, arg1) – checks if the input string starting from index(arg1) with the string
provided in arg0.

contains(arg0) – checks if the input string contains the string provided in arg0.

Example:

Try It

public class StringUtility


{

public static void main(String[] args)

String a = "Welcome To Java";

String endsWithString = "a";

System.out.println(a.endsWith(endsWithString));

String startsWithString = "el";

System.out.println(a.startsWith(startsWithString));

System.out.println(a.startsWith(startsWithString, 1));

String containsString = "sd";

System.out.println(a.contains(containsString));

}
}

true
false
true
false

indexOf() , lastIndexOf() method 


These methods returns the positions of the characters in a particular string.
int indexOf(int i) -  returns the position of the first occurrence of the character i in the
string . If the integer doesn’t exist in the string, it returns -1

int indexOf(int i, int j) - returns the position of the first occurrence of the character i in the
substring of the string starting from index j (substring(j)). If the integer doesn’t exist in the
string, it returns -1

indexOf(String s) - returns the position of the first occurrence of the string s in the string . If
the integer doesn’t exist in the string, it returns -1

indexOf(String s, int i) - returns the position of the first occurrence of the string s in the
substring of the string starting from index i (substring(i)). If the integer doesn’t exist in the
string, it returns -1

Similarly, int indexOf(int i), int indexOf(int i, int j, indexOf(String s) and indexOf(String


s, int i) – all these methods exist, which finds out the position of the last occurrences.

Example:

Try It

public class Index

public static void main(String[] args)

String a = "Welcome To Java 5";


System.out.println(a.indexOf(1));

System.out.println(a.indexOf('5', 5));

System.out.println(a.indexOf("Welcome"));

System.out.println(a.indexOf("Welcome",10));

System.out.println(a.lastIndexOf("Wel"));

-1
16
0
-1
0

replace() , replaceAll(), replaceFirst() method 

replace(char a, char b) – In the input String, this method replaces all the occurrences of
char a by char b.

replaceFirst(String strA, String strB) – In the input String, this method replaces the first
occurrence of strA a by strB.

replaceAll(String strA, String strB) – In the input String, this method replaces all the
occurrences of strA a by strB. The basic difference between replace() and replaceAll() is
that, replaceAll() accepts regex and replace() accepts characters.

Example:

Try It

public class Replace

public static void main(String[] args)

String a = "Welcome to Java 5";

String b = a.replace("e", "X");

System.out.println(b);

String c = a.replaceFirst("e", "X");

System.out.println(c);

String d = a.replaceAll("e", "X");

System.out.println(d);

}
WXlcomX To Java 5
WXlcome To Java 5
WXlcomX To Java 5

equals(), equalsIgnoreCase() method 


All these 2 methods are used for String comparison. Here we need to remember that we
cannot compare Strings using == operators. Because == operators are used to compare
objects references.

equals() method compares the String case-sensitively

equalsIgnoreCase() method compares the Strings irrespective of their cases.

Example:

Try It

public class Compare

public static void main(String[] args)

String a = "Welcome";

String b = "Welcome";

String c = "welcome";

String d = "compareStrings";

System.out.println(a.equals(b));

System.out.println(a.equals(c));

System.out.println(a.equalsIgnoreCase(c));

System.out.println(a.equalsIgnoreCase(d));

}
true
false
true
false

More Advanced Methods in String Class


What are equals(), equalsIgnoreCase() method? 
All these 2 methods are used for String comparison. Here we need to remember that we
cannot compare Strings using == operators. Because == operators are used to compare
objects references.

equals() method compares the String case-sensitively

equalsIgnoreCase() method compares the Strings irrespective of their cases.

Example:

public class Compare

public static void main(String[] args)

String a = "Welcome";

String b = "Welcome";

String c = "welcome";

String d = "compareStrings";

System.out.println(a.equals(b));
System.out.println(a.equals(c));

System.out.println(a.equalsIgnoreCase(c));

System.out.println(a.equalsIgnoreCase(d));

Click "Try It" button to execute above code. Output will be:

true
false
true
false

From "String in immutable" to "Concepts of String Pool"

String is immutable. Okay… we know it, but what does “immutable” means?

Well, immutable means, that once a string is created, it cannot be destroyed, neither can it
be modified until JVM is restarted.

For example, if we do –

String a = "Java";

a = a + " Test";

By now, we can tell that this will assign value “Java Test” in variable a. But, internally that
doesn’t quite do so. What it does is, it creates a new string “Java Test”, and point the
variable ‘a’ to that memory location. So, now, variable ‘a’ have a value “Java Test”. So,
internally there are 2 memory locations allocated for string “Java” and “Java Test”.
Programmatically we can prove that –

public class Immutable

public static void main(String[] args)

String a = "Java";

String b = a;

System.out.println(a == b);

a = a + "Test";

System.out.println(a == b);

So, it looks like that there’s a lot of memory is wasted if we use String all over our code,
right? But, if we look close, certainly there is some facilities of using String. For that we
need to know what String pool is.

String Pool
Whenever we are creating a new string using string literal (String a = "Welcome To
Java";), it first searches in the String Pool. If that String already exists in there, it uses the
reference of the same string in the program. If, it does not exist, it allocates memory for the
new string and put it in the String Pool, so that the new variables can use its reference.

Again, when we create String objects by using new(), it doesn’t check in String Pool and it
creates an object right there. So, it is a better habit to create strings using string literals.

Facilities of Using String

When, we are using same String again and again all over the program, it is better idea to
use a String. Because, every time, it will not allocate memory location, rather, it will use the
same reference again and again.

StringBuffer and StringBuilder


StringBuffer and StringBuilder are classes which provides almost same functionalities as
String Class. 

Try It

public class StringBufferExample

public static void main(String[] args)

StringBuffer sb = new StringBuffer("String Buffer Example");

StringBuilder sb1 = new StringBuilder("String Builder Example");

System.out.println(sb);

System.out.println(sb1);

Click "Try It" button to execute above code. Output will be:
String Buffer Example
String Builder Example

Difference between String, StringBuffer and


StringBuilder

Properties String StringBuffer StringBuilder

immutable YES NO NO

Synchronized N/A as String is YES NO


Immutable

So, by performance StringBuilder is fastest as it is both not immutable and non-


synchronized.

When to use String , StringBuffer and StringBuider?


When, we are using same String again and again all over the program, it is better idea
to use a String. Because, every time, it will not allocate memory location, rather, it will use
the same reference again and again. It can produce better performance.

If the object is not used by multiple threads it is better to use StringBuilder. If not used by
multiple threads, it needs not to be synchronized.
If the String is going to be used by multiple threads in the application, then, we need
synchronization and StringBuffer is synchronized by default.

You might also like