import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class VariableDemoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_variable_demo)
val name: String = "John"
var age: Int = 25
var city: String? = null
val nameTextView = findViewById<TextView>(R.id.nameTextView)
val ageTextView = findViewById<TextView>(R.id.ageTextView)
val cityTextView = findViewById<TextView>(R.id.cityTextView)
val changeAgeButton = findViewById<Button>(R.id.changeAgeButton)
val setCityButton = findViewById<Button>(R.id.setCityButton)
nameTextView.text = "val name: $name"
ageTextView.text = "var age: $age"
cityTextView.text = "nullable city: ${city ?: "Unknown"}"
changeAgeButton.setOnClickListener {
age += 1
ageTextView.text = "var age: $age"
}
setCityButton.setOnClickListener {
city = "New York"
cityTextView.text = "nullable city: ${city ?: "Unknown"}"
}
}
}We declare name as val because it does not change. age is var because it changes when the button is clicked. city is a nullable String? initialized to null.
We use the safe call with the Elvis operator ?: to show "Unknown" if city is null.
Buttons update the variables and the UI text accordingly, demonstrating variable mutability and null safety in Kotlin.