0
0
Kotlinprogramming~5 mins

String type and immutability in Kotlin

Choose your learning style9 modes available
Introduction

Strings hold text in programs. They cannot be changed once created, which helps avoid mistakes.

When you want to store names or messages in your app.
When you need to compare or search text.
When you want to build text step-by-step safely.
When you want to pass text data between parts of your program.
When you want to keep text data safe from accidental changes.
Syntax
Kotlin
val text: String = "Hello, Kotlin!"

val means the string cannot be reassigned to a new value.

Strings are immutable, so you cannot change characters inside once created.

Examples
Create a string with text "Hi!" and store it in greeting.
Kotlin
val greeting: String = "Hi!"
Kotlin can guess the type String, so you can skip writing it.
Kotlin
val name = "Alice"
Combine two strings using + to make a new string.
Kotlin
val combined = greeting + " " + name
Get the number of characters in the string using length property.
Kotlin
val length = name.length
Sample Program

This program shows that you cannot change a character inside a string. Instead, you create a new string by adding text.

Kotlin
fun main() {
    val original = "Hello"
    // Try to change a character (not allowed)
    // original[0] = 'J' // This line would cause an error

    val newString = original + ", Kotlin!"
    println("Original string: $original")
    println("New string: $newString")
}
OutputSuccess
Important Notes

Strings are immutable, so any change creates a new string.

Use val to keep string references constant, but var can point to new strings.

To build text efficiently in loops, use StringBuilder instead of repeated string concatenation.

Summary

Strings hold text and cannot be changed once created.

Use + to combine strings and create new ones.

Immutability helps keep your text data safe and predictable.