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.


Character Literal Introduction

String strFromLiteral = "Hello World";

We can treat the above character literal as a String object since it is that object’s reference. So we can call it’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);

The above code output will be:

welcome to java world
'This is an example code' length is 23

Two character literal can be concatenated by “+” operator. And this will create a new String object.

String plusTwoString = "Hello" + "World";

Java virtual machine implement “+” operator use StringBuffer internally as below.

plusTwoStringImpl = new StringBuffer().append("Hello").append("World").toString();

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 java String class that maintain those interned strings.

		String strObj1 = "Hello Teacher";
		String strObj2 = "Hello Teacher";
		if(strObj1 == strObj2)
			System.out.println("strObj1 equal strObj2");

The output for above code

strObj1 equal strObj2

But when you operate on strObj1 such as below code, strObj1 will not equal strObj2 any more. Because String object is immutable, so the “+=” operation will generate a new object with new literal value.

		strObj1 += " ok";
		if(strObj1 != strObj2)
			System.out.println("strObj1 not equal strObj2");

Output for above code

strObj1 not equal strObj2


  1. String() : Create an new object with empty character.
  2. String(character literal) : Create a new object that content data is same with the character literal.
  3. Constructor created String object 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.");

    The output should be

    strTest1 equal strTest2, because same value character literal is interned.
    strTest1 not equal strTest3, because strTest3 is created by it's constructor.


  1. intern() : This method will return a reference to a interned String object. There is a private pool managed by String class. The pool is empty at the beginning. When a String object invoke it’s intern() method, if there has already an character object with 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 object.
  2. equals() : Compare two java character object’s content value. Return true if they has same value, otherwise return false. Please note “==”  operator compares two object’s reference not the object holding content. But equals compares the two object’s 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 object’s 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.
    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 end 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 is equal or not. A substring of original is compared to the substring of the other.
    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 begin 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 character in the sequence into lower case.
  17. toUpperCase() : Change all the character in the sequence into upper case.
  18. trim() : Remove the wihte space in the beginning and ending of the sequence and return it.
  19. char[] toCharArray() : Coverts the character sequence to a new char array.
READ :   How To Auto Import All Class In Android Studio

You can find more introduction at

Download “” – Downloaded 202 times – 807 B

Leave a Reply

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.