Table of contents
1.
Introduction
2.
What is String?
2.1.
Implementation:
2.2.
Java
3.
Common Java String methods
3.1.
toUpperCase() and toLowerCase() String method
3.1.1.
Implementation
3.2.
Java
3.3.
trim() String method
3.3.1.
Implementation
3.4.
Java
3.5.
startsWith() and endsWith() String method
3.5.1.
Implementation
3.6.
Java
3.7.
charAt() String method
3.7.1.
Implementation
3.8.
Java
3.9.
length() String method
3.9.1.
Implementation  
3.10.
Java
3.11.
intern() String method
3.11.1.
Implementation
3.12.
Java
3.13.
valueOf() String method
3.13.1.
Implementation
3.14.
Java
3.15.
replace() String method
3.15.1.
Implementation  
3.16.
Java
4.
Other Java String methods
5.
Frequently Asked Questions
5.1.
What is a string method in Java?
5.2.
What is string class with example?
5.3.
What is exploring string class in Java?
6.
Conclusion
Last Updated: Nov 9, 2024
Easy

String Class Methods

Author Aditi
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The java.lang.String class in Java has a multitude of built-in methods for manipulating strings. We may execute actions on String objects using these methods, such as cutting, concatenating, converting, comparing, and replacing strings. In this blog, we'll go through the String class and methods in-depth and various additional Java String methods.

String Class Methods

Also see, Duck Number in Java and Hashcode Method in Java.

What is String?

A string is a collection of characters; for example, "String" is a six-character string. A string is an immutable object in Java, implying it is constant and cannot be modified once generated. Program example given below displays how to create strings in multiple ways.

Implementation:

  • Java

Java

public class Example{  
  public static void main(String args[]){ 
   //creating a string by java string literal
   String s1 = "CodingNinjas";
   char chArr[]={'s', 't', 'r', 'i', 'n', 'g'};
   //converting char array chArr[] to string s2
   String s2 = new String(chArr);
     
   //creating java string by using the new keyword
   String s3 = new String("Example of Java String");
     
   //Displaying all the three strings
   System.out.println(s1); 
   System.out.println(s2); 
   System.out.println(s3); 
  }
}
You can also try this code with Online Java Compiler
Run Code

Output:

CodingNinjas
string
Example of Java String

Also see, Swap Function in Java

Common Java String methods

Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

Check this out, Solid Principles in java

toUpperCase() and toLowerCase() String method

This String is converted to an uppercase letter using the Java String toUpperCase() method and a lowercase letter using the String toLowerCase() method.

Implementation

  • Java

Java

public class Stringoperation1  

   public static void main(String args[]) 
   { 
       String str="CodingNinjas";   
       System.out.println(str.toUpperCase());//CODINGNINJAS   
       System.out.println(str.toLowerCase());//codingninjas   
       System.out.println(str);//CodingNinjas(no change)   
   } 
}
You can also try this code with Online Java Compiler
Run Code

Output:

CODINGNINJAS
codingninjas
CodingNinjas

trim() String method

The trim() function of the String class removes white spaces before and after the String and returns the substring.

Implementation

  • Java

Java

public class Stringoperation2  

   public static void main(String args[]) 
   { 
       String str="  CodingNinjas  ";   
       System.out.println(str);//  CodingNinjas     
       System.out.println(str.trim());//CodingNinjas   
   } 
}
You can also try this code with Online Java Compiler
Run Code

Output:

CodingNinjas  
CodingNinjas

startsWith() and endsWith() String method

The function startsWith() determines if the String begins with the letters supplied as arguments and finishes with the letters passed as arguments. The endsWith() function determines if the String contains the letters provided as parameters.

Implementation

  • Java

Java

public class Stringoperation3  

   public static void main(String args[]) 
   { 
       String str="CodingNinjas";   
       System.out.println(str.startsWith("Co"));//true   
       System.out.println(str.endsWith("s"));//true
       System.out.println(str.endsWith("g"));//false 
   } 
}
You can also try this code with Online Java Compiler
Run Code

Output:

true
true
false

charAt() String method

The charAt() function of the String class returns a character at the provided index. The specified index value must be in the range of 0 to length() -1, inclusive. If index >= length of String, it raises IndexOutOfBoundsException.

Implementation

  • Java

Java

public class Stringoperation4  

   public static void main(String args[]) 
   { 
       String str="CodingNinjas";   
       System.out.println(str.charAt(0));//C   
       System.out.println(str.charAt(6));//N   
   } 
}
You can also try this code with Online Java Compiler
Run Code


Output:

C
N

length() String method

The length() function of the String class returns the length of the provided String.

Implementation  

  • Java

Java

public class Stringoperation5  

   public static void main(String args[]) 
   { 
       String str="CodingNinjas";   
       System.out.println(str.length());//12   
   } 
}
You can also try this code with Online Java Compiler
Run Code

Output:

12
You can also try this code with Online Java Compiler
Run Code

intern() String method

The class String keeps a private pool of strings that is initially empty. If the pool already has a String equal to this String object as determined by the equals(Object) function, the String from the pool is returned when the intern method is called. Otherwise, a reference to this String object is returned, and this String object is added to the pool.

Implementation

  • Java

Java

public class Stringoperation6  

   public static void main(String args[]) 
   { 
       String str=new String("CodingNinjas");   
       String str2=str.intern();   
       System.out.println(str2);//CodingNinjas   
   } 
}
You can also try this code with Online Java Compiler
Run Code

Output:

CodingNinjas

valueOf() String method

The String class's function valueOf() function converts any type into String, including int, long, float, double, boolean, char, and char array.

Implementation

  • Java

Java

public class Stringoperation7  

   public static void main(String args[]) 
   { 
       int x=20;   
       String str=String.valueOf(x);   
       System.out.println(str+10);   
   } 
}
You can also try this code with Online Java Compiler
Run Code

Output:

2010

replace() String method

The replace() function of the String class replaces all occurrences of the first sequence of characters with the second sequence of characters.

Implementation  

  • Java

Java

public class Stringoperation8  

   public static void main(String args[]) 
   { 
       String str="C++ is a programming language. C++ is a platform. C++ is an Island.";     
       String replaceStr=str.replace("C++","Java");//replaces all occurrences of "C++" to "Java"     
       System.out.println(replaceStr);   
   } 
}
You can also try this code with Online Java Compiler
Run Code

Output:

Java is a programming language. Java is a platform. Java is an Island.

 

You can also read about the topic of Java Destructor

Must Read:  String Args in Java

Other Java String methods

  • boolean equals(Object obj): If the String and the supplied string match, true is returned; otherwise, false.
  • boolean equalsIgnoreCase(String string): It operates in the same way as the equals method, except it doesn't consider the case when comparing strings. It performs a case-insensitive analysis.
  • int compareTo(String string): The Unicode value of each character in the strings is used to compare the two strings.
  • int compareToIgnoreCase(String string): It's the same as the CompareTo method, but it ignores the case while comparing.
  • boolean startsWith(String prefix, int offset): It determines whether or not the substring (beginning at the supplied offset index) has the specified prefix.
  • int hashCode(): It returns the String's hashcode.
  • int indexOf(int ch): Returns the position in the String where the provided character ch appears for the first time.
  • int indexOf(int ch, int fromIndex): It works in the same way as indexOf, except it starts searching in the text from the supplied fromIndex.
  • int lastIndexOf(int ch): It returns the String's last occurrence of the character ch.
  • int lastIndexOf(int ch, int fromIndex): It starts searching from fromIndex, much as the lastIndexOf(int ch) function.
  • int indexOf(String str): The index of the first occurrence of the supplied substring str is returned by this method.
  • int lastindexOf(String str): Returns the index of the string str's latest occurrence.
  • String substring(int beginIndex): It gives you the String's substring. The character in the supplied index is the first character in the substring.
  • String substring(int beginIndex, int endIndex): The substring is returned. At beginIndex, the substring begins with a character and ends with the character at endIndex.
  • String concat(String str): At the end of the String, concatenates the provided string "str."
  • boolean contains(CharSequence s): It determines if the String has the supplied char value sequence. If yes, it returns true; otherwise, it returns false. When 's' is null, it raises a NullPointerException.
  • public boolean isEmpty(): If the provided String has no length, this function returns true. It returns false if the length of the provided Java String is greater than zero.
  • public static String join(): This method combines the provided texts using the specified delimiter and returns a Java String that has been concatenated.
  • String replaceFirst(String regex, String replacement): It substitutes the provided replacement string for the first occurrence of a substring that matches the given regular expression "regex."
  • String replaceAll(String regex, String replacement): It uses the replacement string to replace all occurrences of substrings that match the regular expression regex.
  • String[] split(String regex, int limit): It breaks the String into substrings and produces an array that matches the regular expression. Here, the limit is a result threshold.
  • String[] split(String regex): The split(String regex, int limit) function is similar to the split(String regex, int limit), except it does not contain a threshold limit.
  • public static String format(): This function produces a formatted Java String.
  • char[] toCharArray(): The string is converted to a character array.
  • static String copyValueOf(char[] data): It returns a string containing the characters from the character array supplied.
  • static String copyValueOf(char[] data, int offset, int count): The same procedure as before, but with two additional arguments: the subarray's beginning offset and length.
  • void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): The characters from the src array are copied to the dest array. Only the provided range (from srcBegin to srcEnd) is transferred to the dest subarray (starting from destBegin).
  • boolean contentEquals(StringBuffer sb): It compares the String to the string buffer that has been supplied.
  • boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the input substring to the given String's substring.
  • boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variant of the regionMatches function, this time with an additional boolean argument to determine whether the comparison is case sensitive or case insensitive.
  • byte[] getBytes(String charsetName): It transforms a String to a series of bytes using the provided charset encoding and returns the array of bytes as a result.
  • byte[] getBytes(): This function is identical to the last one, only it converts the String into a series of bytes using the default charset encoding.
  • boolean matches(String regex): It determines whether the String matches the regular expression regex that has been supplied.
  • int codePointAt(int index): It's identical to the charAt method, except instead of returning the character, it returns the Unicode code point value of the supplied index.

Must Read Array of Objects in Java

Frequently Asked Questions

What is a string method in Java?

A string method in Java refers to built-in functions provided by the String class to manipulate and perform operations on string objects, like length(), substring(), etc.

What is string class with example?

The String class in Java represents a sequence of characters. Example:

String greeting = "Hello";  

What is exploring string class in Java?

Exploring the String class in Java involves understanding its methods and properties for manipulating strings, such as concatenation, comparison, and extraction.

Conclusion

In this article, we discussed the String class in Java, which provides a robust array of methods for manipulating and querying text. These methods, from basic string operations like concatenation and substring to more complex functions like matches and replace, are integral for effective text processing in Java. Accessible through the default `java.lang` package, they are essential tools for any Java developer, which enhances both the functionality and versatility of string handling.

We hope this blog has helped you enhance your knowledge regarding the string class methods. If you would like to learn more, check out our articles on Understanding StringsStrings Operations, and String Interview Questions In Java.

Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Live masterclass