Table of Contents
- 1. Java String.String()
- 2. Java String.codePointCount()
- 3. Java String.codePointAt()
- 4. Java String.concat()
- 5. Java String.contains()
- 6. Java String.copyValueOf()
- 7. Java String.endsWith()
- 8. Java String.format()
- 9. Java String.getBytes()
- 10. Java String.indexOf()
- 11. Java String.intern()
- 12. Java String.isEmpty()
- 13. Java String.lastIndexOf()
- 14. Java String.regionMatches()
- 15. Java String.replace()
- 16. Java String.replaceAll()
- 17. Java String.split()
- 18. Java String.startsWith()
- 19. Java String.subSequence()
- 20. Java String.substring()
- 21. Java String.toLowerCase()
- 22. Java String.toUpperCase()
- 23. Java String.trim()
- 24. Java String.valueOf()
1. Java String.String()
String objects can be created by either using literals:
String s = "a string";
or by calling one of the constructors:
String s = new String("a string");
If we use the String literal, it’ll try to reuse already existing object from the String constant pool.
On the other hand, when instantiating a String using the constructor, a new object will be created
This constructor accepts many types of arguments and uses them to create a new String object.
Available Signatures
public String() public String(byte[] bytes) public String(byte[] bytes, Charset charset) public String(byte[] bytes, int offset, int length) public String(byte[] bytes, int offset, int length, Charset charset) public String(byte[] bytes, int offset, int length, String charsetName) public String(byte[] bytes, String charsetName) public String(char[] value) public String(char[] value, int offset, int count) public String(int[] codePoints, int offset, int count) public String(String original) public String(StringBuffer buffer) public String(StringBuilder builder)
Example
@Test public void whenCreateStringUsingByteArray_thenCorrect() { byte[] array = new byte[] { 97, 98, 99, 100 }; String s = new String(array); assertEquals("abcd", s); }
2. Java String.codePointCount()
The method codePointCount() returns the number of Unicode code points in the specified range. The text range begins at the first index and ends at the second index – 1.
Available Signatures
public int codePointCount(int beginIndex, int endIndex)
Example
@Test public void whenCallCodePointCount_thenCorrect() { assertEquals(2, "abcd".codePointCount(0, 2)); }
IndexOutOfBoundsException – if the first index is negative, the first index is greater than the second index or the second index is not less than the length of the String.
@Test(expected = IndexOutOfBoundsException.class) public void whenSecondIndexEqualToLengthOfString_thenExceptionThrown() { char character = "Paul".charAt(4); }
3. Java String.codePointAt()
The method codePointAt() takes an int as a parameter and returns the code point at the specified index. A code point is a decimal value that the character is given in the Unicode standard.
Available Signatures
public int codePointAt(int index)
Example
@Test public void whenCallCodePointAt_thenDecimalUnicodeReturned() { assertEquals(97, "abcd".codePointAt(0)); }
StringIndexOutOfBoundsException – if a non-existent index is passed to the method.
@Test(expected = StringIndexOutOfBoundsException.class) public void whenPassNonExistingIndex_thenStringIndexOutOfBoundsExceptionThrown() { int a = "abcd".codePointAt(4); }
4. Java String.concat()
The method concat() concatenates two Strings. Simply put, it connects them into a single String. If the length of the argument is 0, then the method simply returns the String object.
Available Signatures
public String concat(String str)
Example
@Test public void whenCallConcat_thenCorrect() { assertEquals("elephant", "elep".concat("hant")); }
5. Java String.contains()
The method contains() checks if a String contains another String. The method accepts a CharSequence. So, we can pass any of the implementing classes to it such as StringBuilder and StringBuffer.
Available Signatures
public boolean contains(CharSequence s)
Example
@Test public void whenCallContains_thenCorrect() { String s = "abcd"; assertTrue(s.contains("abc")); assertFalse(s.contains("cde")); }
6. Java String.copyValueOf()
The method copyValueOf() converts a character array to a String with the same contents. This method is equivalent to valueOf(char[]).
The offset represents the index of the first element to start copying from, and the count represents the number of elements to copy.
Available Signatures
public static String copyValueOf(char[] data) public static String copyValueOf(char[] data, int offset, int count)
Example
@Test public void whenCallCopyValueOf_thenStringConstructed() { char[] array = new char[] { 'a', 'b', 'c', 'd' }; assertEquals("abcd", String.copyValueOf(array)); }
7. Java String.endsWith()
The method endsWith() is a convenience method that checks if a String ends with another given String. If the argument is an empty String, then the method returns true.
Available Signatures
public boolean endsWith(String suffix)
Example
@Test public void whenCallEndsWith_thenCorrect() { String s1 = "test"; assertTrue(s1.endsWith("t")); }
8. Java String.format()
The method format() formats a String using a format String and arguments. For example, characters ‘s’ and ‘S’ evaluate to “null” if the argument arg is null.
If arg implements Formattable, then the method Formattable, then the method arg.formatTo() is invoked. Otherwise, the result is evaluated by invoking arg.toString().
For more information on formatting, visit the Javadoc.
Available Signatures
public static String format(String format, Object... args) public static String format(Locale l, String format, Object... args)
Example
@Test public void whenFormat_thenCorrect() { String value = "maixuanviet.com"; String formatted = String.format("Welcome to %s!", value); assertEquals("Welcome to maixuanviet.com!", formatted); }
IllegalFormatException – If the format String contains an invalid syntax.
@Test(expected = IllegalFormatException.class) public void whenInvalidFormatSyntax_thenIllegalFormatExceptionThrown() { String value = "maixuanviet.com"; String formatted = String.format("Welcome to %x!", value); }
9. Java String.getBytes()
The method getBytes() encodes a String into a byte array using the platform’s default charset if no argument is passed.
We can pass a specific Charset to be used in the encoding process, either as a String object or a String object.
Available Signatures
public byte[] getBytes() public byte[] getBytes(Charset charset) public byte[] getBytes(String charsetName)
Example
@Test public void whenGetBytes_thenCorrect() throws UnsupportedEncodingException { byte[] byteArray1 = "abcd".getBytes(); byte[] byteArray2 = "efgh".getBytes(StandardCharsets.US_ASCII); byte[] byteArray3 = "ijkl".getBytes("UTF-8"); byte[] expected1 = new byte[] { 97, 98, 99, 100 }; byte[] expected2 = new byte[] { 101, 102, 103, 104 }; byte[] expected3 = new byte[] { 105, 106, 107, 108 }; assertArrayEquals(expected1, byteArray1); assertArrayEquals(expected2, byteArray2); assertArrayEquals(expected3, byteArray3); }
10. Java String.indexOf()
The method indexOf() returns the first occurrence index of a character or a String in another String. We can pass the index of the character to start searching from.
Note that the method returns -1 if the passed value is not found.
Available Signatures
public int indexOf(int ch) public int indexOf(int ch, int fromIndex) public int indexOf(String str) public int indexOf(String str, int fromIndex)
Example
@Test public void whenCallIndexOf_thenCorrect() { String str = "foo"; assertEquals(1, str.indexOf("o")); assertEquals(-1, str.indexOf("s")); }
11. Java String.intern()
The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool.
Note that, if another String with the same contents exists in the String constant pool, then a new object won’t be created and the new reference will point to the other String.
Available Signatures
public String intern()
Example
@Test public void whenIntern_thenCorrect() { String s1 = "abc"; String s2 = new String("abc"); String s3 = new String("foo"); String s4 = s1.intern(); String s5 = s2.intern(); assertFalse(s3 == s4); assertTrue(s1 == s5); }
12. Java String.isEmpty()
The method isEmpty() is a convenience method that checks if the size of a String is equal to zero.
Available Signatures
public boolean isEmpty()
Example
@Test public void whenCallIsEmpty_thenCorrect() { String s1 = ""; assertTrue(s1.isEmpty()); }
13. Java String.lastIndexOf()
The method lastIndexOf() returns the index of the last occurrence of a String in another String. If an int is passed to the method, then the method searches for the Unicode character equivalent.
We can also pass the index of the character to start searching from.
Available Signatures
public int lastIndexOf(int ch) public int lastIndexOf(int ch, int fromIndex) public int lastIndexOf(String str)
Example
@Test public void whenCallLastIndexOf_thenCorrect() { assertEquals(2, "foo".lastIndexOf("o")); assertEquals(2, "foo".lastIndexOf(111)); }
14. Java String.regionMatches()
The method regionMatches() checks if two String regions are equal.
Here are a few important points:
- ignoreCase specifies whether we should ignore the case of both Strings
- toffset determines the starting index of the first String
- other specifies the second String.
- ooffset specifies the starting index of the second String
- len specifies the number of characters to compare
Available Signatures
boolean regionMatches(int toffset, String other, int ooffset, int len) boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Example
@Test public void whenCallRegionMatches_thenCorrect() { assertTrue("welcome to maixuanviet.com".regionMatches(false, 11, "maixuanviet.com", 0, 8)); }
15. Java String.replace()
The method regionMatches() checks if two String regions are equal.
Here are a few important points:
- ignoreCase specifies whether we should ignore the case of both Strings
- toffset determines the starting index of the first String
- other specifies the second String.
- ooffset specifies the starting index of the second String
- len specifies the number of characters to compare
Available Signatures
public boolean regionMatches(int toffset, String other, int ooffset, int len) boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Example
@Test public void whenCallRegionMatches_thenCorrect() { assertTrue("welcome to maixuanviet.com".regionMatches(false, 11, "maixuanviet.com", 0, 8)); }
16. Java String.replaceAll()
The method replaceAll() replaces all occurrences of a String in another String.
Available Signatures
public String replaceAll(String regex, String replacement)
Example
@Test public void whenCallReplace_thenCorrect() { String s = "I learn Spanish"; assertEquals("I learn French", s.replaceAll("Spanish", "French")); }
17. Java String.split()
The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.
We can also pass a limit to the number of elements in the returned array. If we pass 0 as a limit, then the method will behave as if we didn’t pass any limit, returning an array containing all elements that can be split using the passed delimiter.
Available Signatures
public String[] split(String regex, int limit) public String[] split(String regex)
Example
@Test public void whenSplit_thenCorrect() { String s = "Welcome to maixuanviet.com"; String[] expected1 = new String[] { "Welcome", "to", "maixuanviet.com" }; String[] expected2 = new String[] { "Welcome", "to maixuanviet.com" }; assertArrayEquals(expected1, s.split(" ")); assertArrayEquals(expected2, s.split(" ", 2)); }
PatternSyntaxException – if the pattern of the delimiter is invalid.
@Test(expected = PatternSyntaxException.class) public void whenPassInvalidParameterToSplit_thenPatternSyntaxExceptionThrown() { String s = "Welcome*to maixuanviet.com"; String[] result = s.split("*"); }
18. Java String.startsWith()
The method startsWith() is a convenience method that checks whether a String starts with another String. We can also pass the index of the first character to start checking from.
Available Signatures
public boolean startsWith(String prefix) public boolean startsWith(String prefix, int toffset)
Example
@Test public void whenCallStartsWith_thenCorrect() { String str = "foo"; assertTrue(str.startsWith("f")); assertTrue(str.startsWith("oo", 1)); }
19. Java String.subSequence()
The method subSequence() obtains a part of a String given the starting index and the length of the result. The method SubSequence() behaves in the same way as substring().
The only difference is that it returns a CharSequence instead of a String.
Available Signatures
public CharSequence subSequence(int beginIndex, int endIndex)
Example
@Test public void whenCallSubSequence_thenCorrect() { String s = "Welcome to maixuanviet.com"; assertEquals("Welcome", s.subSequence(0, 7)); }
20. Java String.substring()
The method substring() comes with two signatures. If we pass the beginIndex and the endIndex to the method, then it obtains a part of a String given the starting index and the length of the result.
We can also pass the beginIndex only and obtain the part of the String from the beginIndex to the end of the String.
Available Signatures
public String substring(int beginIndex) public String substring(int beginIndex, int endIndex)
Example
@Test public void whenCallSubstring_thenCorrect() { String s = "Welcome to maixuanviet.com"; assertEquals("Welcome", s.substring(0, 7)); }
IndexOutOfBoundsException – if the first index is negative, the first index is larger than the second index or the second index is larger than the length of the String
@Test(expected = IndexOutOfBoundsException.class) public void whenSecondIndexEqualToLengthOfString_thenCorrect() { String s = "Welcome to maixuanviet.com"; String sub = s.substring(0, 20); }
21. Java String.toLowerCase()
The method toLowerCase() converts all characters of a String to lower case. If no Locale is passed to the method, then it will use the default Locale.
However, it may produce unexpected results if it’s run on a system whose default Locale is different. To avoid this, we can simply pass the Locale to the method.
Available Signatures
public String toLowerCase(Locale locale) public String toLowerCase()
Example
@Test public void whenConvertToLowerCase_thenCorrect() { String s = "WELCOME to VIETMX!"; assertEquals("welcome to maixuanviet.com!", s.toLowerCase()); }
22. Java String.toUpperCase()
The method toUpperCase() converts all characters of a String to upper case. If no Locale is passed to the method, then it will use the default Locale.
However, it may produce unexpected results if it’s run on a system whose default Locale is different. To avoid this, we can simply pass the Locale to the method.
Available Signatures
public String toUpperCase() public String toUpperCase(Locale locale)
Example
@Test public void whenConvertToUpperCase_thenCorrect() { String s = "Welcome to maixuanviet.com!"; assertEquals("WELCOME TO VIETMX!", s.toUpperCase()); }
23. Java String.trim()
The method trim() removes any whitespace at the beginning and at the end of a String. If the String contains only spaces, then the method returns an empty String.
Available Signatures
public String trim()
Example
@Test public void whenTrim_thenCorrect() { assertEquals("foo", " foo ".trim()); }
24. Java String.valueOf()
The method valueOf() has several overloads that accept one parameter of different types and convert them to a String. Examples include boolean, char, char array, double, int and long. We can also convert a part of a char array to a String by passing:
- offset – the index of the character to start converting from
- count – the number of characters to convert
Available Signatures
public static String valueOf(boolean b) public static String valueOf(char c) public static String valueOf(char[] data) public static String valueOf(char[] data, int offset, int count) public static String valueOf(double d) public static String valueOf(float f) public static String valueOf(int i) public static String valueOf(long l) public static String valueOf(Object obj)
Example
@Test public void whenCallValueOf_thenCorrect() { long l = 200L; assertEquals("200", String.valueOf(l)); }