C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
In Java programs we use the String class. Many parts of programs use Strings. We declare, concatenate, test and search strings.
Objects. Strings are objects. They are references that point to their character data. Most methods we use with Strings are accessed through an instance.
String class, program. We use string literals—these are specified directly in the program. Then with the plus operator, we combine (concatenate) these strings.
Concat: The plus-operator combines string data. We combine the data from two or more strings this way.
Length: We also call the length() method on each string variable reference. This returns the character count.
Based on: Java 7 Java program that uses strings public class Program { public static void main(String[] args) { // Create strings with literals. String value1 = "Java"; String value2 = "Programmer"; // Concatenate strings. String value3 = value1 + " " + value2; // Print string. System.out.println(value3); // Get string lengths. int length1 = value1.length(); int length2 = value2.length(); int length3 = value3.length(); // Print lengths. System.out.println(length1); System.out.println(length2); System.out.println(length3); } } Output Java Programmer 4 10 15
Upper, lower. With the methods toUpperCase() and toLowerCase(), we change cases. The toUpperCase method affects only lowercase letters. And toLowerCase affects only uppercase ones.
Tip: Numbers, punctuation and whitespace are unaffected by these two methods. Sometimes, the methods will make no changes.
Java program that changes casing public class Program { public static void main(String[] args) { // A mixed-case string. String value1 = "The Golden Bowl"; // Change casing. String upper = value1.toUpperCase(); String lower = value1.toLowerCase(); // Print results. System.out.println(upper); System.out.println(lower); } } Output THE GOLDEN BOWL the golden bowl
Contains. How can we search one String for another? With contains(), we pass in a String we want to find. The method returns true, if the String is found. It returns false if not.
Case: In my testing, the contains() method is case-sensitive. We can compare strings case-in sensitively in many ways.
Also: We can use a custom char-searching method. Or we could change a program to completely avoid the problem.
Tip: Please see also the equalsIgnoreCase and compareToIgnoreCase methods, which provide case-insensitive searching.
Java program that uses contains public class Program { public static void main(String[] args) { String name = "socrates"; String value1 = "soc"; String value2 = "rate"; String value3 = "plato"; // The name contains this value. if (name.contains(value1)) { System.out.println(value1); } // The name also contains this value. if (name.contains(value2)) { System.out.println(value2); } // The name does not contain this value. if (!name.contains(value3)) { System.out.println("no: " + value3); } } } Output soc rate no: plato
CharAt. A String is made up of characters (char values). A char is like a number, a value. To get a char from a String, we call charAt() and pass it the index of the character.
Tip: Indexes start at zero and process to the length minus one. In this way a String is similar to an array.
Java program that uses charAt public class Program { public static void main(String[] args) { String value = "Java"; // Loop over all indexes in the String. for (int i = 0; i < value.length(); i++) { // Get char at this index and display it. char letter = value.charAt(i); System.out.println(letter); } } } Output J a v a
RegionMatches. This method tests a region of one string against another. We provide a start index for both strings. We also provide a length argument (the number of chars to test on both).
Case: We can have regionMatches ignore the case of characters by passing a value of "true" as the first argument.
Java program that uses regionMatches public class Program { public static void main(String[] args) { String codes = "onetwothreeFour"; // Check for "two" at index 3. // ... Length is 3 chars. if (codes.regionMatches(3, "two", 0, 3)) { System.out.println(true); } // Check for "three" at index 6. // ... Length is 5 chars. if (codes.regionMatches(6, "three", 0, 5)) { System.out.println(true); } // Check for "FOUR" from "IS_FOUR" at index 11. // ... Length is 4 chars. if (codes.regionMatches(true, 11, "IS_FOUR", 3, 4)) { System.out.println(true); } } } Output true true true
ValueOf. This static method converts a value (like an int or boolean) into a String. We do not call it on a String instance—instead we use the String class itself.
Tip: We must use the equals method to compare the Strings. This compares their contents, not just references.
Java program that uses valueOf public class Program { public static void main(String[] args) { // Convert 100 to a String and test it. String value = String.valueOf(100); if (value.equals("100")) { System.out.println(true); } // Convert "false" to a String. String literal = String.valueOf(false); if (literal.equals("false")) { System.out.println(true); } } } Output true true
Trim. This method removes whitespace on the start and end of a String. Newlines, spaces and tabs are removed. Trim() returns a newly-created string, unless nothing is changed.
Java that uses trim public class Program { public static void main(String[] args) { String value = " Cat\n"; String trimmed = value.trim(); // Trim the String. System.out.println("[" + value + "]"); System.out.println("[" + trimmed + "]"); } } Output [ Cat ] [Cat]
IsEmpty. An empty String is not null. It has a length of zero. The isEmpty method is simple: it checks the length, and if greater than zero, returns true. It makes programs easier to read.
Java that uses isEmpty public class Program { public static void main(String[] args) { String value1 = ""; // This has length 0. String value2 = " "; // This is a space. if (value1.isEmpty()) { System.out.println("value1 is empty"); } if (value2.isEmpty()) { System.out.println("not reached"); } } } Output value1 is empty
StartsWith, endsWith. These methods test the starts and ends of Strings. They return true or false if the prefix (or suffix) we pass as an argument is present on the String.
Note: CharAt can also test the first or last chars in a string (one at a time). The metacharacters "^" and "$" in Regex also work.
Java that uses startsWith, endsWith public class Program { public static void main(String[] args) { // Test the startsWith method on this String. String value = "cat"; if (value.startsWith("ca")) { System.out.println(true); } if (!value.startsWith("xy")) { System.out.println(false); } // Try the endsWith method. String value2 = "dog"; if (value2.endsWith("og")) { System.out.println(true); } } } Output true false true
Matches. This method receives a Regex string. If the pattern we supply matches the string we call matches() on, we get a true result. Otherwise it returns false.
Note: Matches() is the same as calling Pattern.matches directly. But this syntax may be easier to use in programs.
Java that uses matches public class Program { public static void main(String[] args) { String value = "carrots"; // This regular expression matches. boolean result1 = value.matches("c.*s"); System.out.println(result1); // This regular expression does not match. boolean result2 = value.matches("c.*x"); System.out.println(result2); } } Output true false
Equals, equalsIgnoreCase. We two Strings must be compared with equals() or equalsIgnoreCase. If we use the equality operator == only the references are compared.
Concat. The plus sign can be used to concatenate strings. This appends one string to another. But concat(), a method, can also be directly called.
Substring. With this method, we take part of a String. We specify a begin index and an end index (not a length or count of the substring). SubSequence is related.
Truncate: The substring method will cause exceptions if we use a last index that is too long. With truncate() we can avoid this problem.
Between: We can find substrings between, before and after other ones with the substring method and indexOf().
IndexOf. With indexOf and its friend lastIndexOf, we search Strings for characters or substrings. These methods start from the left or right.
Split. This method separates strings into parts based on a delimiter pattern. Split supports regular expressions (Regex) so it is powerful. It handles multiple-character delimiters.
Join. This method merges together strings that are separate. It is the opposite of split. With it, we specify a delimiter String.
Replace. We have flexibility in how we replace strings. With replace(), we can target chars, substrings (CharSequences) or Regex pattern matches.
HTML: The replaceAll method can be used to remove HTML tags. It uses a simple regular expression.
Arrays. The internal data, the characters, of a String can be thought of as an array. And with built-in methods, we can convert Strings into, and from, different types of arrays.
Byte array: With the String constructor and the String's getBytes method, we have conversions between bytes and Strings.
Char array: The String constructor converts a char array into a String. With toCharArray we convert a String into a char array.
StringBuilder. When we append to a String, a new one is created. Strings are immutable: to change them, we must copy them. The StringBuilder type is faster. It has a mutable buffer.
Character. Strings are composed of little values called characters. With the Character class, we test and manipulate chars. With Character.isDigit, for example, we test for digits.
Whitespace. Strings often contain whitespace characters, and the trim() method does not handle all problems with whitespace. We convert UNIX and Windows newlines.
Whitespace: methodsWhitespace: newlines, lineSeparator
Uppercase first letter. With toUpperCase we change all letters in a String. But often we want to modify just the first letter, or the first letter of individual words.
StringTokenizer. Java is full of old things we should not use. StringTokenizer is one example. Its functionality is easily replaced with split() but it exists for backwards compatibility.
Reverse. Strings cannot be easily manipulated in their initial form. Instead we transform them to a char array. In this way we can even reverse them.
Data. A String can represent any data. But textual representation is rarely the most efficient form. Instead, directly storing numbers as ints is faster.
With parseInt, an Integer method, we convert from a String to an Integer. This makes further operations on the number easier, faster. A String is just one representation.