Java String With Examples

Java String is one of the most widely used class. Java String class is defined in java.lang package.

Java String

  • Basically, string is a sequence of characters but it’s not a primitive type.
  • When we create a string in java, it actually creates an object of type String.
  • String is immutable object which means that it cannot be changed once it is created.
  • String is the only class where operator overloading is supported in java. We can concat two strings using + operator. For example "a"+"b"="ab".
  • Java provides two useful classes for String manipulation – StringBuffer and StringBuilder.

Let’s go ahead and learn more about Java String class.

Different Ways to Create String

There are many ways to create a string object in java, some of the popular ones are given below.

  1. Using string literal

    This is the most common way of creating string. In this case a string literal is enclosed with double quotes.

    java-string
    When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool.

  2. Using new keyword

    We can create String object using new operator, just like any normal java class. There are several constructors available in String class to get String from char array, byte array, StringBuffer and StringBuilder.

     

Java String compare

String class provides equals() and equalsIgnoreCase() methods to compare two strings. These methods compare the value of string to check if two strings are equal or not. It returns true if two strings are equal and false if not.

Output of above program is:

String class implements Comparable interface, which provides compareTo() and compareToIgnoreCase() methods and it compares two strings lexicographically.

Both strings are converted into Unicode value for comparison and return an integer value which can be greater than, less than or equal to zero. If strings are equal then it returns zero or else it returns either greater or less than zero.

Output of above program is:

Please read this in more detail at String compareTo example.

Java String Methods

Let’s have a look at some of the popular String class methods with an example program.

  1. split()

    Java String split() method is used to split the string using given expression. There are two variants of split() method.

    • split(String regex): This method splits the string using given regex expression and returns array of string.
    • split(String regex, int limit): This method splits the string using given regex expression and return array of string but the element of array is limited by the specified limit. If the specified limit is 2 then the method return an array of size 2.

    Output of above program is:

  2. contains(CharSequence s)

    Java String contains() methods checks if string contains specified sequence of character or not. This method returns true if string contains specified sequence of character, else returns false.

    Output of above program is:

  3. length()

    Java String length() method returns the length of string.

  4. replace()

    Java String replace() method is used to replace a specific part of string with other string. There are four variants of replace() method.

    • replace(char oldChar, char newChar): This method replace all the occurrence of oldChar with newChar in string.
    • replace(CharSequence target, CharSequence replacement): This method replace each target literals with replacement literals in string.
    • replaceAll(String regex, String replacement): This method replace all the occurrence of substring matches with specified regex with specified replacement in string.
    • replaceFirst(String regex, String replacement): This method replace first occurrence of substring that matches with specified regex with specified replacement in string.

    The output of above program is:

  5. format()

    Java Sting format() method is used to format the string. There is two variants of java String format() method.

    • format(Locale l, String format, Object… args): This method formats the string using specified locale, string format and arguments.
    • format(String format, Object… args): This method formats the string using specified string format and arguments.

    Output of above program is:

  6. substring()

    This method returns a part of the string based on specified indexes.

String Concatenation

String concatenation is very basic operation in java. String can be concatenated by using “+” operator or by using concat() method.

Output of above program is:

Check this post for more information about String Concatenation in Java.

Java String Pool

Memory management is the most important aspect of any programming language. Memory management in case of string in Java is a little bit different than any other class. To make Java more memory efficient, JVM introduced a special memory area for the string called String Constant Pool.

When we create a string literal it checks if there is identical string already exist in string pool or not. If it is there then it will return the reference of the existing string of string pool.

Let’s have a look at the below example program.

The output of above program is:

Check this post for more about Java String Pool.

String intern() Method

When we create a string using string literal, it will be created in string pool but what if we create a string using new keyword with the same value that exists in string pool? Can we move the String from heap memory to string pool?

For this intern() method is used and it returns a canonical representation of string object. When we call intern() method on string object that is created using the new keyword, it checks if there is already a String with the same value in the pool?

If yes, then it returns the reference of that String object from the pool. If not, then it creates a new String with the same content in the pool and returns the reference.

Check this post to learn more about Java String intern method.

String Immutability Benefits

Some of the benefits of String being immutable class are:

  1. String Constant Pool, hence saves memory.
  2. Security as it’s can’t be changed.
  3. Thread safe
  4. Class Loading security

Check this post for more about Sting Immutablity Benefits.

Java 8 String join()

A new static method join() has been added in String class in Java 8. This method returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. Let’s look at an example to understand it easily.

Output: Hello World 2019

Java 9 String Methods

There are two methods added in String class in Java 9 release. They are – codePoints() and chars(). Both of these methods return IntStream object on which we can perform some operations.

Let’s have a quick look at these methods.

Output:

Java 11 String Class New Methods

There are many new methods added in String class in Java 11 release.

  • isBlank() – returns true if the string is empty or contains only white space codepoints, otherwise false.
  • lines() – returns a stream of lines extracted from this string, separated by line terminators.
  • strip(), stripLeading(), stripTrailing() – for stripping leading and trailing white spaces from the string.
  • repeat() – returns a string whose value is the concatenation of this string repeated given number of times.

Let’s look at an example program for these methods.

Output:

That’s all about Java String class, it’s method and String manipulation examples.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: