Java String Example

Java String class is used to implement an immutable character sequence object. That means a String object can not be changed or modified after it’s creation and initialization. It is read-only. In this article, we will show you how to create a Java String object, and the usage of it’s methods.

1. Character Literal Introduction.

  1. Below is a java String example.
    String strFromLiteral = "Hello World";
  2. We can treat the above character literal as a String object since it is that object’s reference. So we can call the String object’s method like below.
    String lowerCaseStr = "Welcome To Java World".toLowerCase();
    int len = "This is a example code".length();
    System.out.println("'This is an example code' length is " + len);
  3. The above code output will like below.
    welcome to java world
    'This is an example code' length is 23
  4. Two characters literal can be concatenated by the “+” operator. And this will create a new String object.
    String plusTwoString = "Hello" + "World";
  5. Java virtual machine implements “+” operator use StringBuffer internally as below.
    plusTwoStringImpl = new StringBuffer().append("Hello").append("World").toString();
  6. If two java variable has same character literal, then in JVM the two variable will point to the same String object. This is called interned String. There is a private pool in the java String class that maintains those interned strings.
    String strObj1 = "Hello Teacher";
    String strObj2 = "Hello Teacher";
    if(strObj1 == strObj2)
        System.out.println("strObj1 equal strObj2");
  7. The output for the above code is below.
    strObj1 equal strObj2
  8. But when you operate on strObj1 such as below code, strObj1 will not equal strObj2 anymore. Because the String object is immutable, so the “+=” operation will generate a new object with a new literal value.
    strObj1 += " ok";
    if(strObj1 != strObj2)
        System.out.println("strObj1 not equal strObj2");
  9. Output for the above java source code.
    strObj1 not equal strObj2

2. Constructor.

  1. String(): Create a new object with an empty character.
  2. String(character literal): Create a new object that contains data that is the same as the character literal.
  3. The String object that is created by the constructor is not an interned object.
    String strTest1 = "Good Morning";
    String strTest2 = "Good Morning";
    String strTest3 = new String("Good Morning"); 
        System.out.println("strTest1 equal strTest2, because same value character literal is interned.");
        System.out.println("strTest1 not equal strTest3, because strTest3 is created by it's constructor.");
  4. The above java source code execution output should be like below.
    strTest1 equal strTest2, because same value character literal is interned.
    strTest1 not equal strTest3, because strTest3 is created by it's constructor.

3. Method.

  1. intern(): This method will return a reference to an interned String object. There is a private pool managed by the String class. The pool is empty at the beginning. When a String object invokes it’s intern() method, if there has already a character object with the same value in the pool, then the object in the pool is returned. If there is not such a same value object exist in the pool, then the invoker character object will be added to the pool and the intern() method will return a reference to it. For example there are tow String object a and b, if a.equals(b) is true, then a.intern()==b.intern() is also true. All character literal and string constants are interned objects.
  2. equals(): Compare two java character objects’ content values. Return true if they have the same value, otherwise, return false. Please note “==” operator compares two objects’ references, not the object holding content. But the method equals() compares the two objects’ saved content.
    String strTest1 = "Good Morning";
    String strTest3 = new String("Good Morning"); 
        System.out.println("strTest1 not equal strTest3, because strTest3 is created by it's constructor.");
        System.out.println("strTest1 and strTest3 has same character value.");

    The output should be

    strTest1 not equal strTest3, because strTest3 is created by it's constructor.
    strTest1 and strTest3 has same character value.
  3. equalsIgnoreCase(): Compare two objects ‘ saved content ignore character case.
    String strUpper = "TODAY IS A GOOD DAY";
    String strLower = "today is a good day";
        System.out.println("strUpper not equal to strLower.");
        System.out.println("strUpper equal to strLower ignore case.");

    The Output as below

    strUpper not equal to strLower.
    strUpper equal to strLower ignore case.
  4. int compareTo(String str2): Compare the content of str1 and str2 lexicographically. It will compare each character’s unicode value.
    This method return an int value.
    0 : Means has same content.
    -1: Means str1 less than str2.
    1 : Means str1 greater than str2.
  5. boolean matches(String regex): Check whether the invoker matches the regular expression or not.
  6. substring(int beginIndex, int endIndex): Returns part of the invoker character sequence object. Starts at beginIndex and ends at endIndex. beginIndex should >= 0 and endIndex should less than the character sequence’s length -1.
  7. char charAt(int index): Returns the given index character value. Index’s scope is from 0 to length() – 1.
  8. int length(): Return the character sequence content length. The length is the same as the amount of Unicode code units within the character sequence.
  9. boolean isEmpty(): Return true if length() is 0 else return false.
  10. byte[] getBytes(): Generate a byte array using the default charset that the operating system supported.
  11. byte[] getBytes(Charset charset): Use the given charset to build a byte array.
  12. boolean regionMatches(int toffset, String other, int ooffset, int len): Check whether the two regions of the two character sequence are equal or not. A substring of the original is compared to the substring of the other.
    This method contains the below parameters.
    toffset : The original begin index.
    ooffset : The target begin index.
    len: The substring length of both original and target.
  13. boolean startsWith(String prefix, int toffset): Check whether the string begins with the expected prefix from the specified index or not.
  14. boolean endsWith(String suffix): Tests whether this string character value ends with the expected suffix or not.
  15. CharSequence subSequence(int beginIndex, int endIndex): Extract a fresh new character sequence from this sequence.
  16. toLowerCase(): Change all the characters in the sequence into lower case.
  17. toUpperCase(): Change all the characters in the sequence into upper case.
  18. trim(): Remove the white space at the beginning and end of the sequence and return it.
  19. char[] toCharArray(): Coverts the character sequence to a new char array.
  20. You can find more introduction at

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.