OneBite.Dev - Coding blog in a bite size

format a string in java

Code snippet on how to format a string in java

String str = "Hello, World!";

// create a String object by passing a literal value

String formattedStr = String.format("\n %s \n %s \n", str, str);

// use String.format() method to format the String. 
// The %s is a placeholder for the variables to be used for formatting.
// \n directs the output to a new line

This code will format the string “Hello, World!” by outputting it twice on two separate lines. First, we create a String object using the literal value “Hello, World!” and store it in a variable called “str”. We then call the String.format() method, which will generate a new string with the text from the “str” variable inserted in place of the %s placeholder. We also add “\n” to the end of our string, which tells the interpreter to move to a new line for the output. Finally, the formatted string is stored in the variable “formattedStr” for us to use.

java