bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Java/Java Reference
Java•Java Reference

Java String format() Method

❮ String Methods

Example

String myStr = "Hello %s! One kilobyte is %,d bytes.";
String result = String.format(myStr, "World", 1024);
System.out.println(result);

Definition and Usage

The format() method returns a formatted string using a locale, format and additional arguments.

If a locale is not passed to this method then the locale given by Locale.getDefault() is used.

Data from the additional arguments is formatted and written into placeholders in the format string, which are marked by a % symbol. The way in which arguments are formatted depends on the sequence of characters that follows the % symbol.

Placeholders

The placeholders have the form %[arg$][flags][width][.precision]conversion . The components in [square brackets] are optional.

An explanation of each of the components:

  • arg- Optional. A number followed by a sign which indicates which of the additional arguments to use, argument numbers start at 1. This can be replaced with a < which specifies that the argument from the previous placeholder should be used.
  • flags - Optional. A sequence of any of the following characters: - - Makes the output left-justified by adding any padding spaces to the right instead of to the left. # - Shows an alternate representation of the formatted data depending on the conversion. + - Causes positive numbers to always be prefixed with "+". - (A space character) This prefixes a space to positive numbers, primarily so that the digits can be lined up with the digits of negative numbers. 0 - Pads numbers with zeroes on the left. , - Groups digits (for example by thousands) and puts separators between the groups. This is affected by the locale. ( - Encloses negative numbers in parentheses.
  • width - Optional. A whole number specifying the minimum number of characters that the output should occupy. If necessary spaces are added to the left to reach this number, or to the right if the - flag is used.
  • .precision Optional. A . followed by a whole number indicating how many decimal digits to show in the formatted data.
  • conversion - Required. A character which indicates how an argument's data should be represented. If the character is uppercase the data will be formatted in uppercase where possible. The list of possible characters is shown in the table below.
  • - - Makes the output left-justified by adding any padding spaces to the right instead of to the left.
  • # - Shows an alternate representation of the formatted data depending on the conversion.
  • + - Causes positive numbers to always be prefixed with "+".
  • - (A space character) This prefixes a space to positive numbers, primarily so that the digits can be lined up with the digits of negative numbers.
  • 0 - Pads numbers with zeroes on the left.
  • , - Groups digits (for example by thousands) and puts separators between the groups. This is affected by the locale.
  • ( - Encloses negative numbers in parentheses.

List of conversions

CharacterConversionDescription
%PercentDisplays a literal "%" character in the output.
nLine breakDisplays a line break in the output.
b or BBooleanDisplays the boolean value of an argument as "true" or "false". If "B" is used then it displays "TRUE" or "FALSE" instead.
h or HHash code in hexadecimalDisplays the hash code of the argument in hexadecimal by using its hashCode() value. If H is used, the letters A to F are shown in uppercase. Note: This does not format a number as a hexadecimal integer. For hexadecimal integer formatting, use x or X .
s or SStringDisplays the default string representation of the argument. If "S" is used then the string will be converted to uppercase where possible.
c or CUnicode characterDisplays a unicode character representation of the argument. For whole numbers, this is the unicode character that corresponds to the number. If "C" is used then the character will be converted to uppercase where possible.
dDecimal integerRepresents a whole number as a decimal integer.
oOctal integerRepresents a whole number as an octal integer. The "#" flag will prefix the number with "0".
x or XHexadecimal integerRepresents a whole number as a hexadecimal integer. The "#" flag will prefix the number with "0x". If "X" is used then digits A to F and the letter X are shown in uppercase.
e or EScientific notationRepresents a floating point number in scientific notation. If "E" is used then the letter "E" of the representation will be uppercase. The "#" flag will force a decimal point even if there are no decimal digits.
fFloating point numberRepresents a floating point number. The "#" flag will force a decimal point even if there are no decimal digits.
g or GGeneral numberDisplays the shortest representation between f and e or E for a floating point number.
a or AHexadecimal floating point numberDisplay a floating point number's internal representation with hexadecimal digits.
t or TTime or dateDisplays a formatted date or time. The t or T must be followed by one more character indicating how the date or time should be formatted. If "T" is used then text parts of a date or time such as "JANUARY" will be uppercase. The following characters can be used for date and time formatting: H - 24-hour format of an hour (00 to 23) I - 12-hour format of an hour (01 to 12) k - 24-hour format of an hour (0 to 23) l (lowercase 'L') - 12-hour format of an hour (1 to 12) M - Minutes with leading zeros (00 to 59) S - Seconds with leading zeros (00 to 59) (The value 60 may occur for leap seconds) L - Milliseconds with leading zeroes (000 to 999) N - Nanoseconds with leading zeroes (000000000 to 999999999) p - "am", "pm", "AM" or "PM" to indicate morning or afternoon z - Difference to Greenwich time (Example: -0800) Z - Timezone abbreviations (Examples: EST, MDT) s - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) Q - The milliseconds since the Unix Epoch (January 1 1970 00:00:00 GMT) B - A full textual representation of a month (January through December) b or h - A short textual representation of a month (three letters) A - A full textual representation of a day (Example: Monday) a - A short textual representation of a day (Example: Mon) C - The first two digits of the year (For 1970, "19" would be shown) Y - A four digit representation of a year y - A two digit representation of a year j - The day of the year with leading zeroes (001 to 366) m - A numeric representation of a month (01 to 12) d - The day of the month (01 to 31) e - The day of the month without leading zeros (1 to 31) R - The time in 24-hour format (Example: 21:30) T - The time in 24-hour format with seconds (Example: 21:30:02) r - The time in 12-hour format with seconds (Example: 09:30:02 PM) ("AM" and "PM" are always uppercase) D - Date representation as month/day/year (Example: 12/17/23) F - Date representation as year-month-day (Example: 2023-12-17) c - Full date and time (Example: Thu Mar 28 10:51:00 EDT 2024)
  • H - 24-hour format of an hour (00 to 23)
  • I - 12-hour format of an hour (01 to 12)
  • k - 24-hour format of an hour (0 to 23)
  • l (lowercase 'L') - 12-hour format of an hour (1 to 12)
  • M - Minutes with leading zeros (00 to 59)
  • S - Seconds with leading zeros (00 to 59) (The value 60 may occur for leap seconds)
  • L - Milliseconds with leading zeroes (000 to 999)
  • N - Nanoseconds with leading zeroes (000000000 to 999999999)
  • p - "am", "pm", "AM" or "PM" to indicate morning or afternoon
  • z - Difference to Greenwich time (Example: -0800)
  • Z - Timezone abbreviations (Examples: EST, MDT)
  • s - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
  • Q - The milliseconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
  • B - A full textual representation of a month (January through December)
  • b or h - A short textual representation of a month (three letters)
  • A - A full textual representation of a day (Example: Monday)
  • a - A short textual representation of a day (Example: Mon)
  • C - The first two digits of the year (For 1970, "19" would be shown)
  • Y - A four digit representation of a year
  • y - A two digit representation of a year
  • j - The day of the year with leading zeroes (001 to 366)
  • m - A numeric representation of a month (01 to 12)
  • d - The day of the month (01 to 31)
  • e - The day of the month without leading zeros (1 to 31)
  • R - The time in 24-hour format (Example: 21:30)
  • T - The time in 24-hour format with seconds (Example: 21:30:02)
  • r - The time in 12-hour format with seconds (Example: 09:30:02 PM) ("AM" and "PM" are always uppercase)
  • D - Date representation as month/day/year (Example: 12/17/23)
  • F - Date representation as year-month-day (Example: 2023-12-17)
  • c - Full date and time (Example: Thu Mar 28 10:51:00 EDT 2024)

One of the following

public static String format(Locale
locale , String
format , Object...
args )
public static String format(String
format , Object...
args )

Parameter Values

ParameterDescription
localeOptional. A locale used to determine some of the formatting, such as which characters are used for decimal points and grouping separators.
formatRequired. A string to be returned which can have placeholders for the additional arguments indicating how to format them.
argsOptional. Any number of additional arguments to the method, their values can be formatted and displayed in the returned string.

Technical Details

Returns:A String value formatted using the specified locale, format and arguments.
Throws:IllegalFormatException - if the format string contains an invalid placeholder or a placeholder isn't compatible with the data type of the argument.
Java version:1.5

Previous

Java String equalsIgnoreCase() Method

Next

Java String getBytes() Method

This chapter

Overview
264

Lessons

546m

Read time

1. Java Keywords2. Java assert Keyword3. Java abstract Keyword4. Java boolean Keyword5. Java break Keyword6. Java byte Keyword7. Java case Keyword8. Java catch Keyword9. Java char Keyword10. Java class Keyword11. Java continue Keyword12. Java default Keyword13. Java do Keyword14. Java double Keyword15. Java else Keyword16. Java enum Keyword17. Java exports Keyword18. Java extends Keyword19. Java final Keyword20. Java finally Keyword21. Java float Keyword22. Java for Keyword23. Java if Keyword24. Java implements Keyword25. Java import Keyword26. Java instanceof Keyword27. Java int Keyword28. Java interface Keyword29. Java long Keyword30. Java module Keyword31. Java native Keyword32. Java new Keyword33. Java package Keyword34. Java private Keyword35. Java protected Keyword36. Java public Keyword37. Java return Keyword38. Java requires Keyword39. Java short Keyword40. Java static Keyword41. Java super Keyword42. Java switch Keyword43. Java synchronized Keyword44. Java this Keyword45. Java throw Keyword46. Java throws Keyword47. Java transient Keyword48. Java try Keyword49. Java var Keyword50. Java void Keyword51. Java volatile Keyword52. Java while Keyword53. Java String Methods54. Java String charAt() Method55. Java String codePointAt() Method56. Java String codePointBefore() Method57. Java String codePointCount() Method58. Java String compareTo() Method59. Java String compareToIgnoreCase() Method60. Java String concat() Method61. Java String contains() Method62. Java String contentEquals() Method63. Java String copyValueOf() Method64. Java String endsWith() Method65. Java String equals() Method66. Java String equalsIgnoreCase() Method67. Java String format() Method68. Java String getBytes() Method69. Java String getChars() Method70. Java String hashCode() Method71. Java String indexOf() Method72. Java String isEmpty() Method73. Java String join() Method74. Java String lastIndexOf() Method75. Java String length() Method76. Java String matches() Method77. Java String offsetByCodePoints() Method78. Java String regionMatches() Method79. Java String replace() Method80. Java String replaceAll() Method81. Java String replaceFirst() Method82. Java String split() Method83. Java String startsWith() Method84. Java String subSequence() Method85. Java String substring() Method86. Java String toCharArray() Method87. Java String toLowerCase() Method88. Java String toString() Method89. Java String toUpperCase() Method90. Java String trim() Method91. Java String valueOf() Method92. Java Math Methods93. Java Math abs() Method94. Java Math acos() Method95. Java Math addExact() Method96. Java Math asin() Method97. Java Math atan() Method98. Java Math atan2() Method99. Java Math cbrt() Method100. Java Math ceil() Method101. Java Math copySign() Method102. Java Math cos() Method103. Java Math cosh() Method104. Java Math decrementExact() Method105. Java Math exp() Method106. Java Math expm1() Method107. Java Math floor() Method108. Java Math floorDiv() Method109. Java Math floorMod() Method110. Java Math getExponent() Method111. Java Math hypot() Method112. Java Math IEEEremainder() Method113. Java Math incrementExact() Method114. Java Math log() Method115. Java Math log10() Method116. Java Math log1p() Method117. Java Math max() Method118. Java Math min() Method119. Java Math multiplyExact() Method120. Java Math negateExact() Method121. Java Math nextAfter() Method122. Java Math nextDown() Method123. Java Math nextUp() Method124. Java Math pow() Method125. Java Math random() Method126. Java Math rint() Method127. Java Math round() Method128. Java Math scalb() Method129. Java Math signum() Method130. Java Math sin() Method131. Java Math sinh() Method132. Java Math sqrt() Method133. Java Math subtractExact() Method134. Java Math tan() Method135. Java Math tanh() Method136. Java Math toDegrees() Method137. Java Math toIntExact() Method138. Java Math toRadians() Method139. Java Math ulp() Method140. Java Output Methods141. Java Output print() Method142. Java Output printf() Method143. Java Output println() Method144. Java Arrays Class145. Java Arrays. compare() Method146. Java Arrays. equals() Method147. Java Arrays. sort() Method148. Java Arrays. fill() Method149. Java Array length Property150. Java ArrayList Methods151. Java ArrayList add() Method152. Java ArrayList add() Method153. Java ArrayList clear() Method154. Java ArrayList clone() Method155. Java ArrayList contains() Method156. Java ArrayList ensureCapacity() Method157. Java ArrayList forEach() Method158. Java ArrayList get() Method159. Java ArrayList indexOf() Method160. Java ArrayList isEmpty() Method161. Java ArrayList iterator() Method162. Java ArrayList lastIndexOf() Method163. Java ArrayList listIterator() Method164. Java ArrayList remove() Method165. Java ArrayList removeAll() Method166. Java ArrayList removeIf() Method167. Java ArrayList replaceAll() Method168. Java ArrayList retainAll() Method169. Java ArrayList set() Method170. Java ArrayList size() Method171. Java ArrayList sort() Method172. Java ArrayList spliterator() Method173. Java ArrayList subList() Method174. Java ArrayList toArray() Method175. Java ArrayList trimToSize() Method176. Java LinkedList Methods177. Java LinkedList add() Method178. Java LinkedList add() Method179. Java LinkedList clear() Method180. Java LinkedList clone() Method181. Java LinkedList contains() Method182. Java LinkedList forEach() Method183. Java LinkedList get() Method184. Java LinkedList getFirst() Method185. Java LinkedList getLast() Method186. Java LinkedList indexOf() Method187. Java LinkedList isEmpty() Method188. Java LinkedList iterator() Method189. Java LinkedList lastIndexOf() Method190. Java LinkedList listIterator() Method191. Java LinkedList remove() Method192. Java LinkedList removeAll() Method193. Java LinkedList removeFirst() Method194. Java LinkedList removeIf() Method195. Java LinkedList removeLast() Method196. Java LinkedList replaceAll() Method197. Java LinkedList retainAll() Method198. Java LinkedList set() Method199. Java LinkedList size() Method200. Java LinkedList sort() Method201. Java LinkedList spliterator() Method202. Java LinkedList subList() Method203. Java LinkedList toArray() Method204. Java HashMap Methods205. Java HashMap clear() Method206. Java HashMap clone() Method207. Java HashMap compute() Method208. Java HashMap computeIfAbsent() Method209. Java HashMap computeIfPresent() Method210. Java HashMap containsKey() Method211. Java HashMap containsValue() Method212. Java HashMap entrySet() Method213. Java HashMap forEach() Method214. Java HashMap get() Method215. Java HashMap getOrDefault() Method216. Java HashMap isEmpty() Method217. Java HashMap keySet() Method218. Java HashMap merge() Method219. Java HashMap put() Method220. Java HashMap putAll() Method221. Java HashMap putIfAbsent() Method222. Java HashMap remove() Method223. Java HashMap replace() Method224. Java HashMap replaceAll() Method225. Java HashMap size() Method226. Java HashMap values() Method227. Java Scanner Methods228. Java Scanner close() Method229. Java Scanner delimiter() Method230. Java Scanner findInLine() Method231. Java Scanner findWithinHorizon() Method232. Java Scanner hasNext() Method233. Java Scanner hasNextBoolean() Method234. Java Scanner hasNextByte() Method235. Java Scanner hasNextDouble() Method236. Java Scanner hasNextFloat() Method237. Java Scanner hasNextInt() Method238. Java Scanner hasNextLine() Method239. Java Scanner hasNextLong() Method240. Java Scanner hasNextShort() Method241. Java Scanner locale() Method242. Java Scanner next() Method243. Java Scanner nextBoolean() Method244. Java Scanner nextByte() Method245. Java Scanner nextDouble() Method246. Java Scanner nextFloat() Method247. Java Scanner nextInt() Method248. Java Scanner nextLine() Method249. Java Scanner nextLong() Method250. Java Scanner nextShort() Method251. Java Scanner radix() Method252. Java Scanner reset() Method253. Java Scanner useDelimiter() Method254. Java Scanner useLocale() Method255. Java Scanner useRadix() Method256. Java File Class Methods257. Java FileInputStream Methods258. Java FileOutputStream Methods259. Java BufferedReader Methods260. Java BufferedWriter Methods261. Java Iterator Interface262. Java Collections Class Methods263. Java System Methods264. Java Errors and Exception Types

On this page

Definition and UsagePlaceholdersList of conversionsParameter ValuesTechnical Details