Java Features String / Number / currency

Is there an easier way to understand how the various formatting methods in java are related? I am confused about the following:

System.out.printf() System.out.format() String.format() System.console.format() new Formatter(new StringBuffer("Test")).format(); DecimalFormat.format(value); NumberFormat.format(value); 

Are the classes / methods listed above related? What is the best way to understand the differences and use in which situation?

As an example, System.out.printf , System.out.format and String.format use the same syntax and format flags. I can’t understand what the difference is in all three of them.

thanks

+4
source share
1 answer

I would consider downloading javadocs and source jars for your respective version of Java, because all your questions can be easily answered by looking at the source code and documents.

 System.out.printf(formatString, args) 

System.out is a PrintStream . PrintStream.printf(formatString, args) is actually a convenience method call PrintStream.format(formatString, args); .

 System.out.format(formatString, args) 

This is a call to PrintStream.format(formatString, args) , which uses Formatter to format the results and add them to PrintStream .

 String.format(formatString, args) 

This method also uses Formatter and returns a new string with formatted format string and args results.

 System.console().format(formatString, args) 

System.console() is a Console . Console.format(format, args) uses Formatter to display a formatted string in the console.

 new Formatter(new StringBuffer("Test")).format(formatString, args); 

This creates an instance of Formatter using the passed string buffer. If you use this call, you will have to use out() to get the Appendable recorded using Formatter . Instead, you can do something like:

 StringBuffer sb = new StringBuffer("Test"); new Formatter(sb).format(formatString, args); // now do something with sb.toString() 

Finally:

 DecimalFormat.format(value); NumberFormat.format(value); 

These are two instantiable formats for numbers that do not use the Formatter class. DecimalFormat and NumerFormat both have a format that accepts a double or Number and returns them as a string according to the definition of these classes. As far as I can tell, Formatter does not use them.

Hope this helps.

+4
source

Source: https://habr.com/ru/post/1388739/


All Articles