Java String format()

The java string format() method returns the formatted string by given locale, format and arguments.

If you don't specify the locale in String.format() method, it uses default locale by calling Locale.getDefault() method.

The format() method of java language is like sprintf() function in c language and printf() method of java language.

Internal implementation

public static String format(String format, Object... args) {  
       return new Formatter().format(format, args).toString();  
   }  

Java String format() method example

public class FormatExample{  
public static void main(String args[]){  
String name="sonoo";  
String sf1=String.format("name is %s",name);  
String sf2=String.format("value is %f",32.33434);  
String sf3=String.format("value is %32.12f",32.33434);//returns 12 char fractional part filling with 0  
  
System.out.println(sf1);  
System.out.println(sf2);  
System.out.println(sf3);  
}}  

run:

name is sonoo
value is 32.334340
value is 32.334340000000

link:https://www.javatpoint.com/java-string-format

posted @ 2023-12-12 20:59  鲸小鱼-  阅读(28)  评论(0编辑  收藏  举报