Languages like Scala, Ruby or even PHP allow to build dynamic textual content in an elegant and concise way. Is string interpolation available in Java?
To set an example of what I mean by “elegant and concise way”, let’s print a result of a simple equation x * y = z, where x, y and z are placeholders for input values and the calculated result respectively.
Ruby – main.rb
[ruby]
#!/usr/bin/ruby
x = 5; y = 4
puts “#{x} * #{y} = #{x * y}”
[/ruby]
[bash]
$ruby main.rb
5 * 4 = 20
[/bash]
Scala (as of 2.10) – Main.scala
[scala]
object Main {
def main(args: Array[String]) {
val (x, y) = (5, 4)
println(s”$x * $y = ${x * y}”)
}
}
[/scala]
[bash]
$scalac Main.scala
$scala Main
5 * 4 = 20
[/bash]
PHP – main.php
[php]
<?php
$x = 5; $y = 4; $z = $x * $y;
echo “$x * $y = $z”;
?>
[/php]
[bash]
$php main.php
5 * 4 = 20
[/bash]
The closest equivalent in Java is the use of String.format
Java – Main.java
[java]
public class Main {
public static void main(String []args){
int x = 5, y = 4;
System.out.println(String.format(“%d * %d = %d”, x, y, x * y));
}
}
[/java]
[bash]
$javac Main.java
$java Main
5 * 4 = 20
[/bash]
The code snippets were created and executed via codingground