Have you ever had a simple app idea, like a coffee-ordering app, and wondered: "How can the app remember how many cups I ordered? How does it calculate the total price?" The answer lies in one of the most powerful and fundamental concepts in programming: Variables.
In this article, we’ll embark on a practical journey to discover how variables transform static ideas into interactive and smart applications. Using a simple coffee-ordering app example, we'll learn how to make our app "think", make decisions, and dynamically interact with users.
A variable is a “box” or “container” in the app’s memory that stores a specific value. This value could be a number, text, or logical data (true or false). They give your app memory, allowing it to track changes.
Example in Kotlin:
var quantity: Int = 2
Each type of data has a matching variable type. Mastering these basic data types is key:
quantity
).Use variables for dynamic calculations:
val pricePerCup: Double = 5.0
var quantity: Int = 2
var totalPrice: Double = pricePerCup * quantity // Result: 10.0
Adding whipped cream using if statement:
val hasWhippedCream: Boolean = true
if (hasWhippedCream) {
totalPrice += quantity
}
val customerName: String = editTextName.text.toString()
val addWhippedCream: Boolean = whippedCreamCheckBox.isChecked
fun createOrderSummary(customerName: String, price: Double, quantity: Int, hasWhippedCream: Boolean): String {
var summary = "Name: $customerName"
summary += "\nQuantity: $quantity"
summary += "\nHas whipped cream? $hasWhippedCream"
summary += "\nTotal: $$price"
summary += "\nThank you!"
return summary
}
You can show this summary in a TextView
or a Toast.
To navigate between activities and pass data, use Intent:
val intent = Intent(this, OrderSummaryActivity::class.java)
intent.putExtra("ORDER_SUMMARY", orderSummaryString)
startActivity(intent)
What began as a simple coffee-ordering idea has now evolved into a functional system thanks to variables. You’ve learned how to:
Int
, String
)Boolean
, if
)*
, +
)Button
, EditText
)Intent
)These are the foundational elements of all complex apps. With a deep understanding of how to use and control variables, you've taken your first major step toward becoming a professional Android developer.
Now, go ahead and try it yourself!