0

In C# there is the $ operator for strings:

$"Some Text here with {aVariable}";

Is there a similar way of doing that in Java?

The current way I do this is:

"Some Text here with " + aVariable;
Orace
  • 7,822
  • 30
  • 45
  • There is no operator in java, but classes that do what you want: https://docs.oracle.com/javase/8/docs/api/java/text/MessageFormat.html – OH GOD SPIDERS Jul 12 '22 at 15:20
  • 1
    JFYI _"So in C# there is the $ operator for strings (Ex. $"Some Text here with {Variable here}";"_ - is called string interpolation. – Guru Stron Jul 12 '22 at 15:24
  • Strictly speaking, it's not actually an operator. If it were an operator, you could use it on a string variable to achieve the same result with the contents of the variable. You can't. It's just a different kind of string expression wher the `$` is part of the delimiters. – madreflection Jul 12 '22 at 15:28
  • Not yet but there is a [JEP](https://openjdk.org/jeps/0) for something similar: [String Templates](https://openjdk.org/jeps/8273943). – David Conrad Jul 12 '22 at 15:33
  • 1
    alternatives (workaround?): `"Some Text here with %s".formatted(aVariable)`, `String.format("Some Text here with %s", aVariable)` or (kind of older) `MessageFormat.format("Some Text here with {0}", aVariable)` – user16320675 Jul 12 '22 at 16:53
  • Yea I knew about the String.format, and whatnots, it's similar to how you can do it in C++. I was just hoping that maybe someone knew of the same kind of way as it could be handled in C#. @GuruStron Thanks, I had no idea that it was called that. I just know practical uses for it xD – SocialHermit Jul 25 '22 at 02:46

0 Answers0