Google News
logo
Scala - Interview Questions
What is the difference between the println() and print() functions in Scala?
In Scala, both the `println()` and `print()` functions are used to output text or values to the console. The main difference between them lies in how they handle the end of the line:

1. `println()` : The `println()` function adds a newline character (`\n`) at the end of the output, which moves the cursor to the next line after printing the text. This means that each subsequent call to `println()` will print on a new line.
   println("Hello")
   println("World")​

   Output :
   Hello
   World​


   In this example, "Hello" is printed on one line, and then the cursor moves to the next line before printing "World" on a new line.
2. `print()` : The `print()` function does not add a newline character at the end of the output. It simply prints the text or value without moving the cursor to the next line. If you use multiple `print()` statements consecutively, they will all be printed on the same line.
   print("Hello ")
   print("World")​

   Output :
   Hello World​

   In this example, "Hello " and "World" are printed on the same line because no newline character is added between them.

So, the difference between `println()` and `print()` in Scala is the presence or absence of a newline character at the end of the output. If you want to print on a new line, you can use `println()`, and if you want to print on the same line, you can use `print()`. The choice depends on your specific formatting requirements.
Advertisement