1

So I understand how to print quotes around something like "Hello" using system.out.println for example:

System.out.print("\"Hello\"");

to get "Hello"

But for the life of me I cannot figure out how to print quotes around a variable. I've tried for example:

String test = "Hello";

System.out.print("\test\, ");

If anyone has tips, I would greatly appreciate it! Thanks!

3 Answers3

4

Like this:

System.out.print("\"" + test + "\"");

You're not printing the variable inside a string, but by itself, so it's outside of the format quotes. And you print quotes escaped, just like you did in your first string; just enclose them in their own quotes.

AntonH
  • 6,359
  • 2
  • 30
  • 40
2

There are multiple ways to do that,

String test = "Hello";

and then

System.out.println("\"" + test + "\"");

or

System.out.printf("\"%s\"%n", test);

or write a method to add quotes,

private static String quoteString(String in) {
  return String.format("\"%s\"", in);
}

then

System.out.println(quoteString(test));

Or perhaps

String test = quoteString("Hello");
System.out.println(test);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

To print the variable value enclosed in quotes, you have to concatenate the quotes:

System.out.println("\"" + test + "\"");
Roberto Linares
  • 2,215
  • 3
  • 23
  • 35