3

I am writing some code right now and I haven't done this in a while, how would I use the println function to write both a string and a variable?

I tried the following:

System.out.println("randomtext"var);

and

System.out.println("randomtext",var);

Neither of those seemed to work, what am I doing wrong? How do I do this?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Parker Moore
  • 31
  • 1
  • 1
  • 2
  • 3
    try simple: `System.out.println("randomtext" + var);` - this will automatically call toString method of var object – Iłya Bursov Oct 15 '13 at 22:58

4 Answers4

14

You either need to use + to concatenate, or use String.format to format a string or similar.

The easiest is to do concatenation:

System.out.println("randomtext" + var);

Some people often use System.out.printf which works the same way as String.format if you have a big messy string you want to concatenate:

System.out.printf("This is %s lot of information about %d and %s", var, integer, stringVar);

When using String.format the most important formatters you need to know is %s for Strings, %f for floating-point numbers, %d for integers.

More information about how to use String.format can be found in the documentation about Formatter.

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
3

You can concatenate the two strings together; the overloaded println methods take at most one parameter.

System.out.println("randomtext" + var);
rgettman
  • 176,041
  • 30
  • 275
  • 357
1
System.out.println(String.format("randomtext %s", var));
alterfox
  • 1,675
  • 3
  • 22
  • 37
0

System.out.print("The sum of two number would be: "+(num1+num2));

  • 1
    Welcome to StackOverflow! Please add some explanation to your answer. Especially since you are answering to a very old question that already has answers, tell us what is different or new about it. – soundflix Jul 29 '23 at 21:02