Pure Programmer
Blue Matrix

Cluster Map



This page is under construction. Please come back later.

At their heart, a string is simply a sequence of characters. Characters, in turn, are encoded as integers using encoding schemes such as [[ASCII]], [[ISO-Latin-1]] or [[Unicode]]. So a string is simply a sequence of integers. Languages like FORTRAN or C that don't support strings as a fundamental type, actually treat strings as a sequence of integers. Modern programming languages support strings as a fundamental data type which make them much easier to use and manipulate.

Strings are particularly useful when conveying information to the user in contrast to being useful for computation like integers or floating point values. While strings are typically implemented as an array/list of the more basic character type, modern languages provide a string data type that encapsulates the characters of a string and provide functionality for working with strings. When using strings in our programs there are two types of strings: [[literal]] strings and string variables.

Variables and Literals

String literals are string values that are directly written in the program itself. String literals only represent the one string as it is typed into the code. String literals are enclosed in double quotes in contrast to character literals which are enclosed in single quotes. String literals can be used any place a string is required.

"Hello, world!"
"My name is: "
"Four score and seven years ago..."
'z'				// This is not a string literal but a character literal

Example String Literals

String variables are like any other variable. This means that string variables must be declared before they can be used and must follow the variable naming rules discussed in the variables section. that is they can be set and reset to different values at will. Unlike variables of the primitive types such as boolean, integer and floating point, string variables represent an entire string of characters. String variables can be set using string literals or other string variables.


One of the most basic operations we can perform on strings is called concatenation. Concatenation takes two strings and forms a new one by appending the second string on to the end of the first string. Using concatenation we can build up a complex string from small strings. In Java the concatenation operator is the + (plus) symbol.

 * This program demonstrates string concatenation.
 * Copyright © 2020 Richard Lesh.  All rights reserved.

public class Strings1 {

	public static void main(String[] args) {
		final String a = "one";
		final String b = "two";
		final String c = "three";
		String d = a + b + c;
		d = a + "\t" + b + "\n" + c;

$ javac -Xlint Strings1.java $ java -ea Strings1 onetwothree one two three

Operations on Strings

Java supports a number of operations on strings. The most often used is determining the length of a string. [an error occurred while processing this directive] Counting the characters in a string is accomplished using the length() method. Some of the other string operations available are summarized in the following table.

String Operations
Fixed PointScientific Notation
 * This program demonstrates basic string functions.
 * Copyright © 2020 Richard Lesh.  All rights reserved.

import org.pureprogrammer.Utils;

public class Strings2 {

	public static void main(String[] args) {
		final String alphabet = "abcdefghijklmnopqrstuvwxyzabc";
		final String greekAlphabet = "αβγδεζηθικλμνξοπρσςτυφχψωαβγ";
		final String emoji = "😃😇🥰🤪🤑😴🤒🥵🥶🤯🥳😎😥😱😡🤬💀👽🤖😺🙈🙉🙊😃😇🥰";

		System.out.println("Length: " + Utils.cpLength(alphabet));
		System.out.println("charAt(17): " + Utils.uniAt(alphabet, 17));
		System.out.println("codePointAt(17): " + Utils.cpAt(alphabet, 17));
		System.out.println("substr(23, 26): " + Utils.cpSubstring(alphabet, 23, 26));
		System.out.println("prefix(6): " + Utils.cpSubstring(alphabet, 0, 6));
		System.out.println("right_tail(6): " + Utils.cpSubstring(alphabet, 6));
		System.out.println("suffix(6): " + Utils.cpSubstring(alphabet, Utils.cpLength(alphabet) - 6));
		System.out.println("find(\'def\'): " + Utils.cpIndexOf(alphabet, "def"));
		System.out.println("find(\'def\') is not found: " + (Utils.cpIndexOf(alphabet, "def") == -1));
		System.out.println("find(\'bug\'): " + Utils.cpIndexOf(alphabet, "bug"));
		System.out.println("find(\'bug\') is not found: " + (Utils.cpIndexOf(alphabet, "bug") == -1));
		System.out.println("rfind(\'abc\'): " + Utils.cpLastIndexOf(alphabet, "abc"));
		System.out.println("rfind(\'abc\') is not found: " + (Utils.cpLastIndexOf(alphabet, "abc") == -1));
		System.out.println("rfind(\'bug\'): " + Utils.cpLastIndexOf(alphabet, "bug"));
		System.out.println("rfind(\'bug\') is not found: " + (Utils.cpLastIndexOf(alphabet, "bug") == -1));

		System.out.println("Length: " + Utils.cpLength(greekAlphabet));
		System.out.println("charAt(17): " + Utils.uniAt(greekAlphabet, 17));
		System.out.println("codePointAt(17): " + Utils.cpAt(greekAlphabet, 17));
		System.out.println("substr(23, 26): " + Utils.cpSubstring(greekAlphabet, 23, 26));
		System.out.println("prefix(6): " + Utils.cpSubstring(greekAlphabet, 0, 6));
		System.out.println("right_tail(6): " + Utils.cpSubstring(greekAlphabet, 6));
		System.out.println("suffix(6): " + Utils.cpSubstring(greekAlphabet, Utils.cpLength(greekAlphabet) - 6));
		System.out.println("find(\'δεζ\'): " + Utils.cpIndexOf(greekAlphabet, "δεζ"));
		System.out.println("find(\'δεζ\') is not found: " + (Utils.cpIndexOf(greekAlphabet, "δεζ") == -1));
		System.out.println("find(\'bug\'): " + Utils.cpIndexOf(greekAlphabet, "bug"));
		System.out.println("find(\'bug\') is not found: " + (Utils.cpIndexOf(greekAlphabet, "bug") == -1));
		System.out.println("rfind(\'αβγ\'): " + Utils.cpLastIndexOf(greekAlphabet, "αβγ"));
		System.out.println("rfind(\'αβγ\') is not found: " + (Utils.cpLastIndexOf(greekAlphabet, "αβγ") == -1));
		System.out.println("rfind(\'bug\'): " + Utils.cpLastIndexOf(greekAlphabet, "bug"));
		System.out.println("rfind(\'bug\') is not found: " + (Utils.cpLastIndexOf(greekAlphabet, "bug") == -1));

 * Because strings are represented using UTF-16 it takes two characters to
 * represent one codepoint for these emoji.  So lengths and positions are twice
 * what we normally would expect when dealing with Unicode characters.  So the
 * standard string functions basically only work correctly with chraracters from
 * the BMP.  Use the functions from Utils module to work correctly with all 
 * Unicode characters.
		System.out.println("Length: " + Utils.cpLength(emoji));
		System.out.println("charAt(16): " + Utils.uniAt(emoji, 16));
		System.out.println("codePointAt(16): " + Utils.cpAt(emoji, 16));
		System.out.println("substr(20, 24): " + Utils.cpSubstring(emoji, 20, 24));
		System.out.println("prefix(6): " + Utils.cpSubstring(emoji, 0, 6));
		System.out.println("right_tail(6): " + Utils.cpSubstring(emoji, 6));
		System.out.println("suffix(6): " + Utils.cpSubstring(emoji, Utils.cpLength(emoji) - 6));
		System.out.println("find(\'😱😡🤬\'): " + Utils.cpIndexOf(emoji, "😱😡🤬"));
		System.out.println("find(\'😱😡🤬\') is not found: " + (Utils.cpIndexOf(emoji, "😱😡🤬") == -1));
		System.out.println("find(\'bug\'): " + Utils.cpIndexOf(emoji, "bug"));
		System.out.println("find(\'bug\') is not found: " + (Utils.cpIndexOf(emoji, "bug") == -1));
		System.out.println("rfind(\'😃😇🥰\'): " + Utils.cpLastIndexOf(emoji, "😃😇🥰"));
		System.out.println("rfind(\'😃😇🥰\') is not found: " + (Utils.cpLastIndexOf(emoji, "😃😇🥰") == -1));
		System.out.println("rfind(\'bug\'): " + Utils.cpLastIndexOf(emoji, "bug"));
		System.out.println("rfind(\'bug\') is not found: " + (Utils.cpLastIndexOf(emoji, "bug") == -1));

$ javac -Xlint Strings2.java $ java -ea Strings2 Length: 29 charAt(17): r codePointAt(17): 114 substr(23, 26): xyz prefix(6): abcdef right_tail(6): ghijklmnopqrstuvwxyzabc suffix(6): xyzabc find('def'): 3 find('def') is not found: false find('bug'): -1 find('bug') is not found: true rfind('abc'): 26 rfind('abc') is not found: false rfind('bug'): -1 rfind('bug') is not found: true Length: 28 charAt(17): σ codePointAt(17): 963 substr(23, 26): ψωα prefix(6): αβγδεζ right_tail(6): ηθικλμνξοπρσςτυφχψωαβγ suffix(6): χψωαβγ find('δεζ'): 3 find('δεζ') is not found: false find('bug'): -1 find('bug') is not found: true rfind('αβγ'): 25 rfind('αβγ') is not found: false rfind('bug'): -1 rfind('bug') is not found: true Length: 26 charAt(16): 💀 codePointAt(16): 128128 substr(20, 24): 🙈🙉🙊😃 prefix(6): 😃😇🥰🤪🤑😴 right_tail(6): 🤒🥵🥶🤯🥳😎😥😱😡🤬💀👽🤖😺🙈🙉🙊😃😇🥰 suffix(6): 🙈🙉🙊😃😇🥰 find('😱😡🤬'): 13 find('😱😡🤬') is not found: false find('bug'): -1 find('bug') is not found: true rfind('😃😇🥰'): 23 rfind('😃😇🥰') is not found: false rfind('bug'): -1 rfind('bug') is not found: true

Comparing Strings

Like numeric types, string types are comparable. This means that we can order strings and determine which ones are lower and which ones are higher in that ordering. Strings are ordered using [[Lexicographical Order]] also know as Alphabetic or Dictionary Order. This is done by comparing the first characters of the two strings to determine which string is lower and which is higher. If the first characters are the same, we move on to the second character in each string and so on until a difference is found. Shorter strings always compare lower than a longer string that has the lower string as its prefix. Java has two methods that determine if two strings are equal to each other: equals() and equalsIgnoreCase(). Additionally we have the compareTo() and compareToIgnoreCase() methods that returns a negative value if the first string is less than the second, a positive value if the first string is greater than the second, and 0 if the two strings are equal.

 * This program demonstrates string comparisons.
 * Copyright © 2020 Richard Lesh.  All rights reserved.

public class Strings3 {

	public static void main(String[] args) {
		final String color1 = "Blue";
		final String color2 = "Red";
		boolean result;

		System.out.println("compare(color1, color2): " + color1.compareTo(color2));
		result = color1.compareTo(color2) < 0;
		System.out.println("color1 < color2: " + result);
		result = color1.compareTo(color2) > 0;
		System.out.println("color1 > color2: " + result);
		result = color1.equals(color2) ;
		System.out.println("color1 == color2: " + result);
		result = !color1.equals(color2) ;
		System.out.println("color1 != color2: " + result);

$ javac -Xlint Strings3.java $ java -ea Strings3 compare(color1, color2): -16 color1 < color2: true color1 > color2: false color1 == color2: false color1 != color2: true

Character Types

Often it is necessary to determine what class an individual character belongs. Character classes such as alphabetic, numeric, whitespace, control and punctuation are common classes of characters in which we would be interested. The following table illustrates how we would determine the class of a character.

 * This program illustrates some of the string functions in Utils
 * Copyright © 2020 Richard Lesh.  All rights reserved.

import org.pureprogrammer.Utils;

public class Strings4 {

	static final String ltrstr = "   Spaces to the left";
	static final String rtrstr = "Spaces to the right  ";
	static final String trimstr = "   Spaces at each end   ";
	static final String blank = "  \t\n  ";
	static final String lowerstr = "This String is Lowercase";
	static final String upperstr = "This String is Uppercase";

	public static void main(String[] args) {
		System.out.println("|" + Utils.ltrim(ltrstr) + "|");
		System.out.println("|" + Utils.rtrim(rtrstr) + "|");
		System.out.println("|" + Utils.trim(trimstr) + "|");
		System.out.println("|" + Utils.trim(blank) + "|");
		System.out.println("|" + lowerstr.toLowerCase() + "|");
		System.out.println("|" + upperstr.toUpperCase() + "|");

$ javac -Xlint Strings4.java $ java -ea Strings4 |Spaces to the left| |Spaces to the right| |Spaces at each end| || |this string is lowercase| |THIS STRING IS UPPERCASE|
Character Classification
isalnum(c)Check if character is alphanumeric.
isalpha(c)Check if character is alphabetic.
isblank(c)Check if character is blank.
iscntrl(c)Check if character is a control character.
isdigit(c)Check if character is decimal digit.
isgraph(c)Check if character has graphical representation.
islower(c)Check if character is lowercase letter.
isprint(c)Check if character is printable.
ispunct(c)Check if character is a punctuation character.
isspace(c)Check if character is a white-space.
isupper(c)Check if character is uppercase letter.
isxdigit(c)Check if character is hexadecimal digit.

Character Conversion
tolower(c)Returns lowercase version of the character.
toupper(c)Returns uppercase version of the character.
explain StringBuffer or StringBuilder



More ★'s indicate higher difficulty level.