Search code examples
javapython

How to make print of Python in Java?


I've been doing recent programs with Java, Python, and C lately while still learning Ruby and Swift, and I have been interested in making print functions in diffrent languages, like Python's print, Java's System.out.println, C's printf and C++'s cout.

I wanna do some "Hello, (user)" program of Python like this:

user = input("What is your name? ")
print(f"Hello, {user}.")

And make a program in Java with the same print function.

public static void main {
    Scanner user;
    print("What is your name? ");
    user = new Scanner(System.in);
    // print("Hello, ", user, ".");
    print(f"Hello, {user}.")
}

I want to use the f format to add in variables in the print function instead of concatenation (the comment in the Java program). I don't know how to do it just yet except the previous form, so I still didn't have tries. Is the f format possible here? Can it only be recreated in a different language? Or do I have to not make the function at all?


Solution

  • Given the Python code

    user = input("What is your name? ")
    print(f"Hello, {user}.")
    

    the Java equivalent would be

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("What is your name? ");
            String user = scanner.nextLine();
            System.out.printf("Hello, %s.%n", user);
        }
    }
    

    To print a formatted string you would use the printf method where you can use a format string as described in the Format string syntax section of the Formatter class.

    The so called formatted string literals (f-strings) were only introduced with Python 3.6 (PEP 498), and there's no Java equivalent for them (as of the latest Java 14 release).

    (Java also has a MessageFormat which uses a different formatting convention, see also What's the difference between MessageFormat.format and String.format)