How to use String.format () in Java?

I am new to Java and I use thenewboston (youtube) java tutorials. In tutorial 36-37, he starts using String.format (); which he did not explain in past textbooks. Here is the code for the class that he was making:

    public class tuna {
        private int hour;
        private int minute;
        private int second;

        public void setTime(int h, int m, int s){
            hour = ((h >= 0 && h < 24) ? h : 0);
            minute = ((m >= 0 && m < 60) ? m : 0);
            second = ((s >= 0 && s < 60) ? s : 0);
        }

        public String toMilitary(){
            return String.format("%02d:%02d:%02d", hour, minute, second);
        }
    }

So what he does, he does some military time class and uses String formatting. So I ask if anyone can explain to me how String.format () works and how the formatting above works. Thanks for the help!

+21
source share
2 answers

It works the same as printf () from C.

%s for String 
%d for int 
%f for float

ahead

String.format("%02d", 8)

OUTPUT: 08

String.format("%02d", 10)

OUTPUT: 10

String.format("%04d", 10)

OUTPUT: 0010

0 , , , 0 , String API.

+34

hour, minute second 05:23:42. , :

String s = String.format("Hello %s answered your question", "placeofm");

, ,

System.out.println(s);

placeofm

%02d . %s , , . Java, . String. . Java.

+11

Source: https://habr.com/ru/post/1531865/


All Articles