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.
- Below is a java String example.
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 the String object’s method like below.
String lowerCaseStr = "Welcome To Java World".toLowerCase(); System.out.println(lowerCaseStr); int len = "This is a example code".length(); System.out.println("'This is an example code' length is " + len);
- The above code output will like below.
welcome to java world 'This is an example code' length is 23
- Two characters literal can be concatenated by the “+” operator. And this will create a new String object.
String plusTwoString = "Hello" + "World";
- Java virtual machine implements “+” 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 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"); }
- The output for the above code is below.
strObj1 equal strObj2
- 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"); }
- Output for the above java source code.
strObj1 not equal strObj2
2. Constructor.
- String(): Create a new object with an empty character.
- String(character literal): Create a new object that contains data that is the same as the character literal.
- 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"); if(strTest1==strTest2) { System.out.println("strTest1 equal strTest2, because same value character literal is interned."); } if(strTest1!=strTest3) { System.out.println("strTest1 not equal strTest3, because strTest3 is created by it's constructor."); }
- 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.
- 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.
- 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"); if(strTest1!=strTest3) { System.out.println("strTest1 not equal strTest3, because strTest3 is created by it's constructor."); } if(strTest1.equals(strTest3)) { 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.
- equalsIgnoreCase(): Compare two objects ‘ saved content ignore character case.
String strUpper = "TODAY IS A GOOD DAY"; String strLower = "today is a good day"; if(!strUpper.equals(strLower)) { System.out.println("strUpper not equal to strLower."); } if(strUpper.equalsIgnoreCase(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.
- 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.
- boolean matches(String regex): Check whether the invoker matches the regular expression or not.
- 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.
- char charAt(int index): Returns the given index character value. Index’s scope is from 0 to length() – 1.
- int length(): Return the character sequence content length. The length is the same as the amount of Unicode code units within the character sequence.
- boolean isEmpty(): Return true if length() is 0 else return false.
- byte[] getBytes(): Generate a byte array using the default charset that the operating system supported.
- byte[] getBytes(Charset charset): Use the given charset to build a byte array.
- 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.
- boolean startsWith(String prefix, int toffset): Check whether the string begins with the expected prefix from the specified index or not.
- boolean endsWith(String suffix): Tests whether this string character value ends with the expected suffix or not.
- CharSequence subSequence(int beginIndex, int endIndex): Extract a fresh new character sequence from this sequence.
- toLowerCase(): Change all the characters in the sequence into lower case.
- toUpperCase(): Change all the characters in the sequence into upper case.
- trim(): Remove the white space at the beginning and end of the sequence and return it.
- char[] toCharArray(): Coverts the character sequence to a new char array.
- You can find more introduction at https://docs.oracle.com/javase/7/docs/api/java/lang/String.html