0

Other languages like Python, JavaScript, and C# have simple string formatting. Does Java have it's own version of this? I did a Google search and couldn't find anything, but I'm hoping it's not the case.

For those who don't understand the question, here's an example of the other languages.

Python:

f'Hello {name}!

JavaScript:

`Hello ${name}!`

C#:

$"Hello {name}!"
Spedwards
  • 4,167
  • 16
  • 49
  • 106
  • 2
    I think you should update your question and mention, to clarify, that `name` is a _variable_. And the term that you're looking for is _interpolation_. You should mention that in your question as well. – Christian Hujer Nov 12 '17 at 09:21

3 Answers3

2

What you are looking for is interpolation (the detection and replacement with its value) of variables or expressions inside String literals. Java has no such feature. In Java, you will have to revert to:

  • String concatenation, for example StringBuilder.append()
  • String formatting, for example PrintStream.printf(), PrintWriter.printf(), String.format()
Christian Hujer
  • 17,035
  • 5
  • 40
  • 47
0

Use String.format

The syntax is a bit different from other language since it is position based instead of var based. If you need var based interpolator, the closest thing is StringBuilder.

Also see String variable interpolation Java

Hendrik Poernama
  • 413
  • 3
  • 14
0

You can just use

 String s = "Something";
 System.out.printf("My name is: %s", s);

for console output. Or you can use String.format