String Formatting in Java using %

JavaObject Oriented ProgrammingProgramming

Followimg is the code to implement String formatting in Java using % −

Example

 Live Demo

public class Demo {
   public static void main(String args[]){
      String my_str = " sample.";
      String concat_Str = String.format("This is a" + "%s", my_str);
      String format_str_1 = String.format("The value is %.4f", 78.92367);
      System.out.println(concat_Str);
      System.out.println(format_str_1);
   }
}

Output

This is a sample.
The value is 78.9237

A class named Demo contains the main function. Here a string value is defined, which is used to format the string, by concatenating it to another variable. Similarly, a floating point number is also formatted using the ‘%’ operator. Both these values are printed on the console.

raja
Published on 04-Jul-2020 09:55:58
Advertisements