Methods Of String Class In Java With Example

In this tutorial, we’ll talk about the Methods Of String Class In Java. These methods are very useful, and you’ll need to understand and learn them before you can use them in your own Java projects.

What Is String Class In Java

The String Class In Java handles character strings. All string literals in Java programs, like “abc”, are implemented as instances of this class. Strings can’t have their values changed once they’ve been created. String buffers can change strings. Since String objects are immutable, they can be shared.

Can We Extend String Class In Java

The String Class In Java Is Immutable it cannot be extended in any way, and none of its features can be overridden.

Python Tutorial 3 - Variable String
Python Tutorial 3 - Variable String

Without further ado, I will further Explain String Class In Java with some basic examples in order for you to easily understand the topic.

The String Class Methods In Java are collections of characters that are frequently used in Java programming. Strings are considered objects in the Java programming language.

For creating and manipulating strings, the Java platform offers the String class.

Creating Strings In Java

Writing a string is the simplest way see the example below.

String name = “Glenn Magada Azuelo”;

The compiler constructs a String object with the value “Glenn Magada Azuelo” whenever it sees a string literal in your code.

Methods Of String Class In Java can be created using the new keyword and a constructor, just like any other object. There are 11 constructors available for the String class, allowing you to initialize a string from a variety of sources, including an array of characters.

Strings In Java Example Program

public class StringDemo {

   public static void main(String args[]) {
      char[] nameArray = { 'G', 'l', 'e', 'n', 'n', '.' };
      String nameString = new String(nameArray);  
      System.out.println( nameString );
   }
}

This will result in the following.

Output

Glenn.

In order for you to test your Java code provided in this lesson, you must test the code in your code editor. But if you wish to run this code online, we also have an online compiler in Java for you to test your java code for free.

We also provide a Java Online Compiler for every code below. Just scroll down so that you can easily test or execute the source code.

Note -The String Class In Java Is Immutable it can’t be changed, so once a String object is made, it can’t be changed. String Buffer and String Builder Classes should be used when you need to make a lot of changes to strings of characters.

String Length In Java

The String Length In Java can be found with the length() method of the Java String class. The number of Unicode code units in a Java string is the same as the length of the string.

Accessor methods are ways of getting information about an object. The length() accessor method can be used with strings. It returns the number of characters in the string object.

The following program is an example of using the length() method of the String Class In Java.

String Length In Java Example Program

// program by Glenn Magada Azuelo
public class StringDemo {

   public static void main(String args[]) {
      String name = "Angel Jude Suarez Is Handsome";
      int len = name.length();
      System.out.println( "String Length is : " + len );
   }
}

This will result in the following.

Output

String Length is : 29

Concatenating Strings

There is a method in the String class for joining two strings together. This is called concatenating.

stringOne.concat(stringTwo);

This will return a new string, string1 with string2 added at the end. You can also use the concat () method in string literals, such as-.

“My name is “.concat(“Glenn Magada Azuelo”);

Most of the time, the + operator is used to concatenated strings, as in.

“Hello,” + ” Glenn” + “!”

result in.

“Hello, Glenn!”

Let’s look at the example below.

Concatenating Strings Example Program

// praogram by Glenn Magada Azuelo
public class StringDemo {

   public static void main(String args[]) {
      String stringOne = "Magada ";
      System.out.println("Glenn " + stringOne + "Azuelo");
   }
}

This will result in the following.

Output

Glenn Magada Azuelo

Creating Format Strings

The Strings format() method returns a formatted string using the given locale, specified format string, and arguments. Using this method, we can add the strings together and also change the way the resulting string looks.

There are two ways to print output with formatted numbers: printf() and format(). The String class has a similar method called format(), but instead of returning a PrintStream object, it returns a String object.

Using String’s static format() method, you can make a formatted string that you can use more than once. This is different from a print statement, which only works once. For example.

Format Strings Example

// Sample is created By Glenn
System.out.printf(“The value of the float variable is ” +
“%f, while the value of the integer ” +
“variable is %d, and the string ” +
“is %s”, floatVar1, intVar1, stringVar1);

You can make another sample.

// Sample Created By Glenn
String formatString;
formatString = String.format(“The value of the float variable is ” +
“%f, while the value of the integer ” +
“variable is %d, and the string ” +
“is %s”, floatVar1, intVar1, stringVar1);
System.out.println(formatString);

Methods Of String Class In Java

Here is a list of the methods that the String Class In Java can use.

#Method & Description
1char charAt(int index)
Returns the character at the specified index.
2int compareTo(Object o)
Compares this String to another Object.
3int compareTo(String anotherString)
Compares two strings lexicographically.
4int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
5String concat(String str)
Concatenates the specified string to the end of this string.
6boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
7static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
8static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
9boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
10boolean equals(Object anObject)
Compares this string to the specified object.
11boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
12byte[] getBytes()
Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.
13byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
14void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
15int hashCode()
Returns a hash code for this string.
16int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
17int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
18int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
19int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
20String intern()
Returns a canonical representation for the string object.
21int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
22int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
23int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
24int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
25int length()
Returns the length of this string.
26boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
27boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
28boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
29String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
30String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
31String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
32String[] split(String regex)
Splits this string around matches of the given regular expression.
33String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
34boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
35boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
36CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
37String substring(int beginIndex)
Returns a new string that is a substring of this string.
38String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
39char[] toCharArray()
Converts this string to a new character array.
40String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
41String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
42String toString()
This object (which is already a string!) is itself returned.
43String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
44String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
45String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
46static String valueOf(primitive data type x)
Returns the string representation of the passed data type argument.
Methods Of String Class In Java

Conclusion

In this article, we talked about the String Class In Java, including how they work, what they’re used for, and how this chapter can help you learn Java faster. This could be one of the best ways to improve your Java programming skills.

What’s Next

In the next section, we’ll talk about the Arrays. You will learn how to use Arrays and how this topic helps you a lot when building Java projects.


Leave a Comment