C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Println: This writes a value to the console and adds a trailing newline. We can pass Strings, Ints or other types to it.
Print: This is the same as println but it adds no trailing newline. It just writes the data to the start of a line.
Printf: This writes a format string and inserts additional arguments. It is similar to the Java String.format method.
String.format: JavaScala program that uses println, print and printf
// Use println on a string.
println("Hello")
// In Scala println is the same as Console.println.
Console.println("World")
// Use print to have no trailing newline.
print("ABC")
print(123)
println()
// Use printf with a format string.
printf("Number = %d", 123)
Output
Hello
World
ABC123
Number = 123
Here: Control flow stops once readLine is invoked. Type something (like "cat") and press return. The variable now contains that string.
While: This loop continues infinitely. In a real program we might want a "quit" command.
WhileScala program that uses readLine, scala.io.StdIn
// Use an infinite loop.
while (true) {
// Read a line from the console window.
val line = scala.io.StdIn.readLine()
// Write the result string and a newline.
printf("You typed: %s", line)
println()
}
Output
cat
You typed: cat
bird
You typed: bird
Standard library definitions:
def print(x: Any) = Console.print(x)
def println() = Console.println()
Warning on readLine:
warning: method readLine in trait DeprecatedPredef is deprecated:
Use the method in scala.io.StdIn