string methods in java

In Java, the String class has a lot of methods that are used to operate string. In this post, we will see some important methods of String class or string methods in java We will cover each method with example and also discuss the best practices of the java string method and string methods in java

Java 11 introduced some new String methods

Here is the table content of the article.
1. String trim()
2. String length()
3. String replace()
4. String isEmpty()
5. String spilt()
6. String substring()
7. String toCharArray()
8. String toLowerCase()
9. String toUpperCase()
10. String intern()
11. String valueOf()
12. String join()
13. String indexOf()
14. String lastIndexOf()
15. String getBytes()
16. String getChar()
17. String startsWith()
18. string endswith()
19. String equal()
20. String equalsIgnoreCase()
21. String contains()
22. String charAt()
23. String compareTo()
24. repeat() method
25. isBlank method
26. lines() method
27. strip() method
28. stripLeading() method
29. stripTrailing() method

string methods in java

String trim()

Let’s discuss the String trim() method and how to use the java trim method and remove space from string java. The trim() method is present in the String class of java.lang package. Let’s see the advantage of the trim() function in java.

1. What is Java trim() method?
2. Syntax of java trim() method
3. How does the trim() method work?
4. Important points about the java trim method

What is Java trim() method?

The String trim() method is used to truncate the leading space and trailing space from the string. It is used to remove space from string java, but it only removes the extra space before and after the string. As we know the string is an array of characters, so each character is stored in a particular index with its Unicode value.  
The Unicode value of a space character is ‘\u0020’ so when we call the trim() method it checks the Unicode of the space character(‘\u0020’) only before and after of string. If the Unicode of a space character is existing, it removes the spaces and returns the string after the removal of spaces.

String trim in Java

Syntax of java trim() method

access modifier – The access modifier of the trim() method is public. So, can be accessible from everywhere.
return type: The return type of trim() method is String. It returns a String value after removing of white spaces.
Parameter: It doesn’t take any parameter.

String trim in Java
public class StringExample
{
	public static void main(String[] args) 
	{
		String str = " JavaGoal Webiste ";
		System.out.println("Before trim:"+ str);
		System.out.println("After trim:"+ str.trim());
	}
}

Output: Before trim: JavaGoal Webiste
After trim:JavaGoal Webiste

In the above program, we have a String object str that contains a string(JavaGoal website) with white spaces at the beginning and at the end. We are removing those spaces by use of the trim() method.

How does the trim() method work?

As we know String is an array of characters and each character is stored in a particular index. Before saving the string JVM converts all characters in Unicode and then save it.

Suppose we have a String “ JavaGoal  ”, then JVM will convert each character in Unicode and save it in memory.  In this above string, we have three white space one space at the beginning, and two at the end of the string. So let’s see how it will store in memory.

String trim in Java


When we will call the trim() method by use of string object. The trim() method finds the “\u0020” (White space) and removes the spaces from both ends. It doesn’t remove the white space between strings. The trim() method always returns a new string after removing space and the original string will remain the same, because the string is immutable in java.

String trim in Java

Important points about the java trim method

1. java trim method removes the white space from both ends. It doesn’t remove the white space between String.

2. Whenever we call the trim() method, it returns a new object of the string after removing space and the original string object remains unchanged.

public class StringExample
{
	public static void main(String[] args) 
	{
		String str1 = " JavaGoal ";
		String str2 = str1.trim();
		System.out.println("After trim str1:"+str1);
		System.out.println("After trim str2:"+str2);
		System.out.println("Are both have same: "+ (str1 == str2));
	}
}

Output: After trim str1: JavaGoal
After trim str2:JavaGoal
Are both have same: false

3. Java trim method returns the same string object only if the string is empty, or there are no leading and trailing white spaces.

public class StringExample
{
	public static void main(String[] args) 
	{
		String str1 = "";
		String str2 = str1.trim();
		System.out.println("After trim str1:"+str1);
		System.out.println("After trim str2:"+str2);
		System.out.println("Are both have same: "+ (str1 == str2));
	}
}

Output: After trim str1:
After trim str2:
Are both have same: true

4. If a string contains only white spaces, then the trim() method returns the empty string.

String length()

We have learned about string in java and why is it immutable in java. In this topic we will see the string length() method and how does string length() in java work. To operate a string, we need to find the string length of string because if we exceed the length of the string the JVM throws a StringIndexOutOfBoundExcetion.

Here is the table content of the article will we will cover this topic.
1. What is String length in java?
2. Syntax of java value() method
3. How does the value() method work?
4. Count the length without whitespace

What is String length in java?

As we know String is an array of characters and each character is stored in a particular index. To find the length of the string, the String class provides a length() method. The string length method finds the number of characters present in the String. The length() method counts each character even if it is white space.

Syntax of java value() method

string length in java

access modifier: The access modifier of the value() method is public. So, can be accessible from everywhere.
return type: The return type of the value() method is int.
Parameter: It doesn’t take any parameter.

public class StringExample
{
	public static void main(String[] args) 
	{
		String str1 = "JavaGoal website";
		String str2 = " JavaGoal website  ";
		String str3 = "  ";
		String str4 = "";
		
		System.out.println("str1 Length:"+str1.length());
		System.out.println("str2 Length:"+str2.length());
		System.out.println("str3 Length: "+str3.length());
		System.out.println("str4 Length: "+str4.length());
	}
}

Output: str1 Length:16
str2 Length:19
str3 Length: 2
str4 Length: 0

How does the value() method work?

The string length is calculated based on the character presented in the string. The length() method counts all characters that are present in the string even if it is blank space. The first character stores on index 0 and the last one stores at length-1. Suppose we have a String “ JavaGoal  ” and we want to find the length of the string. Then we will invoke the length() method of the string class.

string length in java
public class StringExample
{
	public static void main(String[] args) 
	{		
		String str1 = " JavaGoal website  ";
		System.out.println("Length of str1:"+str1.length());
	}
}

Output: Length of str1:19

Count the length without whitespace

If you want to count the length of a string but you don’t want to include whitespaces, then we should use the trim() method before calling the length() method. The trim() method removes the whitespaces from both ends.

public class StringExample
{
	public static void main(String[] args) 
	{		
		String str1 = " JavaGoal website  ";
		String str2 = "  ";
			
		System.out.println("Length of str1:"+str1.length());
		System.out.println("Length of str1:"+str1.trim().length());
		System.out.println("Length of str2:"+str2.length());
		System.out.println("Length of str2: "+str2.trim().length());
	}
}

Output: Length of str1:19
Length of str1:16
Length of str2:2
Length of str2:0

String replace()

The replace() method is used to replace the content of a string with other content. You can replace the old characters/substring with the new characters/substrings. It means by use of this method you can replace the old content(old characters) with new content (new content). The return type of replace() is String. It returns the String after the replacement operation of character. To get more details we can read java replace method and java string replaceall.

String isEmpty()

The string isEmpty() is used to check whether the current string is empty or not. This method is widely used in java because before performing any operation we check whether the string is empty or not. The String isEmpty() method works based on the length of the string, It returns true if the length of the string is greater than 0 otherwise it returns false.

String isEmpty()
stringName.isEmpty()

stringName: The name of the string in which you want to check whether it is empty or not.

class ExampleOfContains
 {  
	 public static void main(String args[])
	 {    
		String name = "JAVA GOAL";  			 
		boolean isStringEmpty =  name.isEmpty();
		System.out.println("Is String is empty = "+ (isStringEmpty));
		 
		String name2 = "";
		boolean isEmptyString =  name2.isEmpty();
		System.out.println("Is String is empty = "+ (isEmptyString));
	}
}  

Output: Is String is empty = false
Is String is empty = true

Let’s take one more example, where we will different cases of the empty() method.
1. If a String has space then it will not consider a blank string. If you want to consider it a black string then use trim() method.
2. The character \n is considered whitespace, so the trim() method would remove it along with any other trailing space in the String.

class JavaGoal
{
    public static void main(String[] args)
    {
        String stringOne = "JAVA GOAL";
        System.out.println("stringOne is empty = "+ (stringOne.isEmpty()));

        String stringTwo = "";
        System.out.println("stringTwo is empty = "+ (stringTwo.isEmpty()));

        String stringThree = " ";
        System.out.println("stringThree is empty = "+ (stringThree.isEmpty()));

        String stringFour = "\n";
        System.out.println("stringFour is empty = "+ (stringFour.isEmpty()));

        String stringFive = "''";
        System.out.println("stringFive is empty = "+ (stringFive.isEmpty()));

        String newCheck = "";
        String stringSix = new String(newCheck);
        System.out.println("stringSix is empty = "+ (stringSix.isEmpty()));

        String stringSeven = "\n";
        System.out.println("stringSeven empty = "+ (stringSeven.trim().isEmpty()));
    }
}

stringOne empty = false
stringTwo empty = true
stringThree empty = false
stringFour empty = false
stringFive empty = false
stringSix empty = true
stringSeven empty = true

String spilt()

Let see what is the string spilt() method(split method in java) and how to use the string spilt() method in java.

1. What is the string spilt() in Java?
2. String split(String regex)
3. String split(String regex, int limit)

What is the string spilt() in Java?

The String spilt() method in java is used to split the string into parts and return the Array of characters. As we know string is a group of characters or an array of characters, the split() method can break the string into an array of characters. By use of this method, we break the string-based of a particular delimiter. The String spilt in java can be based on space or a comma(,) or it depends on the requirement.

It is an overloaded method in the String class. It has two types:
1. String split(String regex)
2. String split(String regex, int limit)

1. String split(String regex)

This method is defined in the String class and it takes only one parameter. Based on the regex parameter, The method breaks the current string and returns a String array.

stringName.split(regex);

stringName: It is the current string that you want to split into different chunks based on regex.
regex: It is a String type parameter. It is the condition used to split the string.

class ExampleOfSplit
 {  
		 public static void main(String args[])
		 {  
			String str1 = "JAVA GOAL SITE";  
			String[] nameArray1 = str1.split(" ");
			System.out.println("Split by white space:");
			for(String name: nameArray1)
				System.out.println(name);
			
			String str2 = "JAVA,GOAL,SITE";  
			String[] nameArray2 = str2.split(",");
			System.out.println("Split by Comma:");
			for(String name: nameArray2)
				System.out.println(name);
			
			String str3 = "JAVAGOALSITE";  
			String[] nameArray3 = str3.split("");
			System.out.println("Split each character:");
			for(String name1: nameArray3)
				System.out.println("Split by comma = "+name1);
	    }  
}  

Output: Split by white space:
JAVA
GOAL
SITE
Split by Comma:
JAVA
GOAL
SITE
Split each character:
Split by comma = J
Split by comma = A
Split by comma = V
Split by comma = A
Split by comma = G
Split by comma = O
Split by comma = A
Split by comma = L
Split by comma = S
Split by comma = I
Split by comma = T
Split by comma = E

2. String split(String regex, int limit)

This method returns String array on based the given regex. It takes only two parameters. One is the regex, and another is the limit. By use of the second parameter(limit), you can define the maximum limit of chunks.

stringName.split(regex, limit);

stringName: It is the current string that you want to split into different chunks based on regex.
regex: It is a String type parameter. It is the condition used to split the string.
limit: The number of parts in which you want to divide the string. When we don’t provide zero, it will return all the strings matching a regex.

class ExampleOfSplit
 {  
		 public static void main(String args[])
		 {  
			String str1 = "JAVA GOAL SITE";  
			String[] nameArray1 = str1.split(" ", 2);
			System.out.println("Split by white space:");
			for(String name: nameArray1)
				System.out.println(name);
			
			String str2 = "JAVA,GOAL,SITE";  
			String[] nameArray2 = str2.split(",", 1);
			System.out.println("Split by Comma:");
			for(String name: nameArray2)
				System.out.println(name);
			
			String str3 = "JAVAGOALSITE";  
			String[] nameArray3 = str3.split("", 8);
			System.out.println("Split each character:");
			for(String name1: nameArray3)
				System.out.println("Split by comma = "+name1);
		 }  
}  

Output: Split by white space:
JAVA
GOAL SITE
Split by Comma:
JAVA,GOAL,SITE
Split each character:
Split by comma = J
Split by comma = A
Split by comma = V
Split by comma = A
Split by comma = G
Split by comma = O
Split by comma = A
Split by comma = LSITE

When the limit n > 0, the array’s length can’t be greater than n, and the last entry of the array contains all input beyond the last matched delimiter.
n < 0, The array can have any length.
If n > 0, The array can have any length, and trailing empty strings will be discarded.

class ExampleOfSplit
 {  
		 public static void main(String args[])
		 {  
			String str1 = "JAVA GOAL SITE";  
			// limit is -2; array contains all substrings
	        String[] result = str1.split("", -2);
	        System.out.println("Array when limit is -2:");
	        for(String s : result)
	        	System.out.println(s);

	        // limit is 0; array contains all substrings
	        result = str1.split("", 0);
	        System.out.println("Array when limit is 0:"); 
	        for(String s : result)
	        	System.out.println(s);
	        
	        // limit is 2; array contains a maximum of 2 substrings
	        result = str1.split("", 2);
	        System.out.println("Array when limit is 2:");
	        for(String s : result)
	        	System.out.println(s);
	        
	        // limit is 4; array contains a maximum of 4 substrings
	        result = str1.split("", 4);
	        System.out.println("Array when limit is 4:");
	        for(String s : result)
	        	System.out.println(s);
	        
	        // limit is 10; array contains a maximum of 10 substrings
	        result = str1.split("", 10);
	        System.out.println("Array when limit is 10:");
	        for(String s : result)
	        	System.out.println(s);
			
		 }  
}  

Output: Array when limit is -2:
J
A
V
A

G
O
A
L

S
I
T
E

Array when limit is 0:
J
A
V
A

G
O
A
L

S
I
T
E
Array when limit is 2:
J
AVA GOAL SITE
Array when limit is 4:
J
A
V
A GOAL SITE
Array when limit is 10:
J
A
V
A

G
O
A
L
SITE

String substring()

A string is a group of characters or an array of characters. In java substring can be part of String or whole string as well. On the other hand, we can say substring is a subset of String. Java provides some methods to find substring in string java.
Suppose we have a string “JavaGoal”, it has a number of substrings like “Java”, “Goal”, “va”, “ja”, “JavaGoal” etc. To find substring in string java provides substring() method. To get more details we can read the substring method in java and see how to get java substring from String.

String toCharArray()

In the java string toCharArray() method is used to convert string to char array. It is the easiest way to convert a java string to char array, the toCharArray() method creates a new character array with the same length as the length of the string. When it creates a new char array, the original string is left unchanged.

String.toCharArray();
string tochararray()

public: It is an access modifier that defines the access of the method. This method is public so it can access everywhere.
char[]: It returns an array of char type.
no parameter: It doesn’t take any parameter.

class ExampleOfSplit
 {  
		 public static void main(String args[])
		 {  
			String str1 = "A Java learning JAVAGOAL.COM";  
			char[] result = str1.toCharArray();
			System.out.println("Length of String: "+str1.length());
			System.out.println("Length of Array: "+result.length);
			
			for(char s : result)
	        	System.out.println(s);
		 }  
}  

Output: Length of String: 28
Length of Array: 28
A

J
a
v
a

l
e
a
r
n
i
n
g

J
A
V
A
G
O
A
L
.
C
O
M

In the above example, we can see we are using string tochararray() to convert string to array. The string is broken down into an array of characters, and the length of the array equals to the length of the string. The string broke down into characters and each character is assigned to a particular index. The first character is assigned to the first index of the character array and the last character is assigned to the last index.

String toLowerCase()

The string tolowercase() method is used to convert the string into lowercase letters. It is used to convert the character of the string into lowercase of the string. The return type of toLowerCase() is String. Let’s see the syntax and example of java string tolowercase() method

stringName.toLowerCase()

stringName: The name of the string which you want to convert in lowercase letters.

class ExampleOfLowerCase
 {  
	 public static void main(String args[])
	 {    
		String name = "JAVA WINGS";  
		String lowerCase = name.toLowerCase();
		System.out.println("String converted into lower case letters = "+lowerCase);	
         }
}

Output: String converted into lower case letters = java wings

String toUpperCase()

The String toUpperCase() method uses to convert the string into upper-case letters. This string uppercase javascript employs to convert all the letters of String to the upper case of the string. The return type of toUpperCase() is String.

Syntax:

stringName.toUpperCase()

Example:

class ExampleOfUpperCase
 {  
	 public static void main(String args[])
	 {    
		String name = "java wings";  
		String upperCase = name.toUpperCase();
		System.out.println("String converted into upper case letters = "+upperCase);	
         }
}  

Output: String converted into lower case letters = JAVA WINGS

String intern()

String intern() method in java is used to get the String from the string pool that is already presented.  Before moving further, we should read about the String literal and how many ways to create a string. Let’s read the string intern() and how intern() works with string pool java.

Here is the table content of the article will we will cover this topic.
1. What is the String intern() method?
2. How does the java string intern() work?
3. String intern() Example Explanation

What is the String intern() method?

It is used to get the string that is already present in the String pool.  As we know whenever we create a string by string literal, the JVM checks whether the string is present in the string pool or not.
If it presents, then JVM returns the reference of the same string otherwise creates a new string and stores it in the string pool java.
It means when we create a string by string literal, the JVM uses the intern() method.

string intern() method

public: The access modifier of the intern() method is public, so it can be accessed from anywhere.
native:  Here native keyword tells this method is not written in java language, it must be written in another language like C, C++
return type: The return type of the method is String.
parameter:  It doesn’t take any parameter.

How does the java string intern() work?

When we create a string with a new keyword, the JVM creates a new string in memory. If we use the intern() method to create a string, then JVM doesn’t create a new string in memory if it is already presented. Let’s take an example and see how the string intern() method works.

public class StringInternExample
{
   public static void main(String args[])
   {
	   String str1 = "Hello";
	   String str2 = new String("Hello");
	   
	   System.out.println("Are both strings same: "+(str1 == str2));
	   
	   String str3 = new String("Hello").intern();
	   System.out.println("Are both strings same: "+(str1 == str3));
   }
}

Output: Are both strings same: false
Are both strings same: true

In the above example, you can see when we are using the intern() method to get a string.

String intern() Example Explanation

  1. Here we are creating a String str1 by the string literal. The JVM is creating the string in Heap memory and string constant pool.
  2. In the next line, we are creating a new string by using the new operator, the String is created in the heap memory.
  3. In the first print statement, str1 and str2 both are different strings because both are referring to different objects.
  4. In the next line, we are creating a new string by use of the intern() method. Now JVM checks whether a string in the string pool with the value “Hello” is present.  
    Yes, it is presented so it is returning the same object reference.
  5. In the second print statement, str2 and str3 both are the same string because both are referring to the same objects.

String valueOf()

This method is used to convert different types of values into a string. You can convert different types of data values into String data values. The String valueOf() java method is overloaded in the String class.

By use of the valueOf() method of the String class we can do the following conversions:

  • Java int to string
  • Java long to string
  • java boolean to string
  • char to string java
  • float to string java
  • java double to string
  • convert char array to string

It returns a String type value. As we said it is the overload method in the String class and it can accept different types of values as a parameter. Let’s see the String valueof() in java example

String.valueOf(DataType value);
class ExampleValueOf
{  
  public static void main(String args[])
  {  
	int intValue = 1;
	float floatValue = 1.1f;
	double doubleValue = 1.2;
	char charValue = 'a';
	char charArray[] = {'J','A','V', 'A'};
	boolean booleanValue = true;
			
       System.out.println("Converting int to String = "+ String.valueOf(intValue));
       System.out.println("Converting float to String = "+ String.valueOf(floatValue));
       System.out.println("Converting double to String = "+ String.valueOf(doubleValue));
       System.out.println("Converting char to String = "+ String.valueOf(charValue));
       System.out.println("Converting char Array to String = "+ String.valueOf(charArray));
       System.out.println("Converting boolean  to String = "+ String.valueOf(booleanValue));
			
   }  
}  

Output:
Converting int to String = 1
Converting float to String = 1.1
Converting double to String = 1.2
Converting char to String = a
Converting char Array to String = JAVA
Converting boolean  to String = true

String join()

Before Java 8, the programmer faces the problem when they want to concatenate or join multiple strings by the delimiter. Because the programmer does this work by custom code, they have to write a loop structure to do this. This problem is resolved by Java String join() method.

But Java 8 provides two ways to resolve this problem. First, the StringJoiner class introduced in java 8 is used to join multiple strings another way is to use Java String join() method.
This method is also introduced in java 8. Let’s see the working of Java String join()

This method is used to join the delimiter with a string. This method returns a string joined with the given delimiter. You can join multiple strings with the same delimiter. The delimiter is copied for each string. The return type of join() is String. It returns the String joined with the given delimiter.

String.join(delimiter , string1, . . . stringN)

delimiter: The delimiter which you want to copy for each string. string1…stringN: The number of strings that you want to append to with delimiter.

class ExampleOfContains
 {  
	 public static void main(String args[])
	 {    
		String name = "JavaGoal";  			 
		String name1 = "Website";
		String name2 = "Learning";
		String name3 = "Website";
			 
		String joinedString = String.join(";", name, name1, name2, name3);
		System.out.println("Joined with delimiter = "+ (joinedString));
	}
}  

Output: Joined with delimiter = JavaGoal;Website;Learning;Website

String indexOf()

A string is an array of characters and each character gets stored in a specific index. The string indexOf() method is used to get the index of a particular character in the string. You can get the index of any character or substring by use of string indexof() java. It returns the number -1, if the given character or substring is doesn’t exist in the current string.

The indexOf() is an overloaded method in the String class. It has 4 types :

  1. indexOf(int characterName);
  2. indexOf(int characterName, int fromIndex);
  3. indexOf(String subStringName);
  4. indexOf(String subStringName, int fromIndex);

1. indexOf(int characterName)

This method accepts only one parameter. It returns the index value of the first occurrence of the specified character.

Important point: As you can see this method can accept the int parameter, but we can give it character also because it expects to encode the codepoint.

stringName.indexOf(int characterName)

stringName: The name of the string in which you want to find the index of a given character. characterName: Give the character whom position you want to find in the current string.

class ExampleOfIndexOf
 {  
	 public static void main(String args[])
	 {  
		String name = "JAVA WINGS";  
		int index = name.indexOf('V');
		System.out.println("The index of given character is = "+index);
	}
}  

Output: The index of given character is = 2

2. indexOf(int characterName, int fromIndex)

This method accepts two parameters. One parameter is the name of a character and another is the index to start the search. It returns the index value of the first occurrence of the specified character.

stringName.indexOf(int characterName, int fromIndex)

stringName: The name of the string in which you want to find the index of a given character.
characterName: Give the character whom position you want to find in the current string.
fromIndex: the index to start the search from

class ExampleOfIndexOf
{  
    public static void main(String args[])
    {  
 	String name = "JAVA WINGS";  
	int index = name.indexOf('A');
	System.out.println("The index of first occurrence of given character is = "+index);
			 
	int index1 = name.indexOf('A', 2);
	System.out.println("The index of character after the specified index for search = 
        "+index1);	
   }
}

Output: The index of first occurrence of given character is = 1
The index of character after the specified index for search = 3

3. indexOf(String subStringName)

This method accepts only one parameter. It returns the index value of the first occurrence of the specified substring.

stringName.indexOf(String subStringName)

stringName: The name of the string in which you want to find the index of the given substring.
subStringName: Give the subString whose position you want to find in the current string.

class ExampleOfIndexOf
{  
   public static void main(String args[])
   {  
	String name = "JAVA WINGS";  
	int index = name.indexOf("WING");
	System.out.println("The index of first occurnce of given subString is = "+index);	 
   }
}  

Output: The index of first occurrence of given subString is = 5

4. indexOf(String subStringName, int fromIndex)

This method accepts two parameters. One parameter is the name of the substring and another is the index to start the search. It returns the index value of the first occurrence of the specified substring.

stringName.indexOf(String subString, int fromIndex)

stringName: The name of the string in which you want to find the index of the given substring.
subStringName: Give the substring whose position you want to find in the current string.
fromIndex: the index to start the search from.

class ExampleOfIndexOf
{  
  public static void main(String args[])
  {  
	String name = "JAVA WINGS";  			 
	int index1 = name.indexOf("WINGS", 3);
        System.out.println("The index of character after the specified index for search = 
        "+index1);	
   }
}  

Output: The index of character after the specified index for search = 5

String lastIndexOf()

This string lastindexof() java is used to get the last index of the specified character. You can get the last index of any character or substring from a String. If the given character or substring doesn’t exist in the current string, then it returns -1. The return type of lastIndexOf() is int. It always returns an integer number. The lastIndexOf() is an overloaded method in the String class. Let’s see all the overload String lastIndexOf() Java.

  1. lastIndexOf(int characterName);
  2. lastIndexOf(int characterName, int fromIndex);
  3. lastIndexOf(String subStringName);
  4. lastIndexOf(String subStringName, int fromIndex);

1. lastIndexOf(int characterName)

This method accepts only one parameter. It returns the last index value of the specified character.

Important point: As you can see this method can accept the int parameter, but we can give it character also because it expects to encode the codepoint.

stringName.lastIndexOf(int characterName)

stringName: The name of the string in which you want to find the index of a given character.
characterName: Give the character whom position you want to find in the current string.

class ExampleOfLastIndexOf
 {  
	 public static void main(String args[])
	 {  
		String name = "JAVA WINGS";  
		int index = name.lastIndexOf('A');
		System.out.println("The last index of given character is = "+index);	
          }
}  

Output: The last index of given character is = 3

2. lastIndexOf(int characterName, int fromIndex)

This method accepts two parameters. One parameter is the name of the character and another is the index to start the search from. It returns the last index value of the specified character.

stringName.lastIndexOf(int characterName, int fromIndex)

stringName: The name of string in which you want to find the index of a given character.
characterName: Give the character whom position you want to find in the current string.
fromIndex: the index to start the search from.

class ExampleOfLastIndexOf
 {  
	 public static void main(String args[])
	 {  
		String name = "JAVA WINGS";  
		int index = name.lastIndexOf('A');
		System.out.println("The last index of given character is = "+index);
					 
		int index1 = name.indexOf('A', 4);
                System.out.println("The last index of character after the specified index 
                for search = "+index1);
         }
}  

Output: The last index of given character is = 3
The last index of character after the specified index for search = -1

3. lastIndexOf(String subStringName)

This method accepts only one parameter. It returns the last index value of the first occurrence of the specified substring.

stringName.lastIndexOf(String subStringName)

stringName: The name of the string in which you want to find the index of the given substring.
subStringName: Give the subString whose position you want to find in the current string.

class ExampleOfLastIndexOf
 {  
	 public static void main(String args[])
	 {  
		String name = "JAVA WINGS";  
		int index = name.lastIndexOf("WING");
		System.out.println("The last index of given subString is = "+index);	
         }
}  

Output: The last index of given subString is = 5

4. lastIndexOf(String subStringName, int fromIndex)

This method accepts two parameters. One parameter is the name of the substring and another is the index to start the search from. It returns the last index value of the specified substring.

stringName.lastIndexOf(String subString, int fromIndex)

stringName: The name of the string in which you want to find the index of the given substring.
subStringName: Give the substring whose position you want to find in the current string.
fromIndex: the index to start the search from.

class ExampleOfIndexOf
 {  
	 public static void main(String args[])
	 {  
		String name = "JAVA WINGS";  
		int index = name.lastIndexOf("WING", 2);
		System.out.println("The last index of given subString is = "+index);
	}
}  

Output: The last index of given subString is = -1

String getBytes()

This method uses to get the byte array of string. It returns the array of bytes. It has two variants of the String getBytes() method because it is an overloaded method in the String class.

1. String getBytes()

This method doesn’t take any argument. It uses the default charset to encode the string into bytes. Its return type is a byte array.

stringName.getBytes();

stringName: The string which you want to convert into a byte array.

class ExampleOfGetByte
 {  
	 public static void main(String args[])
	 {    
		String name = "JAVA WINGS";  
		// Convert the string "name" into byte array.
		 byte byteArray[] = name.getBytes();
		 for(int i = 0; i < byteArray.length ; i++)
		 System.out.println(byteArray[i]);	
          }
}  

Output:
74
65
86
65
32
87
73
78
71
83

2. String getBytes(String charsetName)

This method takes one argument.  This method accepts the name of the charset, according to which string must be encoded while converting into bytes. Here we have some charset names:

  • US-ASCII
  • ISO-8859-1
  • UTF-8
  • UTF-16BE
  • UTF-16LE
stringName.getBytes(charsetName);

stringName: The string which you want to convert into a byte array.
CharsteName: You must provide the name of the charset.

class ExampleOfGetChar
 {  
	 public static void main(String args[])
	 {    
		String name = "JAVA WINGS";  
		 // Convert the string "name" into byte array.
		 byte byteArray[];
		try 
		{
			byteArray = name.getBytes("UTF-16");
			for(int i = 0; i < byteArray.length ; i++)
			 System.out.println(byteArray[i]);
		} 
		catch (UnsupportedEncodingException e)
                {
			e.printStackTrace();
		}
             }
}  

Output:
-2
1
0
74
0
65
0
86
0
65
0
32
0
87
0
73
0
78
0
71
0
83

String getChar()

This method uses to copy the current string into a character array. You must provide the char array to the method in which you want to copy the content current string.

public void getChars(int srcStartIndex, int srcEndIndex, char[] destination, int dstStartIndex)  

This method doesn’t return anything, Its return type is void. This method takes four parameters we will discuss it.

int srcStartIndex: It is the start index value of the current string that we want to copy. It means the start index is the location of the first character in the string to copy.
int srcEndIndex: It is the end index value of the current string that we want to copy. It means the end index is the location of the last character in the string to copy.
char[] destination: char array
int dstStartIndex: It is the start index value of the char array(destination).

stringName.getChar(startIndex, endIndex, destinationArray, startDesinationIndex)
class ExampleOfGetChar
 {  
	 public static void main(String args[])
	 {    
		String name = "JAVA WINGS";  
		char nameArray[] = new char[6];
		// Copy the word JAVA in char array
		name.getChars(0, 4, nameArray, 0);
		System.out.println(nameArray);
		 
		// Copy the word WINGS in char array
		 name.getChars(5, 10, nameArray, 0);
		 System.out.println(nameArray); 
	}
}  

Output: JAVA
WINGS

String startsWith()

The string startswith in java or string startswith() uses to check the particular string starts from the given substring/string. The return type of string startswith() is boolean, It means the method returns true if the current string starts with suffix otherwise it returns false.
There are two variants of startswith() method:
1. String startsWith(String prefix) 2. String startsWith(String prefix, int startPosition)

1. String startsWith(String prefix)

The return type of startsWith(String prefix) is boolean. Returns only true or false values. If this method takes only one parameter, the specified string beginning from the 0th index(First character).

stringName.startsWith(anotherStringName)

stringName: The name of the string that we want to check whether it starts with the given String or not. anotherStringName:  It is a string that will be provided by the user to check whether the current string starts with the same string or not.

class ExampleOfStartsWith
{  
   public static void main(String args[])
   {    
	String string1 = "JAVA WINGS";  
	// It will returns true		
	System.out.println("Is Strings start with JAVA = "+ string1.startsWith("JAVA")); 
        // It will returns false
	System.out.println("Is Strings start with WINGS  = "+ string1.startsWith("WINGS")); 
        // It will returns true	
	System.out.println("Is Strings start with JA = "+ string1.startsWith("JA")); 
    }
} 

Output: Is Strings start with JAVA = true
Is Strings start with WINGS = false
Is Strings start with JA = true

2. String startsWith(String prefix, int startPosition)

The return type of startsWith(String prefix, int startPosition) is boolean. Returns only true or false values. It takes two parameters, One parameter is a string(prefix) and another is startPostion. It checks the current string starts with the given string(prefix) beginning at a specified startPosition.
Let’s discuss the string startswith in java

stringName.startsWith(anotherStringName, 2)

stringName: The name of the string which we want to check whether it starts with the given String or not
anotherStringName: It is a string that will be provided by a user to check whether the current string starts with the same string or not.

class ExampleOfStartsWith
{  
   public static void main(String args[])
   {    
     String string1 = "JAVA WINGS";  
     // It will returns false because JAVA start from index 0
     System.out.println("Is Strings start with JAVA = "+ string1.startsWith("JAVA", 2));   
     // It will returns true because WINGS start from index 5
     System.out.println("Is Strings start with WINGS  = "+ string1.startsWith("WINGS", 5));
     // It will returns true because JA start from index 0
     System.out.println("Is Strings start with JA = "+ string1.startsWith("JA", 0));	
  }
}  

Output: Is Strings start with JAVA = false
Is Strings start with WINGS = true
Is Strings start with JA = true

string endswith()

The String endsWith() method uses to check the current string ends with a given string. It means the method returns true if the current string ends with a suffix otherwise it returns false. The return type of endsWith() is boolean. It returns only true or false values. Let’s see how does String endsWith() method work?

stringName.endsWith(anotherStringName)

stringName: The name of the string that we want to check, whether it ends with the given String or not.
anotherStringName: It is a string that will be provided by a user to check whether the current string ends with the same string or not.

class ExampleOfEndsWith
{  
    public static void main(String args[])
    {    
	String string1 = "JAVA WINGS";  
        // It will returns true
	System.out.println("Is Strings ends with WINGS = "+ string1.endsWith("WINGS"));
	// It will returns false
	System.out.println("Is Strings ends with JAVA = "+ string1.endsWith("JAVA")); 
	// It will returns true
	System.out.println("Is Strings ends with NGS = "+ string1.endsWith("NGS")); 
     }
}  

Output: Is Strings ends with WINGS = true
Is Strings ends with JAVA = false
Is Strings ends with NGS = true

String equal()

In java, the equals() method is defined in the Object class and the String class is overriding the equals() method. In String class equals() method is used for String comparison in Java. We can compare two string by use of equals() method. It compares the values of string for equality. To get more details you can read string equals()

String equalsIgnoreCase()

You can compare two strings by using of equalsIgnoreCase() method. As you know java is case sensitive language and you want to ignore case-sensitive strings. You just want to compare the string value then you should use the equalsIgnoreCase(). It uses for String comparison in Java and its returns type is boolean. To get more details you can read string equalsIgnoreCase()

String contains()

This method uses to search the sequence of characters in a string. It means you can search for any number of characters. Even you can search for a single character or substring. If a sequence of characters finds then it returns true otherwise false. Let’s see how does Java string contains() method works?
The return type of String contains() is a boolean. It returns only true or false values.

stringName.contains(charSequence)

stringName: The name of the string in which you want to search the given character sequence.
charSequence: It is a sequence of characters. Basically, the String class implements the CharSequence interface.

An example of Java string contains()

class ExampleOfContains
{  
    public static void main(String args[])
    {    
 	String string1 = "JAVA GOAL"; 
        // It will returns true 
	System.out.println(string1.contains("GOAL")); 
        // It will returns false because JAVA is case sensitive.
	System.out.println(string1.contains("GOALS")); 
        // It will returns true
	System.out.println(string1.contains("VA")); 
        // It will returns true 
	System.out.println(string1.contains("J")); 
	}
}  

Output:
true
false
true
true

String charAt()

Sometimes, there are situations we want to get the character from a string. The Java String charAt() method uses to get the character.

By use of the charAt() method, we can get the character at the specified index. It gets the first occurrence of a character from the string so it uses when we want to get first character of string java. The index number should be between 0 to length-1. If the length does not lie between 0 to length-1 it will throw StringIndexOutOfBoundsException.

Java String charAt()

The return type of charAt() is char. Where char data type uses to store the characters.

stringName.chartAt(index)

stringName: The name of the string in which you want to find the character.
index: Index will be the position of the character in a string. It should be an integer from 0 to length-1.

class ExampleOfCharAt
{  
   public static void main(String args[])
   {  
	 String name = "JavaGoal";  
	 Char charAtPosition = name.charAt(3); //returns the char value at the 3th index  
	 System.out.println("The character present at index 3 is = " +charAtPosition);  
   }
} 

Output: The character present at index 3 is = a

StringIndexOutOfBoundsException with charAt()

The index should be an integer and it should be lies between 0 to length-1. If you will try to with any illegal index value it will throw an exception.

class PerformanceExample
 {  
    public static void main(String args[])
    {  
	 String name = "Java";  
	 char charAtPosition = name.charAt(5); //returns the char value at the 5th index  
	 System.out.println("The character present at index 5 is = " +charAtPosition);  
    }
}  

Output: Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47) at java.base/java.lang.String.charAt(String.java:693) at PerformanceExample.main(PerformanceExample.java:6)

String compareTo()

java compareTo method compares the strings. It compares the given string with the current string. This method compares the string, based on lexicographic. Lexicographic comparisons are like the ordering that one might find in a dictionary. The return type of compareTo() is int. It returns a positive, negative, or zero(0) value. To get more details you can read String compareTo()

Leave a Comment