Java String Tutorial
A String in Java represents an immutable sequence of characters and cannot be changed
once created. Strings are of type java.lang.String class.
1. Creating a New String
There are two ways to create a String in Java.
1.1. String Literal
String literals are the easiest and most recommended way to create strings in Java.
In this way, simply assign the characters in double quotes to the variable
of java.lang.String type.
String literals are always created in String Constant Pool for performance reasons.
String blogName = "howtodoinjava.com";
String welcomeMessage = "Hello World !!";
1.2. String Object
At times, we may wish to create separate instances 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.
In the following example, there will be 3 separate instances of String with same value in
heap memory.
String blogName1 = new String("howtodoinjava.com");
String blogName2 = new String("howtodoinjava.com");
String blogName3 = new String("howtodoinjava.com");
2. String Methods
char charAt(int index) – Returns the character at the specified index. The specified index
value should be between '0' to 'length() -1' both inclusive. It
throws IndexOutOfBoundsException if index is invalid/ out of range.
boolean equals(Object obj) – Compares the string with the specified string and
returns true if both match else false.
boolean equalsIgnoreCase(String string) – Compares same as equals method but in
case-insensitive way.
int compareTo(String string) – Compares the two strings lexicographically based on the
Unicode value of each character in the strings. You can consider it a 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.
int compareToIgnoreCase(String string) – Same as CompareTo method however it
ignores the case during comparison.
boolean startsWith(String prefix, int offset) – Checks whether the String has the specified
prefix or not – starting from the specified offset index.
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.
boolean endsWith(String suffix) – Checks whether the string ends with the specified
suffix.
int hashCode() – Returns the hash code of the string.
int indexOf(int ch) – Returns the index of first occurrence of the specified character
argument in the string.
int indexOf(int ch, int fromIndex) – Overloaded version of indexOf(char ch) method
however it starts searching in the string from the specified fromIndex.
int indexOf(String str) – Returns the index of first occurrence of specified substring 'str'.
int indexOf(String str, int fromIndex) – Overloaded version of indexOf(String
str) method however it starts searching in the string from the specified fromIndex.
int lastIndexOf(int ch) – Returns the last occurrence of the character 'ch' in the string.
int lastIndexOf(int ch, int fromIndex) – Overloaded version of lastIndexOf(int
ch) method. It starts searching backward starting at the fromIndex.
int lastIndexOf(String str) – Returns the index of last occurrence of string 'str'. It is
similar to lastIndexOf(int ch).
int lastIndexOf(String str, int fromIndex) – Overloaded version of lastIndexOf(String
str) method. It starts searching backward starting at the fromIndex.
String substring(int beginIndex) – Returns the substring of the string. The substring
starts with the character at the specified index.
String substring(int beginIndex, int endIndex) – Returns the substring. The substring
starts with character at beginIndex and ends with the character at endIndex.
String concat(String str) – Concatenates the specified string argument at the end of the
string.
String replace(char oldChar, char newChar) – Returns the new updated string after
changing all the occurrences of oldChar with the newChar arguments.
String replace(String target, String replacement) – Returns the new updated string after
changing all the occurrences of target with the replacement argument.
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 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[] 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 else false. It
throws NullPointerException if argument is null.
String toUpperCase(Locale locale) – Converts the string to upper case string using the
rules defined by specified locale.
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 returns its
reference if it is found. 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.
static String join() – Joins the given strings using the specified delimiter and returns the
concatenated Java String literal.
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.
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() – Compares the substring of input to the substring of
specified string.
boolean regionMatches() – Another variation of regionMatches method with the extra
boolean argument to specify whether the comparison is case sensitive or case
insensitive.
3. Conversions
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 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
Mask a String Except Last 4 Chars
Format string to (123) 456-7890 pattern
Removing Last Character from String
5. FAQs
Why String is immutable
Java String Interview Questions