1

Consider the following code (excerpt of main method):

String str = "The result: ";
int c = 5;
int k = 3;
System.out.println(str + c + k); // This would concatenate the all values, i.e. "The result: 53"

If the only thing allowed to be modified is within System.out.println(), is it possible to concatenate str to the sum of k and c?

ublec
  • 172
  • 2
  • 15

3 Answers3

1

Yes.

System.out.println(str + (c + k)); 

You can change order of execution by adding parentheses (same way as in math).

talex
  • 17,973
  • 3
  • 29
  • 66
1

Indeed, as @talex said, you may use this single line code. Yet, I think that this additude is a bit confusing, and may cause the code to be unreadable.

A better practice would be:

String str = "The result: ";
int c = 5;
int k = 3;
int result = c + k;
System.out.println(str + result);

This way, the code is more readable, and the order of execution will not confuse the programmers that read this code.

javadev
  • 688
  • 2
  • 6
  • 17
  • How is this a better practice? Having more lines of code is usually not 'better readable'. In such short snippets, sure, but this kind of code also occurs in not-so-small snippets. – Stultuske Mar 03 '21 at 07:55
  • Short code is not a good practice if it makes the code unreadable. Readability is one of the most important practices in the industry. – javadev Mar 03 '21 at 10:05
  • that is just assuming it'll be unreadable. System.out.println("The som is: " + (number1 + number2)); is very easy to read. If it's a print statement like this, many consider it easier to read than having to go over several lines of code. Yes, readability is important, so is efficiency. You are creating a variable you don't need. If you do this here, chances are, you're doing it all over your code. – Stultuske Mar 03 '21 at 10:28
0

Yes you should have use parentheses around sum of integers

System.out.println(str + (c + k));