Strings

In this part of the Java tutorial, we will work with string data in more detail.

Strings are very important data types in computer languages. That is why we dedicate a whole chapter to working with strings in Java.

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.

Initializing strings

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

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 com.zetcode.StringInit 
Java
NetBeans
MySQL
Java
Fields of glory

Running the example gives this result.

Strings are objects

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.

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 com.zetcode.StringObjects 
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.

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.

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 com.zetcode.MutableImmutable 
Jane
Kate
Jane
Kate

This is the output of the com.zetcode.MutableImmutable example.

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.

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 com.zetcode.ConcatenateStrings 
Return of the king.
Return of the king.
Return of the king.

This is the example output.

Using quotes

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

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 com.zetcode.Quotes 
There are may stars
He said: "Which one are you looking at?"

Here we see the output of the com.zetcode.Quotes program.

Multiline strings

It is not possible to create a multiline string in Java. In order to span a string on multiple lines, we need to do a concatenation operation.

MultilineString.java
package com.zetcode;

public class MultilineString {

    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);
    }
}

One strophe spans four lines. The four strings are concatenated with the + operator.

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

We see the output of the com.zetcode.MultilineString example.

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.

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 com.zetcode.StringElements 
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

This is the example output.

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

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 com.zetcode.StringBuilderElements 
Misty mountains
Misty mountain
Misty mountains
The Misty mountains
The misty mountains

From the output we can see how the mutable string is changing.

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.

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 com.zetcode.Substrings 
book
case

This is the output.

Splitting strings

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

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 com.zetcode.Splitting
Today
is
a
beautiful
day.

This is the output.

Removing 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.

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(",")) {
            word = part.substring(0, part.length()-1);
        }

        if (part.startsWith("\"") &&  part.endsWith("\"")) {
            word = part.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(",")) {
    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("\"") &&  part.endsWith("\"")) {
    word = part.substring(1, part.length()-1);
}

Likewise, we remove the starting characters. The starting character is checked with the startsWith() method.

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

This is the output of the example. The characters were successfully removed.

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.

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.

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.

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 com.zetcode.ComparingStrings 
false
true

This is the output of the com.zetcode.ComparingStrings program.

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.

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.

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 com.zetcode.ComparingStrings3 
true
false
true
true
false

This is the output of the example.

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.

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 com.zetcode.Conversions 
There are 5 pencils.
The rock weighs 5.345000 kilograms.

This is the output of the com.zetcode.Conversions program.

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 com.zetcode.IndexPosition 
There are 12 apples, 32 oranges and 43 pears
There are 32 apples, 43 oranges and 12 pears
Year: 2016, Month: 09, Day: 07

This is the output of the com.zetcode.IndexPosition program.

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.

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 com.zetcode.Flags 
+553
0000000553
       553
553       
-553
(553)

Here we see the output of the com.zetcode.Flags example.

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

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 com.zetcode.WidthSpecifier 
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.

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 com.zetcode.PrecisionSpecifier 
6.00e-07
54.343
Zet

This is the example output.

The next example will format numeric data.

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 com.zetcode.FormatNumbers 
12263
27747
2fe7
3.452342e-02
45%

The program prints numbers in different formats.

Finally, we will format date and time data.

FormatDateTime.java
package com.zetcode;

import java.util.Calendar;

public class FormatDateTime {

    public static void main(String[] args) {
               
        Calendar c = Calendar.getInstance();
        
        System.out.format("%tF%n", c);
        System.out.format("%tD%n", c);
        System.out.format("%tT%n", c);
        
        System.out.format("%1$tA,%1$tb %1$tY%n", c);
        System.out.format("%1$td.%1$tm.%1$tY%n", c);
        
        System.out.format("%ts%n", c);            
    }
}

The preceding 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.

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

The s conversion character creates a Unix time. It is a number of seconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC.

$ java com.zetcode.FormatDateTime 
2013-07-17
07/17/13
18:29:48
Wednesday,Jul 2013
17.07.2013
1374078588

This is the output of the com.zetcode.FormatDateTime program.

This part of the Java tutorial covered strings in more detail.