String Data Type in Java and Kotlin (Immutability, Null Safety, Examples)
Table of Contents
Introduction
The String data type is used to store a sequence of characters (text). Strings are one of the most commonly used data types in both Java and Kotlin, especially for handling user input, messages, and data processing.
String in Java
In Java, String is a class, not a primitive type. Strings in Java are immutable, meaning once created, their value cannot be changed.
- Stored as objects in the heap
- Immutable by design
- Supports String Pool for memory optimization
Java Example
String name = "CodeCrush";
name = name + " Corner";
System.out.println(name);
Although it looks like the string is modified, Java actually creates a new String object.
String in Kotlin
In Kotlin, String is also a class and is immutable. Kotlin adds powerful features such as string templates and null safety.
- Immutable by default
- Supports string templates using
$ - Nullable and non-nullable strings
Kotlin Example
val name = "CodeCrush"
val site = "$name Corner"
println(site)
Nullable String Example
var text: String? = null
println(text?.length)
String Length & Access
Java
String message = "Hello";
System.out.println(message.length());
System.out.println(message.charAt(0));
Kotlin
val message = "Hello"
println(message.length)
println(message[0])
Java vs Kotlin – String Differences
| Feature | Java | Kotlin |
|---|---|---|
| Type | Class | Class |
| Immutability | Yes | Yes |
| String Templates | No | Yes ($variable) |
| Null Safety | No | Yes |
| Character Access | charAt() | [] operator |
Interview Questions & Answers
Q1. Are strings mutable in Java and Kotlin?
Answer: No. Strings are immutable in both Java and Kotlin, meaning their value cannot be changed once created.
Q2. What is string immutability?
Answer: Once a string is created, its value cannot be changed. Any modification creates a new object.
Q3. What are string templates in Kotlin?
Answer: They allow embedding variables directly inside strings
using $ or ${expression}.
Q4. How does Kotlin handle null strings safely?
Answer: Kotlin uses nullable types (String?)
and safe-call operators (?.) to prevent NullPointerException.
Conclusion
Strings are essential for almost every application. While Java and Kotlin both treat strings as immutable, Kotlin improves safety and readability with null safety and string templates, making string handling simpler and safer.
Comments
Post a Comment