Sage-Code Laboratory
index<--

Java Strings

In the Java programming language, strings are objects. Java platform provides the String class to create and manipulate strings. Java strings are UTF encoded, immutable sequences of characters.

Declare Strings

The most direct way to create a string is to initialize the string with a literal.

String greeting = "Hello world!";
Note: The compiler creates automatically a String object for the string literal. So the initialization just point to the memory location where the string already exists. No need to use "New" to allocate new memory.

Building a Strings

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

/* we declare an array first "helloArray" then a string */
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
String helloString = new String(helloArray);
System.out.println(helloString); // expect: hello world
Note: The String class is immutable. Once it is created a String object cannot be changed. The String class has a number of methods, that appear to modify strings. What these methods really do is create a new string object that contains the result of the operation. The old string remains in memory as garbage.

Longer Strings

Java programming language enable strings to span multiple lines. of code. This is a special feature in Java called "text block". These are triple quoted strings, similar to Python.

Text block:

/* multi-line strings */
public class TextBlock {
  public static void main(String[] args) {
    System.out.println('T');
    var text = """
        This is a text block.
        You can use %s formatted()
        with text block templates.
        """.formatted("method");
    System.out.println(text);
  }
}

In this example the position of the triple quotes is very important. The intentation is removed and the %s placeholder is replaced by "method". A triple quoted string is handled almost like a normal string.

This is a text block.
You can use method formatted()
with text block templates.

Notes: There are many details related to text blocks, but the most intresting is that extra indentation and triling spaces are detected and automaticly removed by the compiler using a special logic as in next example:
void writeHTML() {
    String html = """
········    <html>
········        <body>
········            <p>Hello World.</p>
········        </body>
········    </html>
········""";
    System.out.print(html);
}

In this example I have used dots instead of spaces for extra indentation that is removed by the compiler. The position of the triple quotes is very important for this to happen correctly.


    <html>
        <body>
            <p>Hello World.</p>
        </body>
    </html>

External article: Java Text Blocks

Concatenate Strings

The String class includes a method for concatenating two strings. You can use the concat() method with string literals or variables. Since a string literal is an object, we can use dot operator to invoke its method: .concat() like in example below:

/* concatenate two strings */
String quote =
    "Now is the time for all good " +
    "men to come to the aid of their country.";

String result = "My message is: ".concat("Hello, world!");

Formatting & Printing

We saw the use of the println() and print() methods for printing strings to standard output (System.out). We could use string concatenation to print smarter messages. What if we have some numbers to print? We must convert the number to string then concatenate. That is a lot of code to write. Is there a better way?

Yes there is! Java has other methods, however, that allow you to exercise much more control over your print output when numbers are included. The java.io package includes a PrintStream class that has two formatting methods that you can use to replace print and println. These methods are: format and printf.

Format Method:

public PrintStream format(String format, Object... args)

Parameter: "format" is a string that specifies the formatting to be used and args is a list of the variables to be printed using that formatting. It is a string that has inside so called: "format specifiers" that are replaced by strings to produce a result.

Format specifiers begin with a percent sign (%) and end with a converter. The converter is a character indicating the type of argument to be formatted. In between the percent sign (%) and the converter you can have optional flags and specifiers. There are many converters, flags, and specifiers, which are documented in java.util.Formatter.

Ok, here is a basic example:

/* printing a string */
int i = 461012;
System.out.format("The value of i is: %d%n", i);

Notes:

Output:

The value of i is: 461012
Other format options:

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.

/* testing length() method */
String test = "Hello World!";
int len = test.length(); //expected 12

Comparing Strings

String class has a number of methods for comparing strings and portions of strings. The following table lists these methods.

Method Description
boolean endsWith(String suffix)
boolean startsWith(String prefix)
Returns true if this string ends with or begins with the substring specified as an argument to the method.
boolean startsWith(String prefix, int offset) Considers the string beginning at the index offset, and returns true if it begins with the substring specified as an argument.
int compareTo(String anotherString) Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring differences in case. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
boolean equals(Object anObject) Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.
boolean equalsIgnoreCase(String anotherString) Returns true if and only if the argument is a String object that represents the same sequence of characters as this object, ignoring differences in case.
boolean regionMatches(int toffset, String other, int ooffset, int len) Tests whether the specified region of this string matches the specified region of the String argument.

Region is of length len and begins at the index toffset for this string and ooffset for the other string.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Tests whether the specified region of this string matches the specified region of the String argument.

Region is of length len and begins at the index toffset for this string and ooffset for the other string.

The boolean argument indicates whether case should be ignored; if true, case is ignored when comparing characters.

boolean matches(String regex) Tests whether this string matches the specified regular expression. Regular expressions are discussed in the lesson titled "Regular Expressions."

Caution:You can not use regular comparison operators like: "==" and "!=" for strings. Strings are objects, therefore using these operators will compare references (pointers) and not the string values. If you do, you will end-up with logical errors.

Example:

We define several strings, initialize them with values and then using method equal() we compare them.

/* Java program to Compare two strings */
public class Main {
    public static void main(String args[])
    {
        String string1 = new String("Sage-Code");
        String string2 = new String("sage-code");
        String string3 = new String("test");
        String string4 = new String("Test");
        String string5 = new String("test");

        // Comparing for String 1 != String 2
        System.out.println("Comparing " + string1 + " and " + string2
                           + " : " + string1.equals(string2));

        // Comparing for String 3 = String 4
        System.out.println("Comparing " + string3 + " and " + string4
                           + " : " + string3.equals(string4));

        // Comparing for String 4 != String 5
        System.out.println("Comparing " + string4 + " and " + string5
                           + " : " + string4.equals(string5));

        // Comparing for String 1 != String 4
        System.out.println("Comparing " + string1 + " and " + string4
                           + " : " + string1.equals(string4));
        // Comparing for String 3 == String 4
        System.out.println("Comparing " + string3 + " and " + string5
                           + " : " + string3.equals(string5));
    }
}

Output:

Comparing Sage-Code and sage-code : false
Comparing test and Test : false
Comparing Test and test : false
Comparing Sage-Code and Test : false
Comparing test and test : true

Palindrome Inversion

Let's invert a palindrome that is hard-coded as a string literal. We use String method charAt() to locate a character in a string. After you investigate the example, get ready to do a short homework:

/* palindrome string invertor */
class Main {
    public static void main(String[] args) {
        String palindrome = "murder for a jar of red rum";
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];

        // copy original string in array
        for (int i = 0; i < len; i++) {
            tempCharArray[i] =
                palindrome.charAt(i);
        }

        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }

        String reversePalindrome =
            new String(charArray);
        System.out.println(reversePalindrome);
    }
}

Homework:Let's have some fun by doing this homework on-line. open on repl.it and run it, then change the palindrome with one from the next list, and run it again. Is the palindrome perfect?

Other funny palindromes to try:


Read Next: Arrays