What is a string?

A string is a sequence or array of characters, In Java, The string is an immutable object that means it is constant and can not be changed once it has been created.

To work with string java has a built-in class ‘String’ that provides dozen of methods to deal with a string.

How to create a string in java?

There are two ways to create a string in Java –

  1. Using string literal
  2. Using the new keyword

Using string literal

The Java string literal can be created using double quotes.

Example

public class StringExample1 {

    public static void main(String[] args) {

        // Using string literal
        String str = "Hello World!";

        // Printing the string
        System.out.println(str);

    }
}

Using the new keyword

The Java string literal can be created using the ‘new’ keyword.

Example

public class StringExample2 {

    public static void main(String[] args) {

        // Using string literal
        String str = "Hello World!";

        // Using new keyword
        String myStr = new String("I, am a string\nThis is second line.");

        // Printing the string
        System.out.println(str);
        System.out.println(myStr);

    }
}

String constants pool

The Java string constant pool is a special memory area where literal string values are stored. Whenever we create a string literal, the JVM checks the “string constant pool” for the already existing string with the same value in the pool. If the string with the same value exists, a reference to the pooled instance is returned otherwise, new string instance is created and added into the pool.

Java String methods

MethodDescription
char charAt (int index)Returns the character at the given index.
IntStream chars()Returns an IntStream object extending the char values of this sequence.
int codePointAt (int index)Returns the Unicode code point at the given index.
int codePointBefore (int index)Returns the Unicode code point before the given index.
int codePointCount (int beginIndex, int endIndex)Returns the number of Unicode code points in the given text range of current String.
IntStream codePoints()Returns an IntStream object, a stream of code point values from the current string.
int compareTo (String anotherString)Compares current string with another string lexicographically.
int compareToIgnoreCase (String str)Compares current string with another string lexicographically, ignoring case differences.
String concat (String str)Concatenates the given string to the end of the current string.
boolean contains (CharSequence s)Checks if the current string containing a given string.
boolean contentEquals (CharSequence cs)Compares current string content with another string content.
boolean contentEquals (StringBuffer sb)Compares current string to the given StringBuffer.
static String copyValueOf (char[] data)Copies the value of the given character array.
static String copyValueOf (char[] data, int offset, int count)Copies the value of given character array at the given range only.
boolean endsWith (String suffix)Checks if the current string ends with the given suffix string.
boolean equals (Object anObject)Checks if the current string equals to the given object.
boolean equalsIgnoreCase (String anotherString)Checks if current string equals to the given object, ignoring case considerations.
static String format (String format, Object… args)Creates and returns a formatted string using the given format string and arguments.
static String format (Locale l, String format, Object… args)Creates and returns a formatted string using the given locale, format string, and arguments.
byte[] getBytes()Encodes the current string into a byte array using the platform’s default charset and returns the new byte array.
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)This method is Deprecated.
byte[] getBytes(String charsetName)Encodes the current string into a byte array using the named charset and returns the new byte array.
byte[] getBytes(Charset charset)Encodes the current string into a byte array using the given charset and returns the new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Copies characters from the current string into the given character array.
int hashCode()Returns the hash code value for the current string.
int indexOf(int ch)Returns the first occurrence of the given character in the current string.
int indexOf(int ch, int fromIndex)Returns the first occurrence of the given character in the current string, starting the search at the given index.
int indexOf(String str)Returns the first occurrence of the given string in the current string.
int indexOf(String str, int fromIndex)Returns the first occurrence of the given string in the current string, starting the search at the given index.
String intern()Returns a canonical representation of the current string object.
boolean isEmpty()Checks whether the current string is empty or not.
static String join(CharSequence delimiter, CharSequence… elements)Returns a new String created from copies of the given CharSequence elements joined together with a given delimiter.
static String join(CharSequence delimiter, Iterable > extends CharSequence < elements)Returns a new String created from copies of the given CharSequence elements joined together with a given delimiter.
int lastIndexOf(int ch)Returns the last index of the given character in the current string.
int lastIndexOf(int ch, int fromIndex)Returns the last index of the given character in the current string. searching backward starting at the given index.
int lastIndexOf(String str)Returns the last index of the given string in the current string.
int lastIndexOf(String str, int fromIndex)Returns the last index of the given string in the current string. searching backward starting at the given index.
int length()Returns the length of the current string.
boolean matches(String regex)Checks whether the current string matches the given regular expression or not.
int offsetByCodePoints(int index, int codePointOffset)Returns the index within the current string that is offset from the given index by codePointOffset code points.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)Checks whether the two string regions are equal or not.
boolean regionMatches(int toffset, String other, int ooffset, int len)Checks whether the two string regions are equal or not.
String replace(char oldChar, char newChar)Returns a new string after replacing given old character with given new character.
String replace(CharSequence target, CharSequence replacement)Returns a new string after replacing given target string with the given replacement string.
String replaceAll(String regex, String replacement)Returns new string after replacing all the occurrences of the given string with the given regular expression.
String replaceFirst(String regex, String replacement)Returns new string after replacing the first occurrences of the given string with the given regular expression.
String[] split(String regex)Returns the array of string after splitting the current string with the given regular expression.
String[] split(String regex, int limit)Returns the array of given size, containing splitted strings with the given regular expression.
boolean startsWith(String prefix)Checks whether the current string starts with the given string or not.
boolean startsWith(String prefix, int toffset)Checks whether the current string at the given index starts with given string or not.
CharSequence subSequence(int beginIndex, int endIndex)Returns a character sequence at given range of current string.
String substring(int beginIndex)Returns a new sub string of current string from the given index.
String substring(int beginIndex, int endIndex)Returns a new sub string of current string in given range.
char[] toCharArray()Returns new character array of current string.
String toLowerCase()Returns new string after converting all the character to lowercase using the rules of the default locale.
String toLowerCase(Locale locale)Returns new string after converting all the character to lowercase using the given local rule.
String toUpperCase()Returns new string after converting all the character to uppercase using the rules of the default locale.
String toUpperCase(Locale locale)Returns new string after converting all the character to uppercase using the given local rule.
String trim()Returns new string aftering removing leading and trailing whitespace.
static String valueOf(boolean b)Returns a string representation of the given boolean.
static String valueOf(char c)Returns a string representation of the given character.
static String valueOf(char[] c)Returns a new string of from the given character array.
static String valueOf(char[] c)Returns a new string of from the given character array and with the given offset and count.
static String valueOf(double d)Returns a string representation of the given double.
static String valueOf(float f)Returns a string representation of the given float.
static String valueOf(int i)Returns a string representation of the given int.
static String valueOf(long l)Returns a string representation of the given long.
static String valueOf(Object obj)Returns a string representation of the given object.