Monday, 16 June 2014

format (String format, Object... args)

public static String format(String format, Object... args)
Returns a formatted string using the specified format string and arguments.

import java.util.Locale;

class StringFormat1{
 public static void main(String args[]){
  int i = 10;
  float f = 10.01f;
  String s2;
  
  s2 = String.format("value of i is %d f is %f", i, f);
  System.out.println(s2);
 }
}

Output
value of i is 10 f is 10.010000

1. Throws IllegalFormatException If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions.
import java.util.Locale;

class StringFormat1Illegal{
 public static void main(String args[]){
  int i = 10;
  float f = 10.01f;
  String s2;
  
  s2 = String.format("value of i is %d f is %d", i, f);
  System.out.println(s2);
 }
}

Output
Exception in thread "main" java.util.IllegalFormatConversionException: d != java
.lang.Float
        at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
        at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
        at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
        at java.util.Formatter.format(Formatter.java:2520)
        at java.util.Formatter.format(Formatter.java:2455)
        at java.lang.String.format(String.java:2925)
        at StringFormat1Illegal.main(StringFormat1Illegal.java:9)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment