Java String Methods

Java 8Object Oriented ProgrammingProgramming

String class has a lot of methods in Java to manipulate strings, finding length, format strings, concatenate, etc.

Following are some of the string methods in Java −

Sr.NoMethod & 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.

Example

Here, we will find the length of strings and concatenate them −

public class Main {
   public static void main(String args[]) {
      String str1 = "This is ";
      String str2 = "it!";
      System.out.println("String1 = "+str1);
      System.out.println("String2 = "+str2);
      int len1 = str1.length();
      System.out.println( "String1 Length = " + len1 );
      int len2 = str2.length();
      System.out.println( "String2 Length = " + len2 );
      System.out.println("Performing Concatenation...");
      System.out.println(str1 + str2);
   }
}

Output

String1 = This is
String2 = it!
String1 Length = 8
String2 Length = 3
Performing Concatenation...
This is it!

Let us see another example wherein we are comparing this string to the specified object −

Example

import java.util.*;
public class Demo {
   public static void main( String args[] ) {
      String Str1 = new String("This is really not immutable!!");
      String Str2 = Str1;
      String Str3 = new String("This is really not immutable!!");
      boolean retVal;
      retVal = Str1.equals( Str2 );
      System.out.println("Returned Value = " + retVal );
      retVal = Str1.equals( Str3 );
      System.out.println("Returned Value = " + retVal );
   }
}

Output

Returned Value = true
Returned Value = true
raja
Published on 24-Sep-2019 08:05:12
Advertisements