Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
String
3.
Common Java String methods
3.1.
toUpperCase() and toLowerCase() String method
3.2.
trim() String method
3.3.
startsWith() and endsWith() String method
3.4.
charAt() String method
3.5.
length() String method
3.6.
intern() String method
3.7.
valueOf() String method
3.8.
replace() String method
4.
Other Java String methods
5.
Frequently Asked Questions
5.1.
What do you mean by String in Java?
5.2.
What is the difference between String, StringBuffer, and StringBuilder?
5.3.
What do you mean by class in Java?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

String Class Methods

Author Aditi
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

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.

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

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.

Program:

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);  
   }
}

 

Output:

CodingNinjas
string
Example of Java String

Also see, Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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.

Program:

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)    
    }  
}

 

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.

Program:

public class Stringoperation2  
{  
    public static void main(String args[])  
    {  
        String str="  CodingNinjas  ";    
        System.out.println(str);//  CodingNinjas      
        System.out.println(str.trim());//CodingNinjas    
    }  
}

 

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.

Program:

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  
    }  
}

 

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.

Program:

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    
    }  
}


Output:

C
N

length() String method

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

Program:

public class Stringoperation5  
{  
    public static void main(String args[])  
    {  
        String str="CodingNinjas";    
        System.out.println(str.length());//12    
    }  
}  

 

Output:

12

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.

Program:

public class Stringoperation6  
{  
    public static void main(String args[])  
    {  
        String str=new String("CodingNinjas");    
        String str2=str.intern();    
        System.out.println(str2);//CodingNinjas    
    }  
}

 

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.

Program:

public class Stringoperation7  
{  
    public static void main(String args[])  
    {  
        int x=20;    
        String str=String.valueOf(x);    
        System.out.println(str+10);    
    }  
}

 

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.

Program:

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);    
    }  
}  

 

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 do you mean by String in Java?

In Java, a string is a collection of char values represented as an object. An array of characters functions similarly to a Java string. Java strings are immutable.

 

What is the difference between String, StringBuffer, and StringBuilder?

Strings are regarded as objects in the Java programming language. String is a Java platform class that allows you to construct and manipulate strings. String objects are immutable, but StringBuffer and StringBuilder objects are mutable. StringBuffer and StringBuilder are comparable; however for a single-threaded programme, StringBuilder is favored over StringBuffer.

 

What do you mean by class in Java?

In the Java programming language, a class is a template for creating objects and defining their data types and actions. Classes are groups of things, and objects are the things that make up each group. The essential class attributes should be present in all class objects.

Conclusion

In this article, we have extensively discussed the string class methods of the java programming language.

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.

Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
String Concatenation
Next article
Strings vs StringBuffer
Live masterclass