Variables, Data Types, and Operators in Kotlin
# CHAPTER 4
Variables, Data Types, and Operators in Kotlin
1. Introduction
In the previous chapter, we learned how to store data in named boxes called variables. However, we barely scratched the surface of how Kotlin manages computer memory. Building robust Android applications requires extreme precision regarding what data can be mutated (changed) and what specific format that data takes (text, decimals, true/false). In this chapter, we will master Variables, Data Types, and Operators in Kotlin. We will explore the critical architectural difference betweenvar and val, explicitly define primitive Data Types, and perform mathematical operations.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Understand and utilize the difference between Mutable (
var) and Immutable (val) variables.
-
Explicitly declare data types (
Int,Double,Boolean,String).
- Perform mathematical operations using Arithmetic Operators.
- Execute Type Conversions safely.
3. The Golden Rule: val vs var
Kotlin has two entirely different keywords for creating variables. Understanding the difference is the most important concept in Kotlin memory management.
var (Variable / Mutable): The data inside this box CAN be changed later.
val (Value / Immutable): The data inside this box is LOCKED. It can NEVER be changed once assigned. It is a "constant".
*Best Practice Rule:* ALWAYS use val unless you are absolutely certain the variable needs to change in the future. This prevents massive bugs where data is accidentally overwritten!
4. Explicit Data Types
While Type Inference (letting Kotlin guess) is great, sometimes you want to explicitly tell the computer exactly what type of data the box must hold. You do this using a colon:.
-
Int: Whole numbers (e.g., 10, -500)
-
Double: Decimal numbers (e.g., 3.14, 99.99)
-
Boolean: True or False flags.
-
String: Text wrapped in double quotes.
5. Type Conversion
If you try to add anInt to a String, the app will crash. You must convert types explicitly! Kotlin provides built-in helper functions like .toInt(), .toDouble(), and .toString().
6. Arithmetic Operators
Kotlin uses standard mathematical symbols:-
Addition:
+
-
Subtraction:
-
-
Multiplication:
*
-
Division:
/
-
Modulus (Remainder):
%
7. Logical Operators
When dealing withBoolean variables (True/False), we use logical operators to combine conditions.
-
&&(AND): Both sides must be true.
-
||(OR): Only one side needs to be true.
-
!(NOT): Reverses the boolean (True becomes False).
8. Mini Project: Character Stats
Let's combine explicit data types,val vs var, and arithmetic operators.
9. Common Mistakes
-
Integer Division: If you divide two
Intvariables in Kotlin (e.g.,val result = 5 / 2), the answer will be2, NOT2.5. Because both numbers are Integers, Kotlin chops off the decimal! To get a decimal answer, at least one number must be aDouble(e.g.,val result = 5.0 / 2).
-
Reassigning
val: Beginners often usevaleverywhere because it's shorter to type, and then get frustrated when the compiler throws errors when they try to update a score counter. Remember:val= Locked.var= Changeable.
10. Best Practices
-
Prefer
valOvervar: In enterprise Android engineering, mutability (data changing) is the number one cause of unpredictable bugs. If you create a variable that just holds a downloaded URL, and it never needs to change, it MUST be aval. Only elevate it tovarif the application logic strictly demands mutation.
11. Exercises
-
1.
Declare a mutable variable named
temperatureand explicitly assign it aDoubledata type with a value of98.6.
-
2.
Change the value of
temperatureto100.2.
12. Coding Challenges
Challenge: Write a script that converts Celsius to Fahrenheit. Create an immutableval named celsius set to 25.0. The formula for Fahrenheit is (celsius * 9/5) + 32. Execute the math, store it in a val named fahrenheit, and print the result using string interpolation.
13. MCQ Quiz with Answers
In Kotlin, what is the fundamental architectural difference between the val and var keywords?
A developer writes: val input = "50". They want to multiply this value by 2. Which of the following code snippets correctly prevents a Type Mismatch crash?
14. Interview Questions
-
Q: Explain the paradigm of "Immutability" in software engineering. Why does Kotlin heavily encourage developers to default to
valinstead ofvar?
-
Q: Describe the behavior of Integer Division in Kotlin. If you execute
val ratio = 10 / 3, what is the exact data type and value assigned toratio, and why?
-
Q: Contrast the Explicit Data Type declaration (
val age: Int = 10) with Type Inference (val age = 10). In what specific architectural scenario might Explicit Declaration be absolutely mandatory?
15. FAQs
Q: I see some code usingconst val. What is the difference between val and const val?
A: A standard val is determined at "Runtime" (when the app is actually running). A const val is determined at "Compile Time" (before the app even launches). const val is strictly used for global constants at the very top of a file, like const val BASEAPIURL = "https://google.com".
16. Summary
In Chapter 4, we solidified our understanding of Kotlin memory allocation. We mastered the critical architectural rule of Immutability, learning to default toval to prevent unpredictable data mutation, elevating to var only when strictly necessary. We took direct control over memory structures by explicitly defining primitive Data Types (Int, Double, String, Boolean), successfully executed Type Conversions to bridge disparate data formats, and manipulated logic utilizing fundamental Arithmetic and Logical Operators.