knowledge-kitchen

Object-Orientation - String & Related Classes (in Java)

We are all instruments endowed with feeling and memory. Our senses are so many strings that are struck by surrounding objects and that also frequently strike themselves.

Denis Diderot

  1. Overview
  2. String Class
  3. Immutability
  4. Character Class
  5. StringBuilder Class
  6. Apache Commons Lang
  7. Apache Commons Text
  8. Apache Commons CSV
  9. Conclusions

Overview

Concept

The term ‘String’, used in programming to indicate a ‘string of characters’, first came into regular usage in the mid 1960’s, as languages such as Lisp allowed textual data processing to flourish. A more general meaning, to order a series of mathematical values, as if beads on a string, dates possibly to the 1930’s.

String Class

Instantiation

Like all objects in Java, Strings can be instantiated using the new operator and passing the constructor a char array.

char[] charr = { 'w','o','r','r','y',' ', 'n','o','t' };
String myMessageToYou = new String(charr);

How to get a String object

Rather than directly instantiating a String object, there are many operations and functions in the Java API that instantiate new String objects on our behalf, e.g.

How to get a String object (continued)

Of course, the + operator can be used to concatenate two Strings:

String myMessageToYou = "worry" + " " + "not";

.toString( ) methods

And every class can optionally declare a method named toString() that indicates how an object of that class should be converted to a String.

public class Moped {
    // ...
    public String toString() {
        return String.format(
            "A moped at %s & %s facing %s",
            this.getStreet(),
            this.getAvenue(),
            this.getOrientation()
        )
    }
    // ...
}
// ... assume we instantiated a Moped object ...
System.out.println( myMoped ); // output it as a String

.toString( ) methods (continued)

Even if you don’t define a .toString() method in your custom classes, one exists automatically anyway.

//...
public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
//...

What’s inside a String?

There are several useful functions for investigating the internals of a String.

Comparing two Strings

Comparing two strings can be done in a few different styles.

Immutability

Concept

String objects are immutable - once they have been instantiated, their contents cannot be changed.

public class ImmutableDog {
    public ImmutableDog( String name, String breed, int age ) {
        this.setName(name);
        this.setBreed(breed);
        this.setAge(age);
    }
    // ... assume we define private setter methods
}

Character Class

Concept

The Character class is a wrapper class, used to do processing and analysis of char primitive values, e.g.

StringBuilder Class

Concept

Since Strings are immutable, concatening many Strings together or modifying the contents of a String tends to require a lot of code and more memory than it should. Enter StringBuilder.

Extracting the String from StringBuilder

Converting the contents of a StringBuilder to a regular String is a facile matter.

Apache Commons Lang

Patching the Java API

Java, remarkable though it is, is lacking in many basic functionality today’s programmers might expect. Apache Commons Lang attempts to fill in many of those gaps.

StringUtils is one class in the Apache Commons Lang library that might be of interest to us here.

StringUtils Examples

// align the text "foo" within 10 spaces
String s1 = StringUtils.center("foo", 10); // -> "   foo    "
String s2 = StringUtils.leftPad("foo", 10); // -> "foo       "
String s3 = StringUtils.rightPad("foo", 10); // -> "       foo"
// check whether a string is uppercase or has all alphabetic or numeric characters
boolean isUps = StringUtils.isAllUpperCase("help"); // -> false
boolean isAlphas = StringUtils.isAlpha("abcdef"); // -> true
boolean isNums = StringUtils.isNumeric("12345"); // -> true
boolean isAlphaNums = StringUtils.isAlphanumeric("abcdef12345"); // -> true
// join an array
String[] foo = {"foo", "bar", "baz", "bum"};
String s = StringUtils.join(foo, ","); // -> "foo,bar,baz,bum"

Full documentation of StringUtils here.

Apache Commons Text

Concept

Similar to Commons Lang, Apache’s Commons Text project aims to give developers access to common string algorithms and processes that are not supported by the Java API or the various text-related classes added by Commons Lang.

Classes

Classes include:

Apache Commons CSV

Concept

Commons CSV is another project by Apache to make dealing with CSV (comma- or character-separated values) text files easier.

Conclusions

You now have increased your knowledge of the String and related classes as examples of typical object-oriented Java classes.