ZetCode

Java String

last modified March 18, 2021

Java String tutorial shows how to work with strings in Java using String and StringBuilder.

Java string definition

In Java, a string is a sequence of Unicode characters. Strings are objects. There are two basic classes for working with strings:

String is an immutable sequence of characters. StringBuilder is a mutable sequence of characters. (There is also a StringBuffer class which can be used by multiple threads. If we are not dealing with threads, we use the StringBuilder.)

A string literal a series of characters in the source code that is enclosed in double quotes. For example, "Java" is a string literal. Whenever Java compiler encounters a string literal in the code, it creates a String object with its value.

String lang = "Java"; // same as String lang = new String("Java");

String literals are used by many programming languages. It is an established convention and it also saves typing.

Java initializing strings

There are multiple ways of creating strings, both immutable and mutable. We will show a few of them.

com/zetcode/StringInit.java
package com.zetcode;

public class StringInit {

    public static void main(String[] args) {

        char[] cdb = {'M', 'y', 'S', 'Q', 'L'};

        String lang = "Java";
        String ide = new String("NetBeans");
        String db = new String(cdb);

        System.out.println(lang);
        System.out.println(ide);
        System.out.println(db);

        StringBuilder sb1 = new StringBuilder(lang);
        StringBuilder sb2 = new StringBuilder();
        sb2.append("Fields");
        sb2.append(" of ");
        sb2.append("glory");

        System.out.println(sb1);
        System.out.println(sb2);
    }
}

The example shows a few ways of creating String and StringBuilder objects.

String lang = "Java";

The most common way is to create a string object from a string literal.

String ide = new String("NetBeans");

In this line, we create a string using the usual way of building objects — with the new keyword.

String db = new String(cdb);

Here we create a string object from an array of characters.

StringBuilder sb1 = new StringBuilder(lang);

A StringBuilder object is created from a String.

StringBuilder sb2 = new StringBuilder();
sb2.append("Fields");
sb2.append(" of ");
sb2.append("glory");

We create an empty StringBuilder object. We append three strings into the object.

$ java StringInit.java
Java
NetBeans
MySQL
Java
Fields of glory

Java string is an object

Strings are objects; they are not primitive data types. Strings are instances of the String or StringBuilder class. Since they are objects, they have multiple methods available for doing various work.

com/zetcode/StringObjects.java
package com.zetcode;

public class StringObjects {

    public static void main(String[] args) {

        String lang = "Java";

        String bclass = lang.getClass().toString();
        System.out.println(bclass);

        String sup = lang.getClass().getSuperclass().toString();
        System.out.println(sup);

        if (lang.isEmpty()) {

            System.out.println("The string is empty");
        } else {

            System.out.println("The string is not empty");
        }

        int l = lang.length();
        System.out.println("The string has " + l + " characters");
    }
}

In this program, we demonstrate that strings are objects. Objects must have a class name, a parent class, and they must also have some methods that we can call.

String lang = "Java";

An object of String type is created.

String bclass = lang.getClass().toString();

We determine the class name of the object to which the lang variable refers.

String sup = lang.getClass().getSuperclass().toString();

A parent class of our object is received. All objects have at least one parent — the Object.

if (lang.isEmpty()) {

    System.out.println("The string is empty");
} else {

    System.out.println("The string is not empty");
}

Objects have various methods. One of the useful string methods is the isEmpty method, which determines whether the string is empty.

int l = lang.length();

The length method returns the size of the string.

$ java StringObjects.java
class java.lang.String
class java.lang.Object
The string is not empty
The string has 4 characters

Our string object is an instance of the String class. It has the Object parent class. The object is not empty and it contains four characters.

Java String length

It is not easy to determine the length of a Unicode string. The length method works only for certain Unicode characters.

com/zetcode/StringLength.java
package com.zetcode;

import java.text.BreakIterator;

public class StringLength {

    public static void main(String[] args) {

        var text1 = "falcon";
        var n1 = text1.length();

        System.out.printf("%s has %d characters%n", text1, n1);

        System.out.println("----------------------------");

        var text2 = "вишня";
        var n2 = text2.length();
        System.out.printf("%s has %d characters%n", text2, n2);

        System.out.println("----------------------------");

        var text3 = "🐺🦊🦝";
        var n3 = text3.length();
        System.out.printf("%s has %d characters%n", text3, n3);

        var n3_ = graphemeLength(text3);
        System.out.printf("%s has %d characters%n", text3, n3_);

        System.out.println("----------------------------");

        var text4 = "नमस्ते";

        var n4 = text4.length();
        System.out.printf("%s has %d characters%n", text4, n4);

        var n4_ = graphemeLength(text4);
        System.out.printf("%s has %d characters%n", text4, n4_);
    }

    public static int graphemeLength(String text) {

        BreakIterator it = BreakIterator.getCharacterInstance();
        it.setText(text);

        int count = 0;

        while (it.next() != BreakIterator.DONE) {
            count++;
        }

        return count;
    }
}

In the example, we try to determine the length of various text.

var text1 = "falcon";
var n1 = text1.length();

For basic latin characters, the length method works OK.

var text2 = "вишня";
var n2 = text2.length();

It also works OK for this cyrillic text.

var text3 = "🐺🦊🦝";
var n3 = text3.length();

For emojis, we get a wrong result with length.

var n3_ = graphemeLength(text3);

With BreakIterator used in graphemeLength, we get the correct result for emojis.

var text4 = "नमस्ते";

var n4 = text4.length();
System.out.printf("%s has %d characters%n", text4, n4);

var n4_ = graphemeLength(text4);
System.out.printf("%s has %d characters%n", text4, n4_);

However for sanskrit, both methods return a wrong result. (The correct answer is four characters.)

$ java StringLength.java
falcon has 6 characters
----------------------------
вишня has 5 characters
----------------------------
🐺🦊🦝 has 6 characters
🐺🦊🦝 has 3 characters
----------------------------
नमस्ते has 6 characters
नमस्ते has 3 characters

Java mutable & immutable strings

The String is a sequence of immutable characters, while the StringBuilder is a sequence of mutable characters. The next example will show the difference.

com/zetcode/MutableImmutable.java
package com.zetcode;

public class MutableImmutable {

    public static void main(String[] args) {

        String name = "Jane";
        String name2 = name.replace('J', 'K');
        String name3 = name2.replace('n', 't');

        System.out.println(name);
        System.out.println(name3);

        StringBuilder sb = new StringBuilder("Jane");
        System.out.println(sb);

        sb.setCharAt(0, 'K');
        sb.setCharAt(2, 't');

        System.out.println(sb);
    }
}

Both objects have methods for replacing characters in a string.

String name = "Jane";
String name2 = name.replace('J', 'K');
String name3 = name2.replace('n', 't');

Calling the replace method on a String results in returning a new modified string. The original string is not changed.

sb.setCharAt(0, 'K');
sb.setCharAt(2, 't');

The setCharAt method of a StringBuilder will replace a character at the given index with a new character. The original string is modified.

$ java MutableImmutable.java
Jane
Kate
Jane
Kate

Java String isBlank

The isBlank method returns true if the string is empty or contains only white space.

com/zetcode/StringBlank.java
package com.zetcode;

import java.util.List;

public class StringBlank {

    public static void main(String[] args) {

        var data = List.of("sky", "\n\n", "  ", "blue", "\t\t", "", "sky");

        for (int i=0; i<data.size(); i++) {

            var e = data.get(i);

            if (e.isBlank()) {
                System.out.printf("element with index %d is blank%n", i);
            } else {

                System.out.println(data.get(i));
            }
        }
    }
}

We go through a list of strings and print all blank elements.

$ java StringBlank.java
sky
element with index 1 is blank
element with index 2 is blank
blue
element with index 4 is blank
element with index 5 is blank
sky

Java concatenating strings

Immutable strings can be added using the + operator or the concat method. They will form a new string which is a chain of all concatenated strings. Mutable strings have the append method which builds a string from any number of other strings.

com/zetcode/ConcatenateStrings.java
package com.zetcode;

public class ConcatenateStrings {

    public static void main(String[] args) {

        System.out.println("Return" + " of " + "the king.");
        System.out.println("Return".concat(" of ").concat("the king."));

        StringBuilder sb = new StringBuilder();
        sb.append("Return");
        sb.append(" of ");
        sb.append("the king.");

        System.out.println(sb);
    }
}

The example creates three sentences by adding strings.

System.out.println("Return" + " of " + "the king.");

A new string is formed by using the + operator.

System.out.println("Return".concat(" of ").concat("the king."));

The concat method returns a string that represents the concatenation of this object's characters followed by the string argument's characters.

StringBuilder sb = new StringBuilder();
sb.append("Return");
sb.append(" of ");
sb.append("the king.");

A mutable object of the StringBuilder type is created by calling the append method three times.

$ java ConcatenateStrings.java
Return of the king.
Return of the king.
Return of the king.

Java string using quotes

In certain cases, such as using direct speech, the inner quotes must be escaped.

com/zetcode/Quotes.java
package com.zetcode;

public class Quotes {

    public static void main(String[] args) {

        System.out.println("There are may stars");
        System.out.println("He said: \"Which one are you looking at?\"");
    }
}

We use the \ character to escape additional quotes.

$ java Quotes.java
There are may stars
He said: "Which one are you looking at?"

Java multiline strings

Java 13 introduced text blocks, which allow to define multi-line strings. To create a multi-line string, we use triple quotes.

com/zetcode/MultilineStrings.java
package com.zetcode;

public class MultilineString {

    static String lyrics = """
        I cheated myself
        like I knew I would
        I told ya, I was trouble
        you know that I'm no good""";


    public static void main(String[] args) {

        System.out.println(lyrics);
    }
}

We have a strophe that spans four lines.

$ java MultilineString.java
I cheated myself
like I knew I would
I told ya, I was trouble
you know that I'm no good

In previous versions of Java, we need to do a concatenation operation and use the \n character.

com/zetcode/MultilineString2.java
package com.zetcode;

public class MultilineString2 {

    static String lyrics = "I cheated myself\n" +
"like I knew I would\n" +
"I told ya, I was trouble\n" +
"you know that I'm no good";


    public static void main(String[] args) {

        System.out.println(lyrics);
    }
}

The four strings are concatenated with the + operator.

Java string elements

A string is a sequence of characters. A character is a basic element of a string. The following two examples show some methods that work with characters of a string.

com/zetcode/StringElements.java
package com.zetcode;

public class StringElements {

    public static void main(String[] args) {

        char[] crs = {'Z', 'e', 't', 'C', 'o', 'd', 'e' };
        String s = new String(crs);

        char c1 = s.charAt(0);
        char c2 = s.charAt(s.length()-1);

        System.out.println(c1);
        System.out.println(c2);

        int i1 = s.indexOf('e');
        int i2 = s.lastIndexOf('e');

        System.out.println("The first index of character e is " + i1);
        System.out.println("The last index of character e is " + i2);

        System.out.println(s.contains("t"));
        System.out.println(s.contains("f"));

        char[] elements = s.toCharArray();

        for (char el : elements) {

            System.out.println(el);
        }
    }
}

In the first example, we will work with an immutable string.

char[] crs = {'Z', 'e', 't', 'C', 'o', 'd', 'e' };
String s = new String(crs);

A new immutable string is formed from an array of characters.

char c1 = s.charAt(0);
char c2 = s.charAt(s.length()-1);

With the charAt method, we get the first and the last char value of the string.

int i1 = s.indexOf('e');
int i2 = s.lastIndexOf('e');

With the indexOf and lastIndexOf methods, we get the first and the last occurrence of the character 'e'.

System.out.println(s.contains("t"));

With the contains method, we check if the string contains the t character. The method returns a boolean value.

char[] elements = s.toCharArray();

for (char el : elements) {

    System.out.println(el);
}

The toCharArray method creates a character array from the string. We go through the array and print each of the characters.

$ java StringElements.java
Z
e
The first index of character e is 1
The last index of character e is 6
true
false
Z
e
t
C
o
d
e

In the second example, we work with the elements of a StringBuilder class.

com/zetcode/StringBuilderElements.java
package com.zetcode;

public class StringBuilderElements {

    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder("Misty mountains");
        System.out.println(sb);

        sb.deleteCharAt(sb.length()-1);
        System.out.println(sb);

        sb.append('s');
        System.out.println(sb);

        sb.insert(0, 'T');
        sb.insert(1, 'h');
        sb.insert(2, 'e');
        sb.insert(3, ' ');
        System.out.println(sb);

        sb.setCharAt(4, 'm');
        System.out.println(sb);
    }
}

A mutable string is formed. We modify the contents of the string by deleting, appending, inserting, and replacing characters.

sb.deleteCharAt(sb.length()-1);

This line deletes the last character.

sb.append('s');

The deleted character is appended back to the string.

sb.insert(0, 'T');
sb.insert(1, 'h');
sb.insert(2, 'e');
sb.insert(3, ' ');

We insert four characters at the beginning of the string.

sb.setCharAt(4, 'm');

Finally, we replace a character at index 4.

$ java StringBuilderElements.java
Misty mountains
Misty mountain
Misty mountains
The Misty mountains
The misty mountains

Java String repeat

The repeat method returns a string that is repeated n times.

com/zetcode/StringRepeat.java
package com.zetcode;

public class StringRepeat {

    public static void main(String[] args) {

        var word = "falcon ";

        var output = word.repeat((5));
        System.out.println(output);
    }
}

In the example, we repeat the word five times.

$ java StringRepeat.java
falcon falcon falcon falcon falcon 

Java String lines

The lines method returns a stream of lines extracted from the string, separated by line terminators.

com/zetcode/StringLines.java
package com.zetcode;

public class StringLines {

    public static void main(String[] args) {

        var words = """
                club
                sky
                blue
                cup
                coin
                new
                cent
                owl
                falcon
                brave
                war
                ice
                paint
                water
                """;

        var wstream = words.lines();

        wstream.forEach(word -> {

            if (word.length() == 3) {
                System.out.println(word);
            }
        });
    }
}

We have fourteen words in the text block.

var wstream = words.lines();

With the lines method we create a stream of these words.

wstream.forEach(word -> {

    if (word.length() == 3) {
        System.out.println(word);
    }
});

We go over the stream with forEach and print all words having length of three letters.

$ java StringLines.java 
sky
cup
new
owl
war
ice

Java String startsWith

The startsWith checks if the string starts with the given prefix.

com/zetcode/StringStarts.java
package com.zetcode;

public class StringStarts {

    public static void main(String[] args) {

        var words = "club\nsky\nblue\ncup\ncoin\nnew\ncent\nowl\nfalcon\nwar\nice";

        var wstream = words.lines();
        wstream.forEach(word -> {

            if (word.startsWith("c")) {
                System.out.println(word);
            }
        });
    }
}

We have a couple of words in a string. We print all words that start with letter c.

$ java StringStarts.java 
club
cup
coin
cent

Java String endsWith

The endsWith method checks if the string ends with the specified suffix.

com/zetcode/StringEnds.java
package com.zetcode;

public class StringEnds {

    public static void main(String[] args) {

        var words = "club\nsky\nblue\ncup\ncoin\nnew\ncent\nowl\nfalcon\nwar\nice";

        var wstream = words.lines();
        wstream.forEach(word -> {

            if (word.endsWith("n") || word.endsWith("y")) {
                System.out.println(word);
            }
        });
    }
}

In the example, we print all words that end either with n or y.

$ java StringEnds.java
sky
coin
falcon

Java String toUpperCase/toLowerCase

The toUpperCase method converts all of the characters of the string to upper case. The toLowerCase method converts all of the characters of the string to lower case.

com/zetcode/StringUpperLower.java
package com.zetcode;

public class StringUpperLower {

    public static void main(String[] args) {

        var word1 = "Cherry";

        var u_word1 = word1.toUpperCase();
        var l_word1 = u_word1.toLowerCase();

        System.out.println(u_word1);
        System.out.println(l_word1);

        var word2 = "Čerešňa";

        var u_word2 = word2.toUpperCase();
        var l_word2 = u_word2.toLowerCase();

        System.out.println(u_word2);
        System.out.println(l_word2);
    }
}

We modify the case of two words.

$ java StringUpperLower.java
CHERRY
cherry
ČEREŠŇA
čerešňa

Java String matches

The matches method tells whether or not the string matches the given regular expression.

com/zetcode/StringMatch.java
package com.zetcode;

public class StringMatch {

    public static void main(String[] args) {

        var words = """
                book
                bookshelf
                bookworm
                bookcase
                bookish
                bookkeeper
                booklet
                bookmark
                """;

        var wstream = words.lines();

        wstream.forEach(word -> {
            if (word.matches("book(worm|mark|keeper)?")) {
                System.out.println(word);
            }
        });
    }
}

In the example, we print all the words that satisfy the specified subpatterns.

$ java StringMatch.java 
book
bookworm
bookkeeper
bookmark

Java Palindrome example

A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar. There are many ways to check if a string is a palindrome. The following example is one of the possible solutions.

com/zetcode/Palindrome.java
package com.zetcode;

// A palindrome is a word, number, phrase, or other sequence of characters
// which reads the same backward as forward, such as madam or racecar

public class Palindrome3 {

    public static void main(String[] args) {

        System.out.println(isPalindrome("radar"));
        System.out.println(isPalindrome("kayak"));
        System.out.println(isPalindrome("forest"));
    }

    private static boolean isPalindrome(String original) {

        char[] data = original.toCharArray();

        int i = 0;
        int j = data.length - 1;

        while (j > i) {

            if (data[i] != data[j]) {
                return false;
            }

            ++i;
            --j;
        }

        return true;
    }
}

We have an implementation of the isPalindrome method.

private static boolean isPalindrome(String original) {

    char[] data = original.toCharArray();
...

We turn the string into a array of characters.

int i = 0;
int j = data.length - 1;

while (j > i) {

    if (data[i] != data[j]) {
        return false;
    }

    ++i;
    --j;
}

return true;

We iterate through the array and compare the left side characters with the right side corresponding characters. If all match, we return true, otherwise we return false.

$ java Palindrome.java
true
true
false

Java substrings

The substring method returns a part of a string. The beginning index is inclusive, the ending index is exclusive. The beginning index starts from zero.

com/zetcode/Substrings.java
package com.zetcode;

public class Substrings {

    public static void main(String[] args) {

        String str = "bookcase";

        System.out.println(str.substring(0, 4));
        System.out.println(str.substring(4, str.length()));
    }
}

The example uses the substring method to create two substrings.

System.out.println(str.substring(0, 4));

Here we get the "book" substring. The zero refers to the first character of the string.

System.out.println(str.substring(4, str.length()));

Here the "case" substring is printed.

$ java Substrings.java
book
case

Java split string

The split method cuts a string into parts; it takes a delimiting regular expression as a parameter.

com/zetcode/Splitting.java
package com.zetcode;

public class Splitting {

    public static void main(String[] args) {

        String s = "Today is a beautiful day.";

        String[] words = s.split(" ");

        for (String word : words) {

            System.out.println(word);
        }
    }
}

The example splits a sentence into words.

String s = "Today is a beautiful day.";

This is a sentence to be split. The words are separated by a space character.

String[] words = s.split(" ");

Using the split method, we cut the sentence into words. The space character is used as a delimiter. The method returns an array of strings.

for (String word : words) {

    System.out.println(word);
}

We go throught the array and print its content.

$ java Splitting.java
Today
is
a
beautiful
day.

Java removing string characters

When we split a string into words, some words have starting or ending characters such as comma or dot. In the next example, we show how to remove such characters.

com/zetcode/RemovingChars.java
package com.zetcode;

public class RemovingChars {

    public static void main(String[] args) {

        String str = "Did you go there? We did, but we had a \"great\" service there.";

        String[] parts = str.split(" ");

        for (String part: parts) {

            String word = removeChars(part);
            System.out.println(word);
        }
    }

    private static String removeChars(String part) {

        String word = part;

        if (part.endsWith(".") || part.endsWith("?") || part.endsWith(",") 
                || part.endsWith("\"")) {
            word = part.substring(0, part.length()-1);
        }

        if (part.startsWith("\"")) {
            word = word.substring(1, part.length()-1);
        }

        return word;
    }
}

The example split a string into words and removes potential commas, dots, question marks, or double quotation marks.

String str = "Did you go there? We did, but we had a \"great\" service there.";

In this string, we have a question mark, a comma, quotation marks, and a dot attached to the words.

private static String removeChars(String part) {

Inside this custom method, we remove those characters from our words.

if (part.endsWith(".") || part.endsWith("?") || part.endsWith(",") 
    || part.endsWith("\"")) {
    word = part.substring(0, part.length()-1);
}

In this if statement, we remove the ending character. We use the endsWith method to identify the characters that we want to remove. The substring method returns a part of the string without the character.

if (part.startsWith("\"")) {
    word = word.substring(1, part.length()-1);
}

Also, we remove the starting characters. The starting character is checked with the startsWith method.

$ java RemovingChars.java
Did
you
go
there
We
did
but
we
had
a
great
service
there

Java joining strings

Since Java 8, we have a join method to join strings. Refer to StringJoiner tutorial to learn more about joining strings in Java.

com/zetcode/Joining.java
package com.zetcode;

public class Joining {

    public static void main(String[] args) {

        String joined = String.join(" ", "Today", "is", "Sunday");

        System.out.println(joined);
    }
}

In the example, we joing three strings into one final string.

String joined = String.join(" ", "Today", "is", "Sunday");

The first parameter of the join method is a delimiter that is going to separater each string in the final string. The rest of the parameters are strings to be joined.

Java comparing strings

There are two basic methods for comparing strings. The equals method compares the contents of two strings and returns a boolean value indicating, whether the strings are equal or not. The equalsIgnoreCase does the same thing, except that it ignores the case.

com/zetcode/ComparingStrings.java
package com.zetcode;

public class ComparingStrings {

    public static void main(String[] args) {

        String a = "book";
        String b = "Book";

        System.out.println(a.equals(b));
        System.out.println(a.equalsIgnoreCase(b));
    }
}

We compare two strings using the aforementioned methods.

String a = "book";
String b = "Book";

We define two strings that we compare.

System.out.println(a.equals(b));

The equals method returns false. The two strings differ in the first character.

System.out.println(a.equalsIgnoreCase(b));

When we ignore the case, the strings are equal: the equalsIgnoreCase method returns true.

$ java ComparingStrings.java
false
true

If we are comparing a variable to a string, it is important to remember that the string should be on the left side of the comparing method. Otherwise we might get a NullPointerException.

com/zetcode/ComparingStrings2.java
import java.util.Random;

public class ComparingStrings2 {

    public static String readString() {

        Random r = new Random();
        boolean b = r.nextBoolean();

        if (b == true) {

            return "ZetCode";
        } else {

            return null;
        }
    }

    public static void main(String[] args) {

        String d = readString();

        if ("ZetCode".equals(d)) {

            System.out.println("Strings are equal");
        } else {

            System.out.println("Strings are not equal");
        }
    }
}

In the code example, we compare the strings properly, avoiding a possible NullPointerException.

public static String readString() {

    Random r = new Random();
    boolean b = r.nextBoolean();

    if (b == true) {

        return "ZetCode";
    } else {

        return null;
    }
}

The readString method simulates the case where a method invocation can result in a null value. This could happen, for instance, if we try to read a value from a database.

String d = readString();

The d variable can contain the null value.

if ("ZetCode".equals(d)) {

The above line is the correct way of comparing two strings where one string is a known literal. If we placed the d variable on the left side, this would lead to NullPointerException if the d variable would contain the null value.

The equals method compares the characters of two strings. The == operator tests for reference equality. All string literals are interned automatically in Java. They are placed inside a string pool. This happens at compile time. If two variables contain two equal string literals, they in fact refer to the same string object inside a string pool.

com/zetcode/ComparingStrings3.java
package com.zetcode;

public class ComparingStrings3 {

    public static void main(String[] args) {

        boolean a = "ZetCode" == "ZetCode";
        boolean b = "ZetCode" == new String("ZetCode");
        boolean c = "ZetCode" == "Zet" + "Code";
        boolean d = "ZetCode" == new String("ZetCode").intern();
        boolean e = "ZetCode" == " ZetCode ".trim();

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        System.out.println(e);
    }
}

In this code example, we compare string objects with the == operator.

boolean a = "ZetCode" == "ZetCode";

These strings literals are interned. Therefore, the identity comparison operator returns true.

boolean b = "ZetCode" == new String("ZetCode");

Strings created with the new operator are not interned. The comparison operator results in a false value.

boolean c = "ZetCode" == "Zet" + "Code";

Strings are concatenated at compile time. The string literals result in the same object. The result is a true.

boolean d = "ZetCode" == new String("ZetCode").intern();

The intern object puts the string object on the right side into the pool. Therefore, the d variable holds a boolean true.

boolean e = "ZetCode" == " ZetCode ".trim();

The trim method is called at runtime, generating a distinct object. The e variable holds a boolean false.

$ java ComparingStrings3.java
true
false
true
true
false

Java formatting strings

We can use both System.out.printf and System.out.format methods to format strings in Java. They work the same. These two methods write a formatted string to the output stream using the specified format string and arguments. If there are more arguments than format specifiers, the extra arguments are ignored.

%[argument_index$][flags][width][.precision]conversion

The format specifiers for general, character, and numeric types have this syntax.

%[argument_index$][flags][width]conversion

This is the syntax for types which are used to represents dates and times.

The format specifiers begin with the % character and end with a 1 or 2 character conversion that specifies the kind of formatted output being generated. The optional items are placed between the square brackets.

The argument_index is a decimal integer indicating the position of the argument in the argument list. The flags is a set of characters that modify the output format. The set of valid flags depends on the conversion. The width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.

The precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion. The required conversion is a character indicating how the argument should be formatted.

com/zetcode/Conversions.java
package com.zetcode;

public class Conversions {

    public static void main(String[] args) {

        System.out.format("There are %d %s.%n", 5, "pencils");
        System.out.printf("The rock weighs %f kilograms.%n", 5.345);
    }
}

In this program, we format two simple sentences.

System.out.format("There are %d %s.%n", 5, "pencils");

In this code line, we have three format specifiers. Each specifier starts with the % character. The d specifier formats integer values. The s specifier expects string values. The %n outputs a platform-specific line terminator; it does not require an argument.

System.out.printf("The rock weighs %f kilograms.%n", 5.345);

The f formats a floating point value as a decimal value. The System.out.printf works the same as the System.out.format.

$ java Conversions.java
There are 5 pencils.
The rock weighs 5.345000 kilograms.
com/zetcode/IndexPosition.java
package com.zetcode;

import java.util.Calendar;

public class IndexPosition {

    public static void main(String[] args) {

        int x = 12;
        int y = 32;
        int z = 43;

        Calendar c = Calendar.getInstance();

        System.out.format("There are %d apples, %d oranges and "
                + "%d pears%n", x, y, z);

        System.out.format("There are %2$d apples, %3$d oranges and "
                + "%1$d pears%n", x, y, z);

        System.out.format("Year: %tY, Month: %<tm, Day: %<td%n", c);
    }
}

The example uses argument index to refer to variables included the list of arguments.

System.out.format("There are %d apples, %d oranges and "
        + "%d pears%n", x, y, z);

If we do not specify the index, the variables automatically match the specifiers. The d specifier formats an integer value as a decimal value.

System.out.format("There are %2$d apples, %3$d oranges and "
        + "%1$d pears%n", x, y, z);

The 1$ referes to the x variable, the 2$ referes to the y variable and the 3$ refers to the z variable.

System.out.format("Year: %tY, Month: %<tm, Day: %<td%n", c);

The < flag causes the argument for the previous format specifier to be reused. All three specifiers refer to the c variable. The tY conversion characters give a year formatted as at least four digits with leading zeros as necessary, tm give a month, formatted as two digits with leading zeros as necessary, and td give a day of month, formatted as two digits with leading zeros as necessary.

$ java IndexPosition.java
There are 12 apples, 32 oranges and 43 pears
There are 32 apples, 43 oranges and 12 pears
Year: 2016, Month: 09, Day: 07

The flag modifies the format in a specific way. There are several flags available. For instance, the + flag requires the output to include a positive sign for all positive numbers.

com/zetcode/Flags.java
package com.zetcode;

public class Flags {

    public static void main(String[] args) {

        System.out.format("%+d%n", 553);
        System.out.format("%010d%n", 553);
        System.out.format("%10d%n", 553);
        System.out.format("%-10d%n", 553);
        System.out.format("%d%n", -553);
        System.out.format("%(d%n", -553);
    }
}

The example presents a few flags of the string format specifier.

System.out.format("%010d%n", 553);

The 0 flag will cause the output to be padded with leading zeros to the minimum field width. Our number has three digits. The minimum width is 10. Therefore, we have 7 leading zeros in the output.

System.out.format("%10d%n", 553);

Without the 0 flag, the number is right aligned.

System.out.format("%-10d%n", 553);

The - flag will cause the number to be left aligned.

System.out.format("%d%n", -553);
System.out.format("%(d%n", -553);

By default, negative numbers have a minus sign. If we use the ( flag, the negative values will be put inside round brackets. (This is used in accounting.)

$ java Flags.java
+553
0000000553
       553
553
-553
(553)

The width field is the minimum number of characters to be written to the output. It cannot be used together with the line separator.

com/zetcode/WidthSpecifier.java
package com.zetcode;

public class WidthSpecifier {

    public static void main(String[] args) {

        System.out.println(1);
        System.out.println(16);
        System.out.println(1655);
        System.out.println(16567);
        System.out.println(166701);

        System.out.format("%10d%n", 1);
        System.out.format("%10d%n", 16);
        System.out.format("%10d%n", 1655);
        System.out.format("%10d%n", 16567);
        System.out.format("%10d%n", 166701);
    }
}

First, we print five numbers without specifying the field width. The width of the output is equal to the number of the characters being displayed. In the second case, we have a field width of 10. Each of the 5 outputs has a minimum length of 10 characters. The numbers are right aligned.

System.out.format("%10d%n", 1);

Number 10 states that the string output must have at least ten characters.

$ java WidthSpecifier.java
1
16
1655
16567
166701
         1
        16
      1655
     16567
    166701

We can see that in the second case the numbers are right aligned.

The precision field has different meaning for different conversions. For general argument types, the precision is the maximum number of characters to be written to the output.

com/zetcode/PrecisionSpecifier.java
package com.zetcode;

public class PrecisionSpecifier {

    public static void main(String[] args) {

        System.out.format("%.3g%n", 0.0000006);
        System.out.format("%.3f%n", 54.34263);
        System.out.format("%.3s%n", "ZetCode");
    }
}

The precision specifier is demonstrated on three different outputs.

System.out.format("%.3g%n", 0.0000006);

If the g conversion is used, then the precision is the total number of digits in the resulting magnitude after rounding.

System.out.format("%.3f%n", 54.34263);

For floating point values, the precision is the number of digits after the decimal separator.

System.out.format("%.3s%n", "ZetCode");

For strings, it is the maximum number of printed characters. Only three characters out of seven are printed to the console.

$ java PrecisionSpecifier.java
6.00e-07
54.343
Zet

The next example formats numeric data.

com/zetcode/FormatNumbers.java
package com.zetcode;

public class FormatNumbers {

    public static void main(String[] args) {

        System.out.format("%d%n", 12263);
        System.out.format("%o%n", 12263);
        System.out.format("%x%n", 12263);
        System.out.format("%e%n", 0.03452342263);
        System.out.format("%d%%%n", 45);
    }
}

The example demonstrates the standard formatting specifiers for numbers.

System.out.format("%d%n", 12263);

The d conversion specifier will turn an integer value into a decimal value.

System.out.format("%o%n", 12263);

The o conversion specifier will format the number into the octal base.

System.out.format("%x%n", 12263);

With the x specifier, the result is formatted as a hexadecimal integer.

System.out.format("%e%n", 0.03452342263);

Using the e specifier, the number is printed in a scientific notation.

System.out.format("%d%%%n", 45);

The %% characters are used to print a percent sign.

$ java FormatNumbers.java
12263
27747
2fe7
3.452342e-02
45%

Finally, we format date and time data.

com/zetcode/FormatDateTime.java
package com.zetcode;

import java.time.LocalDateTime;

public class FormatDateTime {

    public static void main(String[] args) {

        LocalDateTime ldt = LocalDateTime.now();

        System.out.format("%tF%n", ldt);
        System.out.format("%tD%n", ldt);
        System.out.format("%tT%n", ldt);

        System.out.format("%1$tA, %1$tb %1$tY%n", ldt);
        System.out.format("%1$td.%1$tm.%1$tY%n", ldt);
    }
}

The example demonstrates the standard formatting specifiers for dates. The conversion part of the date and time format string starts with the t character.

System.out.format("%tF%n", c);

This line prints a date in a complete ISO 8601 format, as a result of the tF conversion.

System.out.format("%1$td.%1$tm.%1$tY%n", c);

Using these format specifiers, we print a date in the form that is used in Slovakia. The parts are separated by the dot character and the day precedes the month and the month precedes the year. All three format specifiers refer to the c variable.

$ java FormatDateTime.java
2021-03-17
03/17/21
21:12:15
Wednesday, Mar 2021
17.03.2021

In this tutorial we have worked with strings in Java.

List all Java tutorials.