Making a String That Can Contain Dynamic Information - Java Language Basics

Java examples for Language Basics:String

Solution 1

Use the String format() method for generating a String containing placeholders for dynamic data.

Demo Code

public class Main {
    /*w  w  w .j a  va 2  s  . c  o m*/
    
    public static void main(String[] args){
        double temperature = 8.6;
        String temperatureString = "The current temperature is %.1f degrees Fahrenheit.";

        String newString = String.format(temperatureString, temperature);
        System.out.println(newString);

        temperature = 101.2;
        
        System.out.println(String.format(temperatureString, temperature));
        
    }
}

Result

Solution 2

System.out.printf() method can be used to position dynamic values within a String.

Demo Code

public class Main {
    public static void main(String[] args){
        double temperature = 98.6;
        System.out.printf("The current temperature is %.1f degrees Fahrenheit.\n", temperature);

        temperature = 101.2;/*from ww  w. j  a v a  2s .c  o  m*/
        
        System.out.printf("The current temperature is %.1f degrees Fahrenheit.", temperature);
        
    }
}

Result

String.format() Conversion Types

Conversion Content Type
b boolean
h hex
s String
c Unicode character
d decimal integer
o octal integer
x hexadecimal integer
e floating point decimal number in computerized scientific notation
f floating point decimal number
g floating point using computerized scientific notation or decimal format, depending upon the precision and value after rounding
a hexadecimal floating-point number with significant and exponent
t date/time
n platform-specific line separator

Each placeholder must begin with a % character to denote that it is a placeholder.

The placeholder can contain flags, width, and precision indicators to help format the dynamic value.

The following format should be used to build each placeholder:

%[flags][width][.precision]conversion_indicator

Related Tutorials