Java String Methods – You Need To Know

Java String charAt():

This method returns the character value for the particular index. The index number begins from 0 and ends at n-1, where n is the length of the string. In the case in which the given index is greater than or equal to the length of the string or is a negative number, then the method returns StringIndexOutOfBoundsException.

public class CharAtTest {

   public static void main(String args[]) {
      String st = "Java String";
      char result = s.charAt(10);
      System.out.println(result);
   }
}

Java String compareTo()

This method compares the values of the string lexicographically on the basis of the Unicode value of each character in the strings. It then returns an integer value that reports whether the string is greater than, equal to or less than the second string. When the first string is greater than the second string, it returns a positive number. It returns a negative number when the first string is less than the second string. In the case in which both the string are equal, the method returns 0.

public class CompareToDemo {
	public static void main(String args[]) {
		String st1 = "Hello";
		String st2 = "World";
		System.out.println(st1.compareTo(st2));
	}
}

Java String concat

The string concat() method creates a new string by concatenating a particular string to the end of the current string. It then returns the combined string.

public class ConcatTest {

	public static void main(String args[]) {
		String st = "Hello";
		st = st.concat(" World");
		System.out.println(st);
	}
}

Java String contains()

This method returns true when the sequence of characters values searched are found in the string otherwise it returns false.

class ContainsTest {
	public static void main(String args[]) {
		String name = "Hello";
		System.out.println(name.contains("World"));
		System.out.println(name.contains("Java"));
		System.out.println(name.contains("Community"));
	}
}

Java String endsWith()

This method returns true if the string ends with a specific suffix otherwise it returns false.

class EndsWithTest {
	public static void main(String args[]) {
		String St = new String("Hello World Java Community");
		boolean obj;

		obj = St.endsWith("Hello World");
		System.out.println("First value = " + obj);

		obj = St.endsWith("Hello");
		System.out.println("Second Value = " + obj);
	}
}

Java String equals()

This method makes a comparison between two strings on the basis of their contents. If all characters of both strings are same, it returns true otherwise it returns false. It overrides the equals() method of the object class.

class EqualsTest {
	public static void main(String args[]) {
		String s1 = "JavaFolder";
		String s2 = "JavaFolder";
		String s3 = "javafolder";
		String s4 = "JAVAFOLDER";
		System.out.println(s1.equals(s2));
		System.out.println(s1.equals(s3));
		System.out.println(s1.equals(s4));
	}
}

Java String equalsIgnoreCase()

This method performs the same function as the string equals() method and returns true if all characters of both strings match. However, this method only checks the content of the strings, not the case.

class EqualsIgnoreCaseTest {
public static void main(String[] args) {

		String st1 = "Hello";
		String st2 = "World";
		String st3 = "Hello World";

		boolean first = st2.equalsIgnoreCase(st1);
		boolean second = st2.equalsIgnoreCase(st3);

		System.out.println(first);
		System.out.println(second);
	}
}

Java String format()

This method returns the formatted string by a specific format, locale, and arguments. It is similar to the sprint() function in C language and the printf() method. The Locale.getDefault() method is called as a default, in the case in which the programmer does not specifies the locale in this method.

public class FormatTest {

	public static void main(String[] args) {

		String st = String.format("First: %1$d Second: %2$d Third: %3$d", 100, 200, 300);
		System.out.println(st);
	}
}

Java String getBytes()

This method returns the sequence of bytes of the string. In other words, it returns the byte array of the string.

public class GetBytesTest {

	public static void main(String[] args) {

		String st = "PQRSXYZ";
		byte[] bt = st.getBytes();
		for (int i = 0; i < bt.length; i++) {
			System.out.println(bt[i]);
		}
	}
}

Java String getChars()

This method does not return any value but copies the content of a string into a particular character array. This method passes four arguments and in the case in which beginIndex is greater than endIndex, the method gives out StringIndexOutOfBoundsException.

public class StringGetCharsTest {

	public static void main(String args[]) {

		String str = new String("Hello World");

		char[] obj = new char[10];
		try {
			str.getChars(3, 5, obj, 1);
			System.out.println(obj);
		} catch (Exception ex) {
			System.out.println(ex);
		}
	}

Java String indexOf()

This method returns an index of a specified char value or substring. The counter of index begins from 0 and the method returns -1 when the char value is not found in the string. The types of the indexOf method in Java are as follows:

  • int indexOf(int ch):

This method of the indexOf method returns the position of the index for a specific character value.

  • int indexOf(int ch, int fromIndex):

This method of the indexOf method returns the position of the index for a specific character value from the index.

  • int indexOf(String substring):

This method of the indexOf method returns the position of the index for a specific substring.

  • int indexOf(String substring, int fromIndex):

This method of the indexOf method returns the position of the index for a specific substring from the index.

public class IndexOfTest {
	
	public static void main(String args[]) {

		String st = "Hello Java World";
		int index1 = st.indexOf("Java");
		int index2 = st.indexOf("World");

		System.out.println(index1 + "  " + index2);
	}
}

Java String intern()

This method returns the canonical representation of the string or the interned string.  When the method is created by using a new keyword, it returns a string from the memory. It can also be used to create a copy of heap string object in string constant pool.

public class InternTest {
	
	public static void main(String args[]) {
		
		String st1 = new String("Hello World");
		String st2 = "Hello";
		String st3 = st1.intern();
		System.out.println(st1 == st2);
		System.out.println(st2 == st3);
	}
}

Java String isEmpty()

This method returns true if the length of the string is empty or 0 and returns false in other cases. This method was added in the Java string from JDK 1.6.

public class IsEmptyExampleTest {

	public static void main(String args[]) {
		String st1 = "JavaFolder";
		String st2 = "";

		System.out.println(st1.isEmpty());
		System.out.println(st2.isEmpty());
	}
}

Java String join()

This method returns a string joined with a specific delimiter. The delimiter is copied for all elements and null is added for the null elements. This method was added in the Java string from JDK 1.8.

public class StringJoinTest {

	public static void main(String args[]) {

		String str = String.join("-", "Hello","Java", "World");

		System.out.println(str);
	}
}

Java String lastIndexOf()

This method returns the last index of a specific char value of substring. The counter of index begins from 0 like the indexOf() method and the method also returns -1 when the char value is not found in the string. The types of the lastIndexOf method in Java are as follows:

  • int lastIndexOf(int ch):

This method of the lastIndexOf method returns the position of the last index for a specific character value.

  • int lastIndexOf(int ch, int fromIndex):

This method of the lastIndexOf method returns the position of the last index for a specific character value from the index.

  • int lastIndexOf(String substring):

This method of the lastIndexOf method returns the position of the last index for a specific substring.

  • int lastIndexOf(String substring, int fromIndex):

This method of the lastIndexOf method returns the position of the last index for a specific substring from the index.

public class LastIndexOfTest {

	public static void main(String args[]) {

		String st1 = "Hello Java World";

		int obj = st1.lastIndexOf('J');

		System.out.println(obj);
	}
}

Java String length()

This method returns the total number of character present in the string. The length of a Java string is exactly same as the Unicode units of it.

public class LengthTest {

	public static void main(String args[]) {

		String st1 = "HelloJava";
		String st2 = "World";
		System.out.println("string length: " + st1.length());
		System.out.println("string length : " + st2.length());
	}
}

Java String replace()

This method returns a new string after replacing all the previous character of a string with new characters. This method was added from the JDK 1.5 to make the replacing of characters of a string easier.

public class ReplaceTest {

	public static void main(String args[]) {

		String st1 = "Welcome to JavaFolder";

		System.out.println("Before replace : " +st1);

		String replaceString = st1.replace('W', 'e');
		System.out.println(replaceString);
	}
}

Java String replaceAll()

This method returns a new string after replacing all the characters matching regex with a new sequence of characters.

public class ReplaceAllTest {

	public static void main(String args[]) {

		String st1 = "Welcome to JavaFolder";

		System.out.println("Before replace : " + st1);

		String st2 = st1.replaceAll(st1, "HelloWorld");

		System.out.println("After replace: " + st2);
	}
}

Java String split()

This method returns a character array after splitting a particular string with a specific regular expression. This method was added from the JDK 1.4.

public class SplitTest {

	public static void main(String args[]) {
		String str1 = "HelloWorld";
		String[] str2 = str1.split("H", 2);

		for (String st : str2)
			System.out.println(st);
	}
}

Java String startsWith()

This method returns true if the string begins with a specified prefix and returns false if not.

public class StartsWithTest {

	public static void main(String args[]) {

		String s1 = "Hello World";

		System.out.println(s1.startsWith("He"));

		System.out.println(s1.startsWith("Hello"));
	}
}

Java String substring()

This method returns a substring. The substring can either be passed from the beginning index which is 0 or from the ending index which is 1. There are further two types of methods using to return substring.

public class SubstringTest {

	public static void main(String args[]) {

		String s1 = "HelloWorld";

		System.out.println(s1.substring(2, 7));
		System.out.println(s1.substring(0));
	}
}

Java String toCharArray()

This method returns a newly created char array after converting a string. The length of the char is equal to the string from which it is created and the contents are initialized from the characters of the string.

public class StringToCharArrayTest {

	public static void main(String args[]) {

		String st1 = "HelloWorld";
		char[] obj = st1.toCharArray();

		for (int i = 0; i < obj.length; i++) {
			System.out.print(obj[i]);
		}
	}
}

Java String toLowerCase()

This method returns a new string after converting all the characters of a specific string into lowercase letters. The function of this method is similar to the function of the toLowerCase(Locale.getDefault()) method.

public class ToLowerCaseTest {

	public static void main(String args[]) {

		String st1 = "HELLOWORLD"; 
		System.out.println(st1.toLowerCase());
		}
	}

Java String toUpperCase()

This method returns a new string after converting all the characters of a specific string into uppercase letters. The function of this method is similar to the function of the toUpperCase(Locale.getDefault()) method.

public class ToUpperCaseTest {

	public static void main(String args[]) {

		String st1 = "helloworld"; 
		System.out.println(st1.toUpperCase());
		}
	}

Java String trim()

This method removes the unnecessary spaces in a string that is leading and trailing spaces. It returns a new string after removing the spaces that are found by checking the Unicode value of the string.

public class TrimTest {
	public static void main(String[] args) {

		String st1 = "  hello java World  ";
		System.out.println(st1.length());
		System.out.println("Before trim: " + st1);
		String st = st1.trim();
		System.out.println(st.length());
		System.out.println("After trim: " + st);
	}
}

Java String valueOf()

This method converts different values into a string such as an int to string, object to a string, long to string, float to a string, character to a string, boolean to string, double to a string, and char array to string.

public class StringValueOfTest {

	public static void main(String args[]) {

		int value = 100;

		String st = String.valueOf(value);

		System.out.println(st + 0);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *