Search code examples
javaformatreturnstring-interpolation

What does String.format() do inside the return statement of my code?


Please could anyone explain what's going on with the return method(String.format)?

Also, I would like to know how does the code inside the last return statement works?

import java.util.Map;
import java.util.HashMap;

public class RockPaperScissors {

     public static void main(String []args) {
        String result = RockPaperScissors("paper","rock");
        System.out.println(result);
     }
     
     public static String RockPaperScissors(String player1, String player2) {
        Map<String, String> rules = new HashMap<>();
        rules.put("rock", "scissors");
        rules.put("paper", "rock");
        rules.put("scissors", "paper");
        if (player1.equals(player2)) {
           return "TIE";
        }
        return String.format("Player %d wins", rules.get(player1).equals(player2) ? 1 : 2);
    }
}

The part that I do not understand is this:

String.format("Player %d wins", rules.get(player1).equals(player2) ? 1 : 2);

What does it do and what is the meaning of %d inside of it?


Solution

  • If you are talking about the last return statement:

    This is called String interpolation and you can read more about that here: Java - Including variables within strings?

    But basically it means that you will write a whole sentence and you will put a tag inside the string such as %s or other to indicate the type of variable that will be there after formatting with String.format().

    It allows you to avoid using + sign to separate strings and variables.

    String aStringVar = "MyString";
    int anIntVar = 5;
    // Line below is the same as: "A string:" + aStringVar + "; and a number " + anIntVar + ";"
    String interpolatedString = String.format("A String: %s; and a number %2d;", aStringVar, anIntVar);
    System.out.println(interpolatedString);
    // Console result: A String: MyString; and a number 5;