User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







java:io:printstream:format

This is an old revision of the document!


format

format args to the format string format and write the result to the stream

format(String format, Object... args);
 
return value: stream

Language Example

package codereferececomjava;
 
public class CodeRefereceComJava {
 
 
    public static void main(String[] args) {
 
    String strout = null;
    String str = "is the answer";
    int i = 42;
    String[] arguments = { "way", "example" };
 
    strout = String.format("%d %s", i, str);
    System.out.println(strout);
 
    strout = String.format( "this is another %s for this %s.\n", arguments ); 
    System.out.println(strout);
 
    double  ans = 42.1234568;
 
    System.out.format("The answer is probably %.0f", ans);
    System.out.format("\t and not %.2f \n", ans);
    System.out.format("also not %1.2f \n", ans); // prints 1
 
 
    String string = "hey";
    System.out.format("%-10s reserve 10 signs on the left side\n", string );
    System.out.format("%20s reserve 10 signs on the right side\n", string );
 
    System.out.format("%10d reserve 10 signs after the number \n", i );
    System.out.format("%+d print math signs \n", i ); // prints the vorzeichen
    System.out.format("%010d reserve 10 places and fill it with 0\n", i );
 
    System.out.format("%,2.3f special character \n", ans );
 
 
 }
}

output

  The answer is probably 42	 and not 42,12 
  also not 42,12 
  hey        reserve 10 signs on the left side
                   hey reserve 10 signs on the right side
          42 reserve 10 signs after the number 
  +42 print math signs 
  0000000042 reserve 10 places and fill it with 0
  42,123 special character 

2nd format example in java

package codereferececomjava;
 
public class CodeRefereceComJava {
 
 
    public static void main(String[] args) {
 
        int dnumber = - 5;
        double fnumber = 12317.27;
        String str = "Number";
        char ch = 'A';
        System.out.format("%-30s : %-+10d : %c : %,15.1f\n", str, dnumber, ch, fnumber);
 }
}

output of 2nd format example

   Number                         : -5         : A :        12.317,3

on the occasion of the current invasion of Russia in Ukraine

Russian Stop this War
java/io/printstream/format.1366006396.txt · Last modified: 2024/02/16 01:11 (external edit)

Impressum Datenschutz