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.
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.
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
- char charAt(int index) – Returns the character at the specified index. Specified index value should be between
'0'
to'length() -1'
both inclusive. It throwsIndexOutOfBoundsException
if index is invalid/ out of range.String blogName = "howtodoinjava.com"; char c = blogName.charAt(5); //'d'
- 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
- 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
- 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
- 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
- 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
- boolean startsWith(String prefix) – Tests whether the string is having specified
prefix
, if yes then it returnstrue
elsefalse
. The offset index value is 0 in this overloaded method.String blogName = "howtodoinjava.com"; blogName.startsWith( "h" ); //true blogName.startsWith( "e" ); //false
- 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
- int hashCode() – Returns the hash code of the string.
String blogName = "howtodoinjava.com"; blogName.hashCode(); //1894145264
- 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
- int indexOf(int ch, int fromIndex) – Overloaded version of
indexOf(char ch)
method however it starts searching in the string from the specifiedfromIndex
.String blogName = "howtodoinjava.com"; blogName.indexOf( 'o', 5 ); //6
- int indexOf(String str) – Returns the index of first occurrence of specified substring
'str'
.String blogName = "howtodoinjava.com"; blogName.indexOf( "java" ); //9
- int indexOf(String str, int fromIndex) – Overloaded version of
indexOf(String str)
method however it starts searching in the string from the specifiedfromIndex
.String blogName = "howtodoinjava.com"; blogName.indexOf( "java" , 5); //9
- int lastIndexOf(int ch) – Returns the last occurrence of the character
'ch'
in the string.String blogName = "howtodoinjava.com"; blogName.lastIndexOf( 'o' ); //15
- int lastIndexOf(int ch, int fromIndex) – Overloaded version of
lastIndexOf(int ch)
method. It starts searching backward starting at thefromIndex
.String blogName = "howtodoinjava.com"; blogName.lastIndexOf( 'o', 5 ); //4
- int lastIndexOf(String str) – Returns the index of last occurrence of string
'str'
. It is similar tolastIndexOf(int ch)
.String blogName = "howtodoinjava.com"; blogName.lastIndexOf( "java" ); //9
- int lastIndexOf(String str, int fromIndex) – Overloaded version of
lastIndexOf(String str)
method. It starts searching backward starting at thefromIndex
.String blogName = "howtodoinjava.com"; blogName.lastIndexOf( "java", 6 ); //9
- 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
- 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
- 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 !!
- 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
- String replace(String target, String replacement) – Returns the new updated string after changing all the occurrences of
target
with thereplacement
argument.String blogName = "howtodoinjava.com"; blogName.replace( "com", "COM" ); //howtodoinjava.COM
- 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
- String replaceAll(String regex, String replacement) – Replaces all the occurrences of substrings that matches the regular expression argument with the replacement string.
- 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]
- String[] split(String regex) – Overload of previous method without any threshold limit.
- boolean contains(CharSequence s) – Checks whether the string contains the specified sequence of char values. If yes then it returns
true
elsefalse
. It throws NullPointerException if argument is null.String blogName = "howtodoinjava.com"; blogName.contains( "java" ); //true blogName.contains( "python" ); //false
- 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
- String toUpperCase() – Overloaded version of previous
toUpperCase()
method with default locale. - String toLowerCase(Locale locale) – Converts the string to lower case string using the rules defined by given locale.
- String toLowerCase() – Overloaded version of previous method with default locale.
- 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.
- boolean isEmpty() – Returns
true
if the given string has 0 length else returns false.String blogName = "howtodoinjava.com"; blogName.isEmpty(); //false "".isEmpty(); //true
- 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
- static String format() – Returns a formatted string.
- String trim() – Removes leading and trailing white spaces from the Java string.
- char[] toCharArray() – Converts the string to a character array.
- 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
- byte[] getBytes(String charsetName) – Converts the String into sequence of bytes using the specified charset encoding.
- byte[] getBytes() – Overloaded version of previous method. It uses the default charset encoding.
- int length() – Returns the length of a String.
- boolean matches(String regex) – Validates whether the String is matching with the specified regular expression argument.
- 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. - 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.
- 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).
- static String valueOf() – Returns a string representation of passed arguments such as int, long, float, double, char and char array.
- boolean contentEquals(StringBuffer sb) – Compares the string to the specified string buffer.
- boolean regionMatches(int srcoffset, String dest, int destoffset, int len) – Compares the substring of input to the substring of specified string.
- 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
- Convert Java String to int
- Convert int to String in Java
- Convert String to Long
- Convert Long to String in Java
- Convert String to Date
- Convert Date to String
- Convert String to String[] Example
- Java 8 – Join String Array – Convert Array to String
- Convert String to InputStream Example
- Convert InputStream to String Example
- Java Split CSV String – Convert String to List Example
- Join CSV to String
- Unescape HTML to String Example
- Escape HTML – Encode String to HTML Example
- Convert byte array to String
- StackTrace to String conversion
- Convert float to String – Format to N decimal points
4. Useful String Examples
- Reverse a String in Java using Recursion
- Remove extra white spaces between words
- Remove only leading spaces of a String
- Remove only trailing spaces of a String
- How to Reverse String in Java
- Reverse words in a string in Java
- Reverse string in Java using recursion
- How to find duplicate words in String
- How to find duplicate characters in a String
- Java Sort String Characters Alphabetically
- Convert String to Title Case
- 4 ways to split a String
- Left, right, or center align string
- Read File to String
- Java 8 StringJoiner Example
- Left pad a string with spaces or zeros
- Right pad a string with spaces or zeros
- Get first 4 characters of a string
- Get last 4 characters of a string
- Format string to (123) 456-7890 pattern
5. FAQs
- Always Use length() Instead of equals() to Check Empty String
- Why String is immutable
- Java String Interview Questions