String Methods In Java

In this article, we will discuss the most commonly used Java string methods with examples.

In Java, strings are a commonly used data type and the String class offers a set of built-in methods to manipulate strings

Java String Methods



Java String Methods

The class String provides a collection of predefined methods that can be utilized to manipulate strings.

String MethodsOverviewReturn Type
charAt()Specifies a character position (index) and returns it.char
codePointAt()At the specified index, this function gives the Unicode of the characterint
codePointBefore()An Unicode representation of the character before the specified index is displayedint
codePointCount()Counts how many Unicode values are found in a string and displays the number.int
compareTo()Compares two strings alphabeticallyint
compareToIgnoreCase()Bypasses case differences when comparing two strings semanticallyint
concat()The append method attaches a string to the end of another stringString
contains()Detects the presence of a sequence of characters in a stringboolean
contentEquals()The function detects whether a string contains exactly the same sequence of characters as the CharSequence or StringBuffer specifiedboolean
copyValueOf()This method generates a String containing the characters in the character arrayString
endsWith()A string is checked to see if it ends with the desired character(s) being searchedboolean
equals()A comparison is made between two strings. The function returns true if the strings are equal, and false otherwise.boolean
equalsIgnoreCase()A comparison is performed between two strings irrespective of the caseboolean
format()Assigns the format string, locale, and arguments to a formatted stringString
getBytes()Makes use of the named charset to encode this String into a set of bytes, adding the result in a new byte arraybyte[]
getChars()Characters are duplicated from a string to a character arrayvoid
hashCode()This function generates the string’s hash codeint
indexOf()This function displays the first occurrence of a string of specified charactersint
intern()This function returns the string object’s standardized formString
isEmpty()A string is checked to see if it is empty or notboolean
lastIndexOf()In a string, this function returns the position of the latest appearance of the specified charactersint
length()String length is calculated as a result of a specified argumentint
matches()Using a regular expression, this function searches a string for matches and displays themboolean
offsetByCodePoints()This function gives the index within this String that is offset by the codePointOffset code points from the index given.int
regionMatches()A test to determine whether two string are identical or notboolean
replace()Returns a new string that replaces the specified values in a string based on a string search for a specified value.String
replaceFirst()Substrings that match the given regular expression are replaced with the given replacement at their first occurrence in the stringsString
replaceAll()This replaces all substrings of this string with the replacement given in the regular expression.String
split()Arrays of substrings are created by splitting a stringString[]
startsWith()A string is checked to see if it begins with the specified charactersboolean
subSequence()An arbitrary subsequence of the character sequence is presentedCharSequence
substring()Substrings of the specified string are generated as new stringsString
toCharArray()Creates a character array considering the given stringchar[]
toLowerCase()The function transforms a string to lowercase lettersString
toString()It returns the value of an object of type StringString
toUpperCase()A string is altered to upper case lettersString
trim()An end-to-end whitespace removal functionString
valueOf()This function generates a string corresponding to the specified valueString

Java String Method charAt()

Characters at specified indexes in a string are returned by the charAt() method.

The first character has an index of 0, the second character has an index 1, etc.

Syntax

public char charAt(int index)

Parameters

The index of the character to return is an int value.

The following program shows the index number of the letter J:

Example: 

public class Main { public static void main(String[] args) {String mrx="You are learning Java String Methods from Mr.Examples"; System.out.println("Character at index number 17 is: "+mrx.charAt(17)); } }

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("\nEnter String here: "); String mrx=input.nextLine();System.out.println("\nEnter Index Number of the Alphabet here: "); int ample= input.nextInt();System.out.println("—————————– Result ———————————–");System.out.println("\n Entered String: "+mrx); System.out.println(" Index Number entered: "+ample);System.out.println(" Character at index number ( "+ample+" ) is: "+mrx.charAt(ample));} }

Java String Method codePointAt()

A string containing the character at the specified index will be returned with the Unicode value using the codePointAt() method.

The first character has an index of 0, the second character has an index 1, etc.

Syntax

public int codePointAt(int index)

Parameters

index is an integer that takes the index number.

The following programme shows the Ascii code of the variable (e) as:

Example: 

public class Main { public static void main(String[] args) {String mrx="Greetings ! We are learning about the Ascii Code methods of Java String "; System.out.println("Character's Ascii code at index number 15 (e) is: "+mrx.codePointAt(15)); } }

Here the given programme shows the Ascii Code of any alphabet as per user’s input:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("\nEnter String here: "); String mrx=input.nextLine();System.out.println("\nEnter Index Number of the Alphabet here: "); int ample= input.nextInt();System.out.println("—————————– Ascii Code Calculator ———————————–");System.out.println("\n Entered String: "+mrx); System.out.println(" Index Number entered: "+ample);System.out.println(" Character's Ascii Code at index number ( "+ample+" ) is: "+mrx.codePointAt(ample));} }

Java String Method codePointBefore()

Using the codePointBefore() method, you can retrieve the Unicode value of the character before the specified index.

Initially, the first character is indexed as 0, then the second character is indexed as 1, and so on.

 

Important: If you enter the value 0, an error will occur, because it is a negative number (unreachable).

Parameters

A value of type int representing the Unicode index is displayed.

The following code shows the Ascii code of (M) which is 77:

Example: 

public class Main { public static void main(String[] args) {String ample="Mr. Examples";System.out.println("The Ascii Code of M before the specified index is given as: "+ample.codePointBefore(1)); } }

The following example shows the multiple working of method codePointBefore() :

Example: 

public class Main { public static void main(String[] args) {String mrx = "Mr."; String ample = "Examples";System.out.println("The Ascii Code of r is shown using the codePointBefore() method: " + mrx.codePointBefore(2)); System.out.println("The Ascii Code of x is shown using the codePointBefore() method: " + ample.codePointBefore(2)); } }

Java String Method codePointCount()

An array of Unicode values is counted using the codePointCount() method.

If you want to specify where to start the search and where to end it, you can use the startIndex and endIndex parameters.

As for the first character, its index is 0, then 1, then 2, etc.

Syntax

public int codePointCount(int startIndex, int endIndex)

Parameters

The startIndex is an integer value indicating where the string starts, the endIndex is an integer value indicating where the string ends.

The following example shows the unicodes of alphabets up to a range:

Example: 

public class Main { public static void main(String[] args) {String mrx_ample = "Hey User !! I hope you will be having fun learning String methods using the codePointCount() method: ";int result =mrx_ample.codePointCount(2,7);System.out.println("The Count of alphabets that contain the Unicode upto the range is shown as: " +result);} }

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter the String here: "); String mrx=input.nextLine();System.out.println("Enter Starting Index: "); int ample1=input.nextInt();System.out.println("Enter Ending Index: "); int ample2=input.nextInt(); System.out.println("\nThe Count of Alphabets having the Ascii Code from index "+ample1+" to "+ample2+" is: "+mrx.codePointCount(ample1,ample2));} }

Java String Method compareTo()

Comparing two strings alphabetically is the purpose of the compareTo() method.

Each character in the string is compared based on its Unicode value.

If the string equals the other string, the method returns 0.

If the string is shorter than the other string (fewer characters), a value less than 0 is returned; if the string is longer than the other string, a value greater than 0 is returned.

Hint: compareToIgnoreCase() compares two strings alphabetically ignoring lowercase and uppercase differences.
Tip: A string can be compared without taking Unicode values into account using the equals() method.

Syntax

public int compareTo(String mrx_string)
public int compareTo(Object object)

Parameters

String 2 represents the other string that needs to be compared with a text string

Object shows objects to be compared are represented by objects

The following programme shows the comparison of two strings:

Correspondingly, we can also compare two user given strings in the way given below:

Example: 

public class Main { public static void main(String[] args) {String mrx="You are learning string compareTo() method from Mr.Examples"; String ample="This string differs from the string given above hence 1 is returned";System.out.println("Result: "+mrx.compareTo(ample)); System.out.println("The Output of the Comparison will be greater than 0 as the both strings are distinct to each other and the second string is greater than the first ");} }

Correspondingly, we can also compare two user given strings in the way given below:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter First Sentence here: "); String mrx=input.nextLine();System.out.println("Enter Second Sentence here: "); String ample=input.nextLine();int result=mrx.compareTo(ample);if(result==0){ System.out.println("\nResult of Compare Method: "+result); System.out.println("\nBoth Strings are equal to each other in terms of all characters and length"); } else if(result>0){ System.out.println("\nResult of Compare Method: "+result); System.out.println("\nBoth Strings are distinct to each other and the length of Sentence one is more than the Sentence two"); } else{ System.out.println("\nResult of Compare Method: "+result); System.out.println("\nBoth Strings are distinct to each other and length of First Sentence is less than the Second Sentence"); } } }

Java String Method compareToIgnoreCase()

Using the compareToIgnoreCase() method, two strings can be compared lexicographically without taking lowercase or uppercase into account.

Characters in the string are compared using their Unicode values converted into lower case.

0 is returned if the strings are equal, regardless of case differences. If the string is shorter than another string (fewer characters), it is returned as a number less than 0, and if it is longer than another string, it is returned as a number greater than 0.

Syntax

public int compareToIgnoreCase(String my_string)

Parameters

my_string is used as a search string ignoring the case it string contains.

Example: 

public class Main { public static void main(String[] args) {String mrx="mrexamples"; String ample="MREXAMPLES";System.out.println("The value is: "+mrx.compareToIgnoreCase(ample));System.out.println("Gives Output as 0 because the Both strings are equal to each other irrespective of the case"); } }

The given programme takes two strings as user input and tells if they are equal or not irrespective of their case using the compareToIgnoreCase() method:

Example: 

import java.util.Scanner; public class Main { public static void main(String[] args) {Scanner my_input=new Scanner(System.in);System.out.println("Enter First String here: "); String mrx=my_input.nextLine();System.out.println("Enter Second String here: "); String ample=my_input.nextLine();int mrx_result=mrx.compareToIgnoreCase(ample);System.out.println("\n——————————— Result —————————————");if (mrx_result==0){ System.out.println("\nResult: "+mrx_result); System.out.println("\nThe both strings are equal to each other irrespective of their cases"); } else if (mrx_result>0){ System.out.println("\nResult: "+mrx_result); System.out.println("\nThe both strings are distinct and the string 1 is greater in length than string 2"); } else{ System.out.println("\nResult: "+mrx_result); System.out.println("\nThe both strings are distinct and the string 2 is greater in length than string 1"); } } }

Java String Method concat()

A string can be attached to another string using the concat() method.

Syntax

public String concat(String mrx_string)

Parameters

Here, mrx_string shows the string to be appended/joined with another string.

The following programme shows the concatenation of the strings mrx and ample :

Example: 

public class Main public static void main(String[] args) {String mrx="Mr."; String ample="Examples";String concat_string=mrx.concat(ample);System.out.println("String After Concatenation: "+concat_string);} }

The following programme shows the joining of two strings:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter String 1 here: "); String mrx=input.nextLine();System.out.println("Enter String 2 here: "); String ample=input.nextLine();String mrx_ample=mrx.concat(ample);System.out.println("\n String 1: "+mrx+"\n String 2: "+ample+"\n After concatenation : "+mrx_ample); } }

Java String Method contains()

A string contains() method checks whether a sequence of characters exists in a string or not.

If the characters exist, then true is returned, otherwise false is returned.

Syntax

public boolean contains(CharSequence mrx)

Parameters

CharSequence mrx searches for the characters in the string.

An interface named CharSequence is an interface that allows a readable sequence of char values, which is part of the java.lang package.
The given example shows the working of the contains() method:

Example: 

public class Main { public static void main(String[] args) {String mrx_string="Hey !! You are learning about contains() method included in Java String methods";System.out.println("\nDoes the String contains the sequence { contains() } ?"+"\nAnswer: "+mrx_string.contains("contains()")); System.out.println("\nDoes the String contains the sequence { included } ? "+"\nAnswer: "+mrx_string.contains("included")); System.out.println("\nDoes the String contains the sequence { Python } ? "+"\nAnswer: "+mrx_string.contains("python")); } }

Similarly, we can also check if a user input contains a specific sequence of characters:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input= new Scanner(System.in);System.out.println("Enter String here: "); String mrx=input.nextLine();System.out.println("Enter Sequence of Characters to be searched : "); CharSequence ample=input.nextLine();if(mrx.contains(ample)){ System.out.println("\nResult: The Following Sequence {"+ample+"} is a part of String"); } else{ System.out.println("\nResult: The Following Sequence {"+ample+"} does not belong to the corresponding String"); }} }

Java String Method contentEquals()

By calling contentEquals(), one can check if the contents of a string match those of a string or a string buffer.

The function returns true if the characters exist, and false otherwise.

Syntax

In the contentEquals() method, there are two methods available:

public boolean contentEquals(StringBuffer mrx)
public boolean contentEquals(CharSequence ample)

Parameters

StringBuffer mrx is the string to be searched for.
CharSequence ample contains a sequence of characters to be searched for in ample.

Java.lang contains the StringBuffer class, which is similar to the String class but allows modification.

Java.lang has an interface called CharSequence, which represents a sequence of char values.

The given programme shows the working of contentEquals() method:

Example: 

public class Main { public static void main(String[] args) {String mrx="Mr.Examples";System.out.println("\n--> Does the character sequence { Mr.Examples } a part of String ?"); System.out.println("Answer: "+mrx.contentEquals("Mr.Examples"));System.out.println("\n--> Does the character sequence { Mr. } a part of String ?"); System.out.println("Answer: "+mrx.contentEquals("Mr."));System.out.println("\n--> Does the character sequence { Examples } a part of String ?"); System.out.println("Answer: "+mrx.contentEquals("Examples")); } }

The following programme performs the same operation by using contentEquals() method to search an exact block of characters using user’s input:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input= new Scanner(System.in);System.out.println("Enter String here: "); String mrx=input.nextLine();System.out.println("Enter the exact group of Characters to be searched : "); CharSequence ample=input.nextLine();if(mrx.contentEquals(ample)){ System.out.println("\nResult: The Following Sequence {"+ample+"} is a part of String"); } else{ System.out.println("\nResult: The Following Sequence {"+ample+"} content does not belong to the corresponding String"); }} }

Java String Method copyValueOf()

Using the copyValueOf() method, you can obtain the characters of a char array as a String.

As a result, this method returns a new String array containing the characters copied from the previous array.

Syntax

public static String copyValueOf(char[] mrx, int ample, int count_mrx)

Parameters

The mrx consists of a character array.

The ample is an int value that represents the char array’s start index.

A count_mrx value represents the length of a character array as an int.

The given examples illustrates the copying of characters of a char array to a String:

Example: 

public class Main { public static void main(String[] args) {char mrx []={'M','R','.','E','X','A','M','P','L','E','S'}; String ample=""; ample=ample.copyValueOf(mrx,0,11); System.out.println(" After Successfully Copying the characters we get the new string as: "+ample); } }

We can also copy all characters from a char array by just using the char array name in the copyValueOf() method:

Example: 

public class Main { public static void main(String[] args) {char character[]={'J','A','V','A','-','S','T','R','I','N','G','-','M','E','T','H','O','D','S'}; String storing_mrx="";String copying_String=storing_mrx.copyValueOf(character);System.out.println("The String after successfully copying value of the Characters array is: "+copying_String); } }

Java String Method endsWith()

Using the endsWith() method, you can check whether a string ends with a specific character(s).

Hint: If you want to check if a string starts with an individual character(s), use the startsWith() method.

Syntax

public boolean endsWith(String mrx)

In this case, mrx represents a String that contains the character(s) to be checked for.

The following programme shows the analyzation of string whether it ends with a specific sequence or not:

Example: 

public class Main { public static void main(String[] args) {String mrx="Greetings Learner !! The topic of Discussion today is java string's endsWith() method";System.out.println("\n--> Does the String mrx Ends with od ?"); System.out.println("Answer: "+mrx.endsWith("od"));System.out.println("\n--> Does the String mrx Ends with method ?"); System.out.println("Answer: "+mrx.endsWith("method"));System.out.println("\n--> Does the String mrx Ends with string ?"); System.out.println("Answer: "+mrx.endsWith("string"));} }

The following programme takes string as a user input and tells if it ends with a sequence of characters:

Example: 

import java.util.Scanner; public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Any String here: "); String mrx=input.nextLine();System.out.println("Enter the sequence of the characters on which the given string terminates : "); String ample=input.nextLine();System.out.println("\n—————————————- Result ——————————————\n"); if(mrx.endsWith(ample)){ System.out.println("String Entered: "+mrx); System.out.println("Ends with Characters: "+ample);System.out.println("\n--> Matched !! the given String ends with:"+ample); } else{ System.out.println("String Entered: "+mrx); System.out.println("Not Matched !! the given String does not ends with the characters: "+ample);}} }

Java String Method startsWith()

Using startsWith(), you can check whether a string begins with the specified character or characters.

Advice: The endsWith() method is a convenient tool to check whether the string you are checking ends with the specified character(s).

Syntax

public boolean startsWith(String mrx)

Parameters

In this case, the mrx is simply a string containing the character(s) you want to check for.

The given examples checks whether the given String starts with different sequences of characters:

Example: 

public class Main { public static void main(String[] args) {String ample="The String startsWith() methods is used to check if the corresponding Strings starts with the specific sequence of characters";System.out.println("\n--> Does the String Ends with The ?"); System.out.println("Answer: "+ample.startsWith("The"));System.out.println("\n--> Does the String Ends with Th ?"); System.out.println("Answer: "+ample.startsWith("Th"));System.out.println("\n--> Does the String Ends with Mr. ?"); System.out.println("Answer: "+ample.startsWith("Mr.")); } }

Similarly, the following programme take one string as a user input and stores it, then takes another string input for the characters to be searched in the following string and returns the output as true or false:

Example: 

import java.util.Scanner; public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter Any String here: "); String mrx=input.nextLine();System.out.println("Enter the sequence of the characters on which the given string starts : "); String ample=input.nextLine();System.out.println("\n—————————————- Result ——————————————\n"); if(mrx.startsWith(ample)){ System.out.println("String Entered: "+mrx); System.out.println("Starts with Characters: "+ample);System.out.println("\n--> Matched !! the given String starts with: "+ample); } else{ System.out.println("String Entered: "+mrx); System.out.println("Not Matched !! the given String does not starts with the characters: "+ample);} } }

Java String Method equals()

In the equals() method, two strings are compared to see if they are the same and the output is returned as true. If they are not the same, then false is returned.

Advice: Using the compareTo() method is a reliable way of alphabetically comparing two strings.

Syntax

public boolean equals(Object mrx_String)

Parameters

Here mrx_String represents the second string to be compared with the first.

Example: 

public class Main { public static void main(String[] args) {String mrx="You are Learning About Java String method equals()"; String ample="You are Learning "; String ample1="You are Learning About Java"; String ample2="You are Learning About Java String"; String ample3="You are Learning About Java String method"; String ample4="You are Learning About Java String method equals()";System.out.println("\n-->Does mrx equals ample ??"); System.out.println("Answer: "+mrx.equals(ample));System.out.println("\n-->Does mrx equals ample1 ??"); System.out.println("Answer: "+mrx.equals(ample1));System.out.println("\n-->Does mrx equals ample2 ??"); System.out.println("Answer: "+mrx.equals(ample2));System.out.println("\n-->Does mrx equals ample3 ??"); System.out.println("Answer: "+mrx.equals(ample3));System.out.println("\n-->Does mrx equals ample4 ??"); System.out.println("Answer: "+mrx.equals(ample4)); } }

Correspondingly, the following programme takes two different strings as user input and shows if they are equal or not:

Example: 

import java.util.Scanner; public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter the String here: "); String ample=input.nextLine();System.out.println("Enter the String to be matched here: "); String mrx=input.nextLine();if(ample.equals(mrx)){ System.out.println("\nResult: Matched !! Both strings are equal"); } else{ System.out.println("\nResult: Not Matched !! Both Strings are distinct to each other"); }} }

Java String Method equalsIgnoreCase()

By using equalsIgnoreCase(), you can compare two strings regardless of whether they are lowercase or uppercase.

A true value is returned if the strings are equal, whereas a false value is returned if they are not.

Note: To compare two strings alphabetically, ignore case differences by using the compareToIgnoreCase() method.

Syntax

public boolean equalsIgnoreCase(String mrx_String)

Parameters

mrx_String is another string to be compared with the first string, regardless of the case it has.

The following example explains the working of the equalsIgnoreCase() method:

Example: 

public class Main { public static void main(String[] args) {String ample="The equalsIgnoreCase() method matches two strings character by character";String mrx="THE EQUALSIGNORECASE() METHOD MATCHES TWO STRINGS CHARACTER BY CHARACTER";System.out.println("\nString 1: "+ample); System.out.println("String 2: "+mrx);System.out.println("\n--> Does the Two Strings equals each other irrespective of their case: "); System.out.println("Answer: "+ample.equalsIgnoreCase(mrx)); } }

The programme given below takes two strings as user input and compares them alphabetically ignoring the case they are written in:

Example: 

import java.util.Scanner; public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter the String here: "); String ample=input.nextLine();System.out.println("Enter the string to be matched here having any word case: "); String mrx=input.nextLine();if(ample.equalsIgnoreCase(mrx)){ System.out.println("\nResult: Matched !! Both strings are equal having different word cases"); } else{ System.out.println("\nResult: Not Matched !! Both Strings are distinct to each other"); }} }

Java String Method hashCode()

Using the hashCode() method, you can obtain the string’s hashcode.

Here’s how the hash code of a String object is calculated:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

In this case, s[i] stands for a string’s ith character, n stands for its length, and ^ indicates exponentiation.

Syntax

public int hashCode()

Parameters

An integer value is returned as an output.

The following examples shows the hashcode of the string “Mr.Examples” :

Example: 

public class Main { public static void main(String[] args) {String mrx="Mr.Examples"; System.out.println("The Hashcode of the given string is: "+mrx.hashCode());} }

The following programme shows the calculation of Hashcode after taking input from user:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter String here: "); String mrx=input.nextLine();System.out.println("\n--> String :"+mrx); System.out.println("--> Hash Code of the String is: "+mrx.hashCode());} }

Java String Method isEmpty()

The isEmpty() method checks the existence of an empty string in a string property.

According to this method, if the string is empty (length() is zero), it returns true, if not, then it returns false.

Syntax

public boolean isEmpty()

The working of isEmpty() method can be explained by following the example below:

Example: 

public class Main { public static void main(String[] args) {String mrx=""; String ample="Mr.Examples";System.out.println("\n--> Is String mrx empty ?"); System.out.println("Answer: "+mrx.isEmpty());System.out.println("\n--> Is String ample empty ?"); System.out.println("Answer: "+ample.isEmpty());} }

Similarly, we can also check the isEmpty() method to check multiple Strings and user-defined string as well:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter String here: "); String mrx_ample=input.next();String mrx=""; String ample=" ";System.out.println("\n--> Is String "+mrx_ample+" empty ?"); System.out.println("Answer: "+mrx_ample.isEmpty());System.out.println("\n--> Is String mrx empty ?"); System.out.println("Answer: "+mrx.isEmpty());System.out.println("\n--> Is String ample empty ?"); System.out.println("Answer: "+ample.isEmpty()+". This shows that even spaces occupy some length in a string.");} }

Java String Method indexOf()

Using indexOf(), you can find where the first occurrence of the specified character(s) is within a string.

Advice: To find the last occurrence of a specified character(s) in a string, use the lastIndexOf() method.

Syntax

IndexOf() has four methods:

public int lastIndexOf(String mrx)
public int lastIndexOf(String mrx, int ample_start_index)
public int lastIndexOf(int ample)
public int lastIndexOf(int ample, int mrx_start_index)

Parameters

The mrx parameter represents the string to search for.

ample_start_search and mrx_start_search are both integer data types that represent the position in the index from where it can begin the search. In the absence of this parameter, the length of the string is used instead.

An ample represents a single character, such as ‘A’ or a Unicode value.

Here, we find the index of the word about :

Example: 

public class Main { public static void main(String[] args) { String mrx="Hello Learner !! We are discussing about the IndexOf() method"; System.out.println("The Index of about is: "+mrx.indexOf("about")); } }

Here is an example of how the same work can be done by taking an input from the user:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter String here: "); String ample=input.nextLine();System.out.println("Enter word whose Index number you want to find: "); String mrx=input.nextLine();System.out.println("\nThe Index of "+mrx+" in the string is: "+ample.indexOf(mrx));} }

The example below shows the Last Index of character d, while starting search from index number 2 :

Example: 

public class Main { public static void main(String[] args) {String mrx="Hello Learner !! We are discussing about the indexOf() method";System.out.println("The Index of d starting search from 7 is: "+mrx.indexOf('d',2)); } }

Java String Method lastIndexOf()

Using the lastIndexOf() method, you can find out where a given character(s) appeared last in a string.

Note: When the indexOf() method is called, it returns the first occurrence of a string’s specified character(s).

Syntax

The following four methods are available for lastIndexOf():

public int lastIndexOf(String mrx)
public int lastIndexOf(String mrx, int ample_start_index)
public int lastIndexOf(int ample)
public int lastIndexOf(int ample, int mrx_start_index)

Parameters

The mrx parameter represents the string to search for.

ample_start_search and mrx_start_search are both integer data types that represent the position in the index from where it can begin the search. In the absence of this parameter, the length of the string is used instead.

An ample represents a single character, such as ‘A’ or a Unicode value.

Here, we find the last index of the word about :

Example: 

public class Main { public static void main(String[] args) {String mrx="Hello Learner !! We are discussing about the LastIndexOf() method";System.out.println("The Last Index of about is: "+mrx.lastIndexOf("about"));} }

The same work could be done by taking an input from user, as shown below:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter String here: "); String ample=input.nextLine();System.out.println("Enter word whose last Index you want to find: "); String mrx=input.nextLine();System.out.println("\nThe last Index of "+mrx+" in the string is: "+ample.lastIndexOf(mrx));} }

The example below shows the Last Index of character e, while starting search from index number 7 :

Example: 

public class Main { public static void main(String[] args) {String mrx="Hello Learner !! We are discussing about the LastIndexOf() method";System.out.println("The Last Index of e starting search from 7 is: "+mrx.lastIndexOf('e',7));} }

Java String Method length()

Using the length() method, you can get the length of any string.

Remember: Empty strings have a length of 0.

Syntax

public int length()

The following example shows the length of a string containing numbers from 0 to 9:

Example: 

public class Main { public static void main(String[] args) {String mrx="0123456789";System.out.println("The length of the String "+mrx+" is: "+mrx.length());} }

We can also use user input to find the length of a string as shown below:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter String here: "); String mrx=input.nextLine();System.out.println("\n--> The length of the String { "+mrx+" } is: "+mrx.length()); } }

Java String Method replace()

Using replace(), you can replace a string with a new string containing the specified character(s) of the first string.

Syntax

public String replace(char mrx_search, char ample_new)

Parameters

mrx_search is a char that represents the character that is meant to replace the character that is currently in use.

An ample_new value is specified as a char, indicating the character that will be used to replace the mrx_search.

In order to better understand the String replace() method, have a look at the example below:

Example: 

public class Main { public static void main(String[] args) { String mrx="Mr.Examples"; System.out.println(mrx.replace('r','R')); } }

The following programme take inputs from user and replace the specified characters and displays the output accordingly:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter String here: "); String mrx=input.nextLine();System.out.println("Enter Character to replace here: "); String ample_1=input.next();System.out.println("Enter Character to be replaced here: "); String ample_2=input.next();System.out.println("\n——————– O U T P U T ——————————"); System.out.println("\n--> Original String: "+mrx); System.out.println("--> After Replacing "+ample_1+" with "+ample_2+" we get: "+mrx.replace(ample_1,ample_2)); } }

Java String Method toLowerCase()

Using the toLowerCase() method, one can convert a string from upper case letters to lower case letters.

Important: Strings are converted to upper case letters by the toUpperCase() method.

Syntax

public String toLowerCase()

The given example will guide you regarding the working of toLowerCase() method:

Example: 

public class Main { public static void main(String[] args) {String mrx=" THE STRING METHODS MAKE IT EASIER FOR THE USER TO PERFORM DIFFERENT OPERATIONS ON JAVA STRINGS ";System.out.println("\nCurrent String: "+mrx); System.out.println("\nAfter Converting to LowerCase: "+mrx.toLowerCase());} }

Correspondingly, we can do the same operation on string after taking input from the user. THe given example demonstrates the working :

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter String in UpperCase : "); String mrx=input.nextLine(); String upper_mrx=mrx.toUpperCase();System.out.println("\n—————————– R E S U L T ———————————");System.out.println("\n--> Before Changing case :"+upper_mrx); System.out.println("--> After Changing to Lowercase: "+mrx.toLowerCase());} }

Java String Method toUpperCase()

By calling toUpperCase(), you can convert a string into uppercase letters.

Note : By using the toLowerCase() method, we can convert a string to lowercase characters.

Syntax

public String toUpperCase()

The example given below shows the conversion of a String of lowercase letters to Uppercase letters:

Example: 

public class Main { public static void main(String[] args) {String mrx=" the string methods make it easier for the user to perform different operations on java strings ";System.out.println("\n--> Current String: "+mrx); System.out.println("\n--> After Converting to UpperCase: "+mrx.toUpperCase());} }

Accordingly, after receiving the user’s input, we can perform the same operation on the string. The following example illustrates how it works:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter String in LowerCase : "); String mrx=input.nextLine(); String lowerCase_mrx=mrx.toLowerCase();System.out.println("\n—————————– R E S U L T ———————————");System.out.println("\n--> Before Changing case : "+lowerCase_mrx); System.out.println("--> After Changing to Upper Case: "+mrx.toUpperCase());} }

Java String Method trim()

In the trim() method, whitespace is removed from both ends of a string.

Important: The original string will not be changed by this method.

Syntax

public String trim()

Here is an example of how to remove whitespace from both sides of a string:

Example: 

public class Main { public static void main(String[] args) {String mrx=" Since We have Covered All the methods from String Methods Java.I hope you would have found it easier and interesting. ";System.out.println("\n--> Original String: "+mrx); System.out.println("\n--> After Using the trim function: "+mrx.trim());} }

Correspondingly, here’s another example to demonstrate the working of trim() method in a easier way:

Example: 

public class Main { public static void main(String[] args) {String mrx=" Mr. Examples ";System.out.println("\n--> Original String: "+mrx); System.out.println("\n--> After Using the trim function: "+mrx.trim());} }

Java How To Count Words

Count Number of Words in a String

The following example can be used to easily count the number of words contained in a string:

Example: 

public class Main { public static void main(String[] args) {String mrx="You are learning Java Programming Language";int count_ample=mrx.split("\\s").length;System.out.println("There are "+count_ample+" words in the given string");} }

Correspondingly, if you want to find the count of words in a user entered string, you can refer to the example below:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input=new Scanner(System.in);System.out.println("Enter the String here : "); String mrx=input.nextLine();int count_ample=mrx.split("\\s").length;System.out.println("\n--> String: "+mrx);System.out.println("--> Count = There are "+count_ample+" words in the given string"); } }

Java How To Reverse a String

You can easily revert a string’ s characters one by one by following the steps below:

Example: 

public class Main { public static void main(String[] args) {String ample = "Hello Learner !! We are Learning how to reverse a String in Java"; String mrx_reversed = ""; for (int i = 0; i < ample.length(); i++) { mrx_reversed = ample.charAt(i) + mrx_reversed; } System.out.println("\n--> Before Reversing String : "+ample); System.out.println("\n--> Reversed string: "+ mrx_reversed);} }

Similarly, by taking an input from user we can also print the string in the reverted manner as shown in the example below:

Example: 

import java.util.Scanner;public class Main { public static void main(String[] args) {Scanner input= new Scanner(System.in);System.out.println("Enter Any String here: "); String mrx=input.nextLine();String ample_reversed="";for(int looping_element=0;looping_element<mrx.length();looping_element++){ample_reversed=mrx.charAt(looping_element)+ample_reversed; }System.out.println("\n--> User Input Before Reversing: "+mrx); System.out.println("\n--> After Reversing: "+ample_reversed);} }

 

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *