0

So I am learning a bit of Java and I'm just curios if there is an equivalent to the string format with the $ sign like in C#. For example

string s = $"Date: {DateTime.Now}";
// s = Date: 5/27/2020 8:02:25 AM

Is this possible in Java? I find it more convenient than doing it with indexes.

Snackerino
  • 119
  • 8

1 Answers1

0

Java provides a type-safe way of concatenating Strings.

Here is a demonstration using jshell:

> jshell

jshell> import java.time.*;

jshell> String s = ("Date: " + LocalDateTime.now());
s ==> "Date: 2020-05-27T09:49:10.476140"

jshell>

Here is a working example program that uses Date formatting:

// File name: Demo.java

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo {
   public static void main(String[] args) {
      Format f = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
      String s = ( "Date: " + f.format(new Date()) );
      System.out.println(s);
   }
}

Output:

> javac Demo.java

> java Demo
Date: 27/03/2020 10:03:02 am
Gopinath
  • 3,671
  • 1
  • 12
  • 15
  • 1
    Thanks, I do know how to concat strings but i wanted to see if Java supports the same way of "String interpolation". – Snackerino May 28 '20 at 12:21