Tutorial

Java String

Published on August 3, 2022
author

Pankaj

Java String

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.

    String str = "abc"; 
    

    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.

    String str  =  new String("abc");
    char[] a = {'a', 'b', 'c'};
    String str2  =  new String(a);
    

    java create string object, java string new

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.

package com.journaldev.string.examples;

/**
 * Java String Example
 * 
 * @author pankaj
 *
 */
public class StringEqualExample {

	public static void main(String[] args) {
		//creating two string object
		String s1 = "abc";
		String s2 = "abc";
		String s3 = "def";
		String s4 = "ABC";
		
		System.out.println(s1.equals(s2));//true
		System.out.println(s2.equals(s3));//false
		
		System.out.println(s1.equals(s4));//false;
		System.out.println(s1.equalsIgnoreCase(s4));//true
	}

}

Output of above program is:

true
false
false
true

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.

package com.journaldev.examples;

/**
 * Java String compareTo Example
 * 
 * @author pankaj
 *
 */
public class StringCompareToExample {

	public static void main(String[] args) {
		
		String a1 = "abc";
		String a2 = "abc";
		String a3 = "def";
		String a4 = "ABC";
		
		System.out.println(a1.compareTo(a2));//0
		System.out.println(a2.compareTo(a3));//less than 0
		System.out.println(a1.compareTo(a4));//greater than 0
		System.out.println(a1.compareToIgnoreCase(a4));//0
	}

}

Output of above program is:

0
-3
32
0

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.
    package com.journaldev.examples;
    
    /**
     * Java String split example
     * 
     * @author pankaj
     *
     */
    public class StringSplitExample {
    
    	public static void main(String[] args) {
    		
    		String s = "a/b/c/d";
    		String[] a1 = s.split("/");
    		System.out.println("split string using only regex:");
    		for (String string : a1) {
    			System.out.println(string);
    		}
    		System.out.println("split string using regex with limit:");
    		String[] a2 = s.split("/", 2);
    		for (String string : a2) {
    			System.out.println(string);
    		}
    	}
    
    }
    

    Output of above program is:

    split string using only regex:
    a
    b
    c
    d
    split string using regex with limit:
    a
    b/c/d
    
  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.

    package com.journaldev.examples;
    
    /**
     * Java String contains() Example
     * 
     * @author pankaj
     *
     */
    public class StringContainsExample {
    
    	public static void main(String[] args) {
    		String s = "Hello World";
    		
    		System.out.println(s.contains("W"));//true
    		System.out.println(s.contains("X"));//false
    	}
    
    }
    

    Output of above program is:

    true
    false
    
  3. length()

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

    package com.journaldev.examples;
    
    /**
     * Java String length
     * 
     * @author pankaj
     *
     */
    public class StringLengthExample {
    
    	public static void main(String[] args) {
    		
    		String s1 = "abc";
    		String s2 = "abcdef";
    		String s3 = "abcdefghi";
    		
    		System.out.println(s1.length());//3
    		System.out.println(s2.length());//6
    		System.out.println(s3.length());//9
    
    	}
    
    }
    
  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.
    package com.journaldev.examples;
    
    /**
     * Java String replace
     * 
     * @author pankaj
     *
     */
    public class StringReplaceExample {
    
    	public static void main(String[] args) {
    		
    		//replace(char oldChar,  char newChar)
    		String s = "Hello World";
    		s = s.replace('l', 'm');
    		System.out.println("After Replacing l with m :");
    		System.out.println(s);
    		
    		//replaceAll(String regex, String replacement)
    		String s1 = "Hello journaldev, Hello pankaj";
    		s1 = s1.replaceAll("Hello", "Hi");
    		System.out.println("After Replacing :");
    		System.out.println(s1);
    		
    		//replaceFirst(String regex, String replacement) 
    		String s2 = "Hello guys, Hello world";
    		s2 = s2.replaceFirst("Hello", "Hi");
    		System.out.println("After Replacing :");
    		System.out.println(s2);
    
    	}
    
    }
    

    The output of above program is:

    After Replacing l with m :
    Hemmo Wormd
    After Replacing :
    Hi journaldev, Hi pankaj
    After Replacing :
    Hi guys, Hello world
    
  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.
    package com.journaldev.examples;
    
    import java.util.Locale;
    
    /**
     * Java String format
     * 
     * @author pankaj
     *
     */
    public class StringFormatExample {
    
    	public static void main(String[] args) {
    		
    		String s = "journaldev.com";
    		// %s is used to append the string
    		System.out.println(String.format("This is %s", s));
    		
    		//using locale as Locale.US
    		System.out.println(String.format(Locale.US, "%f", 3.14));
    	}
    }
    

    Output of above program is:

    This is journaldev.com
    3.140000
    
  6. substring()

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

    package com.journaldev.examples;
    
    /**
     * Java String substring
     *
     */
    public class StringSubStringExample {
    
    	public static void main(String[] args) {
    		
    		String s = "This is journaldev.com";
    		s = s.substring(8,18);
    		System.out.println(s);
    	}
    }
    

String Concatenation

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

package com.journaldev.examples;

/**
 * Java String concatenation
 * 
 * @author pankaj
 *
 */
public class StringConcatExample {

	public static void main(String[] args) {
		
		String s1 = "Hello";
		String s2 = "World";
		String s3 = s1 + s2;
		//using + operator
		System.out.println("Using + operator: ");
		System.out.println(s3);
		
		//using concat method
		System.out.println("Using concat method: ");
		System.out.println(s1.concat(s2));

	}

}

Output of above program is:

Using + operator: 
HelloWorld
Using concat method: 
HelloWorld

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.

package com.journaldev.examples;

/**
 * Java String Pool Example
 * 
 */
public class StringPoolExample {

	public static void main(String[] args) {
		
		String a = "abc";
		String b = "abc";
		String c = "def";
		
		//same reference
		if (a==b) {
			System.out.println("Both string refer to the same object");
		}
		
		//different reference
		if (a==c) {
			System.out.println("Both strings refer to the same object");
		}else {
			System.out.println("Both strings refer to the different object");
		}

	}

}

The output of above program is:

Both string refer to the same object
Both strings refer to the different object

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.

package com.journaldev.examples;

/**
 * Java String intern
 * 
 * @author pankaj
 *
 */
public class StringInternExample {

	public static void main(String[] args) {
		
		String s1 = "pankaj";
		String s2 = "pankaj";
		String s3 = new String("pankaj");
		
		System.out.println(s1==s2);//true
		System.out.println(s2==s3);//false
		
		String s4 = s3.intern();
		System.out.println(s1==s4);//true

	}

}

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.

List<String> words = Arrays.asList(new String[]{"Hello", "World", "2019"});
String msg = String.join(" ", words);
System.out.println(msg);

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.

String s = "abc";

s.codePoints().forEach(x -> System.out.println(x));

s.chars().forEach(x -> System.out.println(x));

Output:

97
98
99
97
98
99

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.

package com.journaldev.strings;

import java.util.List;
import java.util.stream.Collectors;

/**
 * JDK 11 New Functions in String class
 * 
 * @author pankaj
 *
 */
public class JDK11StringFunctions {

	public static void main(String[] args) {
		// isBlank()
		String s = "abc";
		System.out.println(s.isBlank());
		s = "";
		System.out.println(s.isBlank());

		// lines()
		String s1 = "Hi\nHello\rHowdy";
		System.out.println(s1);
		List lines = s1.lines().collect(Collectors.toList());
		System.out.println(lines);

		// strip(), stripLeading(), stripTrailing()
		String s2 = "  Java,  \tPython\t ";
		System.out.println("#" + s2 + "#");
		System.out.println("#" + s2.strip() + "#");
		System.out.println("#" + s2.stripLeading() + "#");
		System.out.println("#" + s2.stripTrailing() + "#");

		// repeat()
		String s3 = "Hello\n";
		System.out.println(s3.repeat(3));
		s3 = "Co";
		System.out.println(s3.repeat(2));

	}

}

Output:

false
true
Hi
Hello
Howdy
[Hi, Hello, Howdy]
#  Java,  	Python	 #
#Java,  	Python#
#Java,  	Python	 #
#  Java,  	Python#
Hello
Hello
Hello

CoCo

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

You can checkout more String examples from our GitHub Repository.

Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
July 5, 2021

chars() was added in Java 8 not in Java 9.

- Gaurav

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 9, 2021

    Thank you so much sir Great work…it ll be very useful…

    - hudaver

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 22, 2020

      Can someone tell where I can find Java real word coding examples

      - JB

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 13, 2020

        I found this really helpful, the webiste design is clean, max all the functions useful can be found with an example. I will recommend this to all my friends.

        - CHITTIREDDY CHETHAN REDDY

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          May 30, 2020

          Dear Pankaj, Thanks for the information, helped a lot.

          - Naveen Kavana

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            May 10, 2020

            Awesome article.I learned a lot

            - Jaswanth Kumar Karamala

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              January 5, 2020

              Thank you so much sir Great work…it ll be very useful…

              - CHETAN

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                June 5, 2019

                Good information…keep up the good work.

                - Kishor

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  February 6, 2019

                  Excellent, all the information at one place, very helpful to get knowledge on latest releases as well

                  - Deepika D

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    January 22, 2019

                    Seems JDK 11 learned a lot from Python syntax. :)

                    - Scott Wu

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Become a contributor for community

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      DigitalOcean Documentation

                      Full documentation for every DigitalOcean product.

                      Resources for startups and SMBs

                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                      Get our newsletter

                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                      New accounts only. By submitting your email you agree to our Privacy Policy

                      The developer cloud

                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Get started for free

                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                      *This promotional offer applies to new accounts only.