Sunday, October 28, 2018

How to format String in Java Example?


import java.util.Formatter;
import java.util.Locale;

public class JavaStringFormatTest {

	public static void main(String[] args) {
		String javaString = "This %s is going to format %s program %d times";
		
		/*As the String object is immutable, the formatter is going to use a StringBuilder
		 * */
		Formatter formatter = new Formatter(new StringBuilder(), Locale.US);
		
		/*This formatter is going to format the javaString to replace strings in place of %s and numbers for %d
		 * */
		formatter.format(javaString, "program", "java", 2);
		
		System.out.println(formatter);
		
		Formatter formatter2 = new Formatter(new StringBuilder(), Locale.US);
		/*This  is going to change the format of the String in a different way
		 * */
		formatter2.format(javaString, "java", "program", 0);
		
		System.out.println(formatter2);		
		
	}

}


Output:
This program is going to format java program 2 times
This java is going to format program program 0 times

/*This is a basic program to format Local time
*/
public class JavaStringFormatLocaleTest {

	public static void main(String[] args) {
		String javaString = "Local time Now : %tT";
		
		/*Here we are using the built-in object 'format' of System class to do the formatting
		 * Calendar.getInstance() will give the local time and String will be formatted using %T for time
		 * */
		System.out.format(javaString, Calendar.getInstance());			
	}
}


Output:(might change based on your local time)
Local time Now : 21:49:34

Importance of formatting in Java:

1. Formatting will be useful while printing the log statements in your Java programs. 
2. This will help unnecessary adding of Strings and will minimize coding standard violations.
3. The code will be much cleaner after formatting and maintenance of the code will be simple.
4. format method formats multiple arguments based on a format string.

 d formats an integer value as a decimal value.
 f formats a floating point value as a decimal value.
 n outputs a platform-specific line terminator.
 x formats an integer as a hexadecimal value.
 s formats any value as a string.
 tB formats an integer as a locale-specific month name.

No comments:

Post a Comment