java formating code example

Example 1: java string format

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);  
}}

Example 2: java printf format string and int

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("================================");
            for(int i=0;i<3;i++){
                String s1=sc.next();
                int x=sc.nextInt();
                //Complete this line                
                System.out.printf("%-15s%03d%n",s1,x);
            }
            System.out.println("================================");

    }
}

Tags:

Java Example