Java String Class Methods with Examples

A fundamental class in the Java programming language that represents a string of characters is called a String. Since it is a component of the java.lang package, your Java code doesn’t need to explicitly import it because it is always available.

You can alter and operate with strings using a wide variety of methods available in the String class. These techniques can be divided into a number of groups, including:

Methods for manipulating strings: These techniques let you combine strings together, extract substrings, and change the case of a string. concat(), substring(), toupperCase(), and tolowerCase() are a few examples.

Java.lang is used Numerous built-in methods in Java’s String class are available for manipulating strings. We may do a number of actions on String objects using these methods, such as cutting, concatenating, converting, comparing, and replacing strings.

When you submit any form in a window-based, web-based, or mobile application, everything is handled as a String, which makes Java String a powerful concept.

Let’s use a few of the String class’s key methods.

The methods toUpperCase() and toLowerCase() for Java strings

This String is converted into uppercase letters using the Java String toUpperCase() method and lowercase letters using the Java String toLowerCase() method.

Essentially objects that represent lists of char values, strings in Java are. Comparable in operation to a Java string is a character array.

For illustration:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};  
s = new String (ch); equivalent to
String s="javatpoint";

There are many ways to work with strings in the Java String class, including compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), and substring().

 

toUpperCase and toLowerCase

Interface for CharSequence

The CharSequence interface is used to represent the group of characters. The String, StringBuffer, and StringBuilder classes are responsible for implementing it. This indicates that we can create strings in Java using these three types.

Interface for CharSequence

Example:

public class str1{
 public static void main(String args[]){
 
   String s="TechVidvan";
   System.out.println(s.toUpperCase());
   System.out.println(s.toLowerCase());
   System.out.println(s);
 }
}

Output:
JAVA
Java
Java

Java string trim() method

White spaces before and after the String are removed using the trim() function of the String class.

Example:

public class Stringoperation2  
{  
public static void main(String ar[])  
{  
String s="  TechVidvan ";    
System.out.println(s);    
System.out.println(s.trim());   
}  
}

Output:
Techvidvan
Techvidvan

General Operations performed on String:

Here are a few string principles you should be familiar with:

Concatenation of Strings in Java

Multiple strings are connected using the concatenation technique.  

Find string:

Finding a specific item inside a given full string is a very simple operation carried out on strings. This can be used to locate a specific character within a string or to locate an entire string within another string.

Find string

a) Find a character in a string:

Find the first location of a character in a string: You are given a string and a character. Your objective is to find the character’s position in the string. Locating the position of the character in a string is a very competitive programming issue of this type.

b) Locate a substring within a different string:

Assume a substring of length M exists within a string of length N.

Run a nested loop after that, with the inner loop running from 0 to M and the outer loop from 0 to (N-M). Verify whether the inner loop’s traversed sub-string corresponds to the given sub-string at each index.

Change to String

It is frequently crucial to make modifications to strings. Another highly frequent operation on strings is to replace a character, word, or phrase.

The simplest way to tackle the given problem is to iterate through the string S, replacing any instance where S1 appears as a substring with S2 when found. To solve this issue, adhere to the methods listed below:

Create a string from scratch and then replace every instance of the substrings S1 to S2 in the string S with the new string.

Utilizing the variable i, iterate through the characters of the string S and take the following actions:

Add the string S2 to the string ans if the prefix substring of the string S matches S1 from the index i.

A new character should be added to the string, and if not.

Print the string ans as the outcome after completing the aforementioned procedures.

Finding the Length of String

Finding the length or size of a given string is one of the most common operations on a String. The length of a string is determined by how many characters are included in it.

Finding the Length of String

Palindrome string

When a string’s reverse is the same as the original, it is referred to as a palindrome.

For instance,

Palindrome “abba” exists, while “abbc” does not.

There are two ways to create strings in Java:

An exact string:

Using the new keyword, “GeeksforGeeks” is in the string s, which is then converted to a new String.

1. Java’s String(byte[, byte_arr]) constructor

Decode the byte array to produce a new String. It uses the platform’s default character set to decode.

Example:

byte[] b_arr = 71, 101, 101, 107, and 115;
s_byte as a string = new String(b_arr); //Geeks

2. String(Charset char_set, Byte[] byte_arr)

In order to create a new String, decode the byte array, it decodes using the char_set.

Example:

Charset cs = Charset.default; Byte[] b_arr = "71, 101, 101, 107, 115"String s_byte_char = new String(b_arr, cs); Charset();

3. String(char_set_name, byte[] byte_arr,

In order to create a new String, decode the byte array, it decodes using the char_set_name. It appears similar.

Benefits of string:

Text Processing: In programming languages, text is represented by strings. They can be used to search, replace, parse, and format text, among other text manipulation and processing operations.

Strings can be used to represent several forms of data, including numbers, dates, and times. For instance, a string can be used to represent a time in the format “HH:MM:SS” or a date in the format “YYYY-MM-DD”.

Strings are a common data type in all computer languages due to their compatibility. As a result, strings are a dependable and effective way to communicate and share data because they can be easily moved between various systems and platforms.

Memory Efficiency: Strings are easy to allocate and deallocate since they are frequently kept in contiguous blocks of memory. Because they don’t use much memory, they can be used to represent vast amounts of data.

Negative aspects of string:

Memory Usage: Working with large or numerous strings might cause strings to use up a lot of memory. In memory-constrained settings like embedded systems or mobile devices, this may be an issue.

Immutability: Strings can never be modified once they have been produced in many computer languages. This might cause inefficiencies and memory costs when working with large or complex strings that call for frequent alterations.

Performance Overhead: When working with lengthy or intricate strings, string operations may take longer than operations on other data types. This is due to the fact that string operations frequently require copying and memory reallocation, both of which take time.

Method Description Return Type
charAt() returns the character located at the requested place (index). char
codePointAt() gives the character at the given index’s Unicode. int
codePointBefore() gives the character preceding the given index’s Unicode. int
codePointCount() gives the number of Unicode values that were located in the string. int

Example program:

public class Demo {
    public static void main(String[] args) {   
        String str = "studytonight";
        System.out.println(str.charAt(2));
    }
}

Length method:

public class Demo {
    public static void main(String[] args) {   
        String str = "Count me";
        System.out.println(str.length());
    }
}

Format method:

public class Demo {
    public static void main(String[] args) {
        String a1 = String.format("%d", 125);            
        String a2 = String.format("%s", "studytonight");  
        String a3 = String.format("%f", 125.00);        
        String a4 = String.format("%x", 125);            
        String a5 = String.format("%c", 'a');  
        System.out.println("Integer Value: "+a1);  
        System.out.println("String Value: "+a2);  
        System.out.println("Float Value: "+a3);  
        System.out.println("Hexadecimal Value: "+a4);  
        System.out.println("Char Value: "+a5);  
    }
}
Output:

Integer Value: 125 
String Value: studytonight 
Float Value: 125.000000 
hexadecimal Value: 7d
 Char Value: a

Output:

Integer Value: 125
String Value: studytonight
Float Value: 125.000000
hexadecimal Value: 7d
Char Value: a

Conclusion

In conclusion, the Java String class, which offers a complete range of methods for working with strings, is a vital and adaptable part of the Java programming language. The String class provides a wide range of features to satisfy your needs, whether you need to modify, compare, search, or format text data. It is necessary for tasks in Java applications that involve text processing, data validation, and user interaction.

The immutability of String objects, which means that any operation that seems to modify a string really creates a new string object, is an important concept to keep in mind. Thread safety is ensured by this immutability, which also has ramifications for memory management and performance issues.

Java developers can effectively handle strings by knowing the methods and tricks provided by the String class.