- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to format strings in Java
Problem Description
How to format strings?
Solution
Following example returns a formatted string value by using a specific locale, format and arguments in format() method
import java.util.*; public class StringFormat{ public static void main(String[] args){ double e = Math.E; System.out.format("%f%n", e); System.out.format(Locale.GERMANY, "%-10.4f%n%n", e); } }
Result
The above code sample will produce the following result.
2.718282 2,7183
The following is an another sample example of format strings
public class HelloWorld { public static void main(String []args) { String name = "Hello World"; String s1 = String.format("name %s", name); String s2 = String.format("value %f",32.33434); String s3 = String.format("value %32.12f",32.33434); System.out.print(s1); System.out.print("\n"); System.out.print(s2); System.out.print("\n"); System.out.print(s3); System.out.print("\n"); } }
Result
The above code sample will produce the following result.
name Hello World value 32.334340 value 32.334340000000
java_strings.htm
Advertisements
To Continue Learning Please Login
Login with Google