- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
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
StringBuilder
The String
is an immutable sequence of characters. The 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.
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 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.
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.
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 a 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.
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
What if we wanted to display quotes, for example in a direct speech? In such a case, the inner quotes must be escaped.
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.
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 will show some methods that work with characters of a string.
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 above 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.
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.
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.
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 will 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 is on the left side of the comparing method. Otherwise we might get the NullPointerException
.
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 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.
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.
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.
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.
$ java com.zetcode.IndexPosition There are 12 apples, 32 oranges and 43 pears There are 32 apples, 43 oranges and 12 pears Year: 2013, Month: 07, Day: 17
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.
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.
$ 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.
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.
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 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.
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论