Print a String in Kotlin

Developers have grown to love the modern, succinct, and expressive programming language Kotlin for its ease of use and adaptability.

You’ve come to the right place if you’re new to Kotlin and want to learn how to print a String. We’ll go over the fundamentals of printing a string in Kotlin in this tutorial.

Syntax

print(str)
//or
println(str)

To print a string in Kotlin, you can use the println() function, which stands for “print line.” Here’s how you can print a string in Kotlin:

fun main() {
    val myString = "Hello, World!"
    println(myString)
}

In this example, we define a string variable myString and assign the value “Hello, World!” to it. Then, we use the println() function to print the contents of myString to the console.

The println() Function

In Kotlin, you can print a string to the console using the println() function. This function stands for “print line” and is used to display text output. Let’s take a look at a simple example:

fun main() {
    val myString = "Hello, World!"
    println(myString)
}

In this code snippet, we do the following:

  1. Define a variable myString and assign the string “Hello, World!” to it.
  2. Use the println() function to print the contents of myString to the console.

When you run this program, you’ll see the text “Hello, World!” displayed in the console.

More Printing Options

While println() is the most common way to print strings in Kotlin, you can also use other print-related functions for different purposes:

  • print(): This function prints the text without a line break, so the next output will be on the same line.
fun main() {
    val name = "Alice"
    print("Hello, ")
    print(name)
    print("!")
}

Output:

Hello, Alice!

System.out.print(): You can also use System.out.print() for printing without a line break. It’s similar to print().

fun main() {
    val number = 42
    System.out.print("The answer is: ")
    System.out.print(number)
}

Output:

The answer is: 42

Conclusion

Printing a string in Kotlin is straightforward, thanks to the println() function. You can use it to display text output in your Kotlin programs. As you continue to explore Kotlin, you’ll discover its many other features and capabilities that make it a powerful and enjoyable programming language to work with.

Now that you’ve learned how to print a string in Kotlin, you can start building more complex applications and explore the language’s full potential. Happy coding!

Related Posts

How to Find Kotlin String Length

Define String Constants in Kotlin

Creating an Empty String in Kotlin

Kotlin – Initialize String

Kotlin String Operations with Example

Kotlin – Create Custom Exception