Index

Overview


Java's string formatting is a convenient way to generate nice strings consisting of a mix of value types.

Examples


public class StringFormatLab{
	
	public void commonFormatting()
	{
		//NOTE: "%%" -- percent symbol is escaped using % symbol
		//(so literal '%' character shows
	
		String s;
		header("commonFormatting");
	
		s = String.format("Width is %d and height is %d", 10, 5);
		prn(s);
	
		s = String.format("A big number: %d", 1000000000000000L);
		prn(s);
	
		s = String.format("A big number with commas: %,d", 1000000000000000L);
		prn(s);
	
		double pi = Math.PI;
		s = String.format("PI is %.2f or more accurately %.4f", pi, pi);
		prn(s);
	
		s = String.format("It might be %s or it might be %s", true, false);
		prn(s);
	
		s = String.format("Hello %s and %s", "Foo", "Boo");
		prn(s);
	}
	
	public void specialFormatting() {
	
		String s;
		header("specialFormatting");
	
		s = String.format("To show the percent sign we escape it: 20%%");
		prn(s);
	
		s = String.format("A couple tabs:\t\tMe Tabbed");
		prn(s);
	
		s = String.format("Blank lines follow. %n%n%nContinuing here");
		prn(s);
	
		s = String.format("Blank lines follow (alternative 2). \n\n\nContinuing here");
		prn(s);
	}
	

	public void formattingStrings() {
	
		header("formattingStrings");

		out.printf("%20s%20s%20s%20s\n",
				"]", "]", "]", "]");
		out.printf("%20s%20s%20s%20s\n",
					"Right", "Right", "Right", "Right");
		prn("");
		out.printf("%-20s%-20s%-20s%-20s\n",
				"[", "[", "[", "[");
		out.printf("%-20s%-20s%-20s%-20s\n",
					"Left", "Left", "Left", "Left");
	
		//%.8s : will print maximum 8 characters of the string.
		out.printf("\nTruncate a string (to 8 chars): %.8s\n",
						"1234567890123456789");
	}

	public void advancedDynamicFormatting(int decPlaces) {
		//Here we can dynamically build a formatter
	
		header("advancedDynamicFormatting");
	
		String template, formatter, s;
		double pi = Math.PI;
		template = "%.#DEC-PLACES#f";
		formatter = template.replace("#DEC-PLACES#", String.valueOf(decPlaces));
	
		out.printf("Method param decPlaces = %d\n", decPlaces);
		s = String.format(formatter, pi);
		prn(s);
	}
	
	//------------------------------------

	private static void prn(Object o) {
		out.println(o.toString());
	}

	private static void header(String s) {
		prn("");
		prn("=================================================");
		prn("---- " + s + " ----");
		prn("");
	}

	public static void main(String[] args)
	{
		StringFormatLab lab = new StringFormatLab();
		lab.commonFormatting();
		lab.specialFormatting();
		lab.formattingStrings();
		lab.advancedDynamicFormatting(2);
		lab.advancedDynamicFormatting(8);
	}

}



References