0

I know that when we print a string on the output window using print functions in all the languages it get printed as a string only. But I want to know if I print an integer/float using same print function, is it going to get casted into string and then printed on the output screen or its type behavior is same as that of when we passed into print function?
I'm asking this question because I participated in some competitive programming and found that if we have to print integers from 1 to 500 on separate lines and if we run a "for" loop 500 times and call print() function each and every iteration/cycle then its going to take a lot of time. But if I create a variable which will hold a string only and I add the integers at the end of the string with a new line character with each and every iteration/cycle and print that string at last after trimming it then its going to take comparatively less time. Giving examples below---

This below Java "for" loop prints number during each iteration/cycle.

for(int i=1;i<=500;i++){
    System.out.println(i);
}

This below Java code defines a string variable then adds numbers at the end during each cycle of the loop with new line character. At last prints the string variable by trimming it so that the last new line charcater will be removed.

String buffer_str = "";
for(int i=1;i<=500;i++){
    buffer_str+=i+"\n";
}
System.out.println(buffer_str.trim());

So the question came into mind when I was thinking if both the answers are same or not. First code block prints integers while second code block prints a string.

I checked by using both code in python language too and found that the second code block is too fast while first code block was a bit slow. So second way seems good but is it appropriate and error proof?

I appreciate your answers.

Naino
  • 3
  • 2
  • Try your experiment with strings instead of integers; if you get similar results, the issue isn't converting integers to strings. – Scott Hunter Aug 31 '20 at 14:10

1 Answers1

0

Firstly, the function System.out.println converts the parameter to a string via the .toString() method (see https://docs.oracle.com/javase/tutorial/essential/io/formatting.html).

Secondly, it might be faster to first accumulate all the output into a buffer, because these I/O operations are relatively slow compared to modifying a variable in the main memory. As to why that is, consider this thread. With the second approach, you only have to go through that procedure once.

Niklas Mohrin
  • 1,756
  • 7
  • 23