0
0
KotlinConceptBeginner · 3 min read

What is String in Kotlin: Simple Explanation and Example

In Kotlin, a String is a sequence of characters used to store text. It is an immutable data type, meaning once created, its content cannot be changed.
⚙️

How It Works

Think of a String in Kotlin like a necklace made of beads, where each bead is a character. This necklace holds letters, numbers, or symbols in a specific order to form words or sentences. Once you create this necklace, you cannot change the beads inside it, but you can create a new necklace if you want a different sequence.

Kotlin treats String as an immutable object, which means you cannot alter its characters after it is created. This helps keep your text data safe and predictable. When you need to change text, Kotlin creates a new String with the changes instead of modifying the original.

đź’»

Example

This example shows how to create a String and print it in Kotlin.

kotlin
fun main() {
    val greeting: String = "Hello, Kotlin!"
    println(greeting)
}
Output
Hello, Kotlin!
🎯

When to Use

Use String in Kotlin whenever you need to work with text, such as names, messages, or any readable information. For example, you might store a user's name, display a welcome message, or handle input from a keyboard.

Since String is immutable, it is safe to share across different parts of your program without worrying about accidental changes. If you need to build or modify text repeatedly, consider using StringBuilder for better performance.

âś…

Key Points

  • String holds a sequence of characters.
  • It is immutable, so its content cannot be changed after creation.
  • Strings are used to represent text like words and sentences.
  • To change text, Kotlin creates a new String rather than modifying the old one.
  • Use StringBuilder for efficient text modifications.
âś…

Key Takeaways

A String in Kotlin is an immutable sequence of characters used to store text.
Once created, a String cannot be changed; modifications create new Strings.
Strings are ideal for storing names, messages, and any readable text.
Use StringBuilder when you need to efficiently modify text repeatedly.
Kotlin’s String immutability helps keep your data safe and predictable.