Println Function
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 35 of 93.
You've been using println() throughout this course to display output. Now let's take a closer look at how it works and explore its sibling function, print().
The println() function prints text to the console and automatically moves the cursor to a new line afterward. println() adds its newline after the argument, so it continues on the current line when a previous print() has not ended that line:
fun main() {
println("First line")
println("Second line")
}
// Output:
// First line
// Second lineIn contrast, print() outputs text without adding a newline. Subsequent output continues on the same line:
fun main() {
print("Hello ")
print("World")
println("!")
println("New line here")
}
// Output:
// Hello World!
// New line hereNotice how "Hello ", "World", and "!" all appear on the same line because the first two use print(). The println("!") adds the exclamation mark and then moves to a new line for the final output.
Both functions can print any type of value: strings, numbers, booleans, or even expressions:
fun main() {
println(42)
println(3 + 5)
println(true)
}Challenge
EasyThe starter reads a passenger name. Use print for "Passenger: ", then println for the name so they appear together on one line. On the next line print Boarding soon. Do not print an input prompt.
Try it yourself
fun main() {
val passenger = readLine()!! // Provided input
// Write the two output lines.
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground