A Guide to Java String Class

A Java String represents an immutable sequence of characters and cannot be changed once created. Strings are of type java.lang.String class. In this page, learn about creating strings with string literal and constructors, string methods and various strings examples related to string conversion and formatting.

1. Create String in Java

There are two ways to create a String in Java.

  1. String literal

    String literals are most easy and recommended way to create strings in Java. In this way, simply assign the characters in double quotes to variable of java.lang.String type.

    String blogName = "howtodoinjava.com";
    String welcomeMessage = "Hello World !!";

    String literals are stored in String pool, a special memory area created by JVM. There can be only one instance of one String. Any second String with same character sequence will have the reference of first string stored in string pool. It makes efficient to work with Strings and saves lots of physical memory in runtime.

    String blogName1 = "howtodoinjava.com";
    String blogName2 = "howtodoinjava.com";
    String blogName3 = "howtodoinjava.com";
    String blogName4 = "howtodoinjava.com";
    String blogName5 = "howtodoinjava.com";

    In above example, we created 5 string literals with same char sequence. Inside JVM, there will be only one instance of String inside string pool. All rest 4 instances will share the reference of string literal created for first literal.

  2. String object

    At times, we may wish to create separate instance for each separate string in memory. We can create one string object per string value using new keyword.

    String objects created using new keyword – are stored in heap memory.

    String blogName1 = new String("howtodoinjava.com");
    String blogName2 = new String("howtodoinjava.com");
    String blogName3 = new String("howtodoinjava.com");

    In above example, there will be 3 separate instances of String with same value in heap memory.

2. Java String Methods

  1. char charAt(int index) – Returns the character at the specified index. Specified index value should be between '0' to 'length() -1' both inclusive. It throws IndexOutOfBoundsException if index is invalid/ out of range.
    String blogName = "howtodoinjava.com";
    char c = blogName.charAt(5);	//'d'
  2. boolean equals(Object obj) – Compares the string with the specified string and returns true if both matches else false.
    String blogName = "howtodoinjava.com";
    blogName.equals( "howtodoinjava.com" );		//true
    blogName.equals( "example.com" );			//false
  3. boolean equalsIgnoreCase(String string) – Compares same as equals method but in case insensitive way.
    String blogName = "howtodoinjava.com";
    blogName.equalsIgnoreCase( "howtodoinjava.com" );		//true
    blogName.equalsIgnoreCase( "HowToDoInJava.com" );		//true
  4. int compareTo(String string) – Compares the two strings lexicographically based on the Unicode value of each character in the strings. You can consider it dictionary based comparison.

    The return value is 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

    String blogName = "howtodoinjava.com";
    blogName.compareTo( "HowToDoInJava.com" );		//32
    blogName.compareTo( "example.com" );			//3
  5. int compareToIgnoreCase(String string) – Same as CompareTo method however it ignores the case during comparison.
    String blogName = "howtodoinjava.com";
    blogName.compareToIgnoreCase( "HowToDoInJava.com" );		//0
    blogName.compareToIgnoreCase( "example.com" );				//3
  6. boolean startsWith(String prefix, int offset) – Checks whether the String is having the specified prefix or not – starting from the specified offset index.
    String blogName = "howtodoinjava.com";
    blogName.startsWith( "d", 5 );		//true
    blogName.startsWith( "e", 5 );		//false
  7. boolean startsWith(String prefix) – Tests whether the string is having specified prefix, if yes then it returns true else false. The offset index value is 0 in this overloaded method.
    String blogName = "howtodoinjava.com";
    blogName.startsWith( "h" );		//true
    blogName.startsWith( "e" );		//false
  8. boolean endsWith(String suffix) – Checks whether the string ends with the specified suffix.
    String blogName = "howtodoinjava.com";
    blogName.endsWith( "com" );			//true
    blogName.endsWith( "java" );		//false
  9. int hashCode() – Returns the hash code of the string.
    String blogName = "howtodoinjava.com";
    blogName.hashCode();			//1894145264
  10. int indexOf(int ch) – Returns the index of first occurrence of the specified character argument in the string.
    String blogName = "howtodoinjava.com";
    blogName.indexOf( 'o' );			//1
  11. int indexOf(int ch, int fromIndex) – Overloaded version of indexOf(char ch) method however it starts searching in the string from the specified fromIndex.
    String blogName = "howtodoinjava.com";
    blogName.indexOf( 'o', 5 );		//6
  12. int indexOf(String str) – Returns the index of first occurrence of specified substring 'str'.
    String blogName = "howtodoinjava.com";
    blogName.indexOf( "java" );			//9
  13. int indexOf(String str, int fromIndex) – Overloaded version of indexOf(String str) method however it starts searching in the string from the specified fromIndex.
    String blogName = "howtodoinjava.com";
    blogName.indexOf( "java" , 5);			//9
  14. int lastIndexOf(int ch) – Returns the last occurrence of the character 'ch' in the string.
    String blogName = "howtodoinjava.com";
    blogName.lastIndexOf( 'o' );			//15
  15. int lastIndexOf(int ch, int fromIndex) – Overloaded version of lastIndexOf(int ch) method. It starts searching backward starting at the fromIndex.
    String blogName = "howtodoinjava.com";
    blogName.lastIndexOf( 'o', 5 );			//4
  16. int lastIndexOf(String str) – Returns the index of last occurrence of string 'str'. It is similar to lastIndexOf(int ch).
    String blogName = "howtodoinjava.com";
    blogName.lastIndexOf( "java" );			//9
  17. int lastIndexOf(String str, int fromIndex) – Overloaded version of lastIndexOf(String str) method. It starts searching backward starting at the fromIndex.
    String blogName = "howtodoinjava.com";
    blogName.lastIndexOf( "java", 6 );			//9
  18. String substring(int beginIndex) – Returns the substring of the string. The substring starts with the character at the specified index.
    String blogName = "howtodoinjava.com";
    blogName.substring( 7 );		//injava.com
  19. String substring(int beginIndex, int endIndex) – Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
    String blogName = "howtodoinjava.com";
    blogName.substring( 7, 9 );		//in
  20. String concat(String str) – Concatenates the specified string argument at the end of the string.
    String blogName = "howtodoinjava.com";
    blogName.concat( " Hello Visitor !!" );		//howtodoinjava.com Hello Visitor !!
  21. String replace(char oldChar, char newChar) – Returns the new updated string after changing all the occurrences of oldChar with the newChar arguments.
    String blogName = "howtodoinjava.com";
    blogName.replace( 'o', 'O' );		//hOwtOdOinjava.cOm
  22. String replace(String target, String replacement) – Returns the new updated string after changing all the occurrences of target with the replacement argument.
    String blogName = "howtodoinjava.com";
    blogName.replace( "com", "COM" );		//howtodoinjava.COM
  23. String replaceFirst(String regex, String replacement) – Replaces the first occurrence of substring that matches the given regular expression argument with the specified replacement string.
    String blogName = "howtodoinjava.com";
    blogName.replaceFirst("how", "HOW");		//HOWtodoinjava.com
  24. String replaceAll(String regex, String replacement) – Replaces all the occurrences of substrings that matches the regular expression argument with the replacement string.
  25. String[] split(String regex, int limit) – Splits the string and returns the array of sub-strings that matches the given regular expression. 'limit' is a maximum number of elements in array.
    String blogName = "howtodoinjava.com";
    blogName.split("o", 3);		//[h, wt, doinjava.com]
  26. String[] split(String regex) – Overload of previous method without any threshold limit.
  27. boolean contains(CharSequence s) – Checks whether the string contains the specified sequence of char values. If yes then it returns true else false. It throws NullPointerException if argument is null.
    String blogName = "howtodoinjava.com";
    blogName.contains( "java" );		//true
    blogName.contains( "python" );		//false
  28. String toUpperCase(Locale locale) – Converts the string to upper case string using the rules defined by specified locale.
    String blogName = "howtodoinjava.com";
    blogName.toUpperCase( Locale.getDefault() );		//HOWTODOINJAVA.COM
  29. String toUpperCase() – Overloaded version of previous toUpperCase() method with default locale.
  30. String toLowerCase(Locale locale) – Converts the string to lower case string using the rules defined by given locale.
  31. String toLowerCase() – Overloaded version of previous method with default locale.
  32. String intern() – Searches the specified string in the memory pool and if it is found then it returns the reference of it. Otherwise this method allocates creates string literal in string pool and return the reference.
  33. boolean isEmpty() – Returns true if the given string has 0 length else returns false.
    String blogName = "howtodoinjava.com";
    blogName.isEmpty();		//false
    "".isEmpty();			//true
  34. static String join() – Joins the given strings using the specified delimiter and returns the concatenated Java String literal.
    String.join("-", "how","to", "do", "in", "java")		//how-to-do-in-java
  35. static String format() – Returns a formatted string.
  36. String trim() – Removes leading and trailing white spaces from the Java string.
  37. char[] toCharArray() – Converts the string to a character array.
  38. static String copyValueOf(char[] data) – Returns a string that contains the characters of the specified character array.
    char[] chars = new char[] {'h','o','w'};
    String.copyValueOf(chars);		//how
  39. byte[] getBytes(String charsetName) – Converts the String into sequence of bytes using the specified charset encoding.
  40. byte[] getBytes() – Overloaded version of previous method. It uses the default charset encoding.
  41. int length() – Returns the length of a String.
  42. boolean matches(String regex) – Validates whether the String is matching with the specified regular expression argument.
  43. int codePointAt(int index) – It is similar to the charAt() method. It returns the Unicode code point value of specified index rather than the character itself.
  44. static String copyValueOf(char[] data, int offset, int count) – Overloaded version of previous method with two extra arguments – initial offset of subarray and length of subarray. It selects characters from array based on extra arguments,and then create the string.
  45. void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin) – Copies the characters of src array to the dest array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
  46. static String valueOf() – Returns a string representation of passed arguments such as int, long, float, double, char and char array.
  47. boolean contentEquals(StringBuffer sb) – Compares the string to the specified string buffer.
  48. boolean regionMatches(int srcoffset, String dest, int destoffset, int len) – Compares the substring of input to the substring of specified string.
  49. boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len) – Another variation of regionMatches method with the extra boolean argument to specify whether the comparison is case sensitive or case insensitive.

3. String Conversion Examples

  1. Convert Java String to int
  2. Convert int to String in Java
  3. Convert String to Long
  4. Convert Long to String in Java
  5. Convert String to Date
  6. Convert Date to String
  7. Convert String to String[] Example
  8. Java 8 – Join String Array – Convert Array to String
  9. Convert String to InputStream Example
  10. Convert InputStream to String Example
  11. Java Split CSV String – Convert String to List Example
  12. Join CSV to String
  13. Unescape HTML to String Example
  14. Escape HTML – Encode String to HTML Example
  15. Convert byte array to String
  16. StackTrace to String conversion
  17. Convert float to String – Format to N decimal points

4. Useful String Examples

  1. Reverse a String in Java using Recursion
  2. Remove extra white spaces between words
  3. Remove only leading spaces of a String
  4. Remove only trailing spaces of a String
  5. How to Reverse String in Java
  6. Reverse words in a string in Java
  7. Reverse string in Java using recursion
  8. How to find duplicate words in String
  9. How to find duplicate characters in a String
  10. Java Sort String Characters Alphabetically
  11. Convert String to Title Case
  12. 4 ways to split a String
  13. Left, right, or center align string
  14. Read File to String
  15. Java 8 StringJoiner Example
  16. Left pad a string with spaces or zeros
  17. Right pad a string with spaces or zeros
  18. Get first 4 characters of a string
  19. Get last 4 characters of a string
  20. Format string to (123) 456-7890 pattern

5. FAQs

  1. Always Use length() Instead of equals() to Check Empty String
  2. Why String is immutable
  3. Java String Interview Questions

6. References

String Java Doc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.