If you have followed the previous articles in this Android development series, you have already installed Android Studio and created your first Android project.
But there is an important skill you need before building larger applications: Kotlin programming.
Modern Android development heavily relies on Kotlin, so understanding its fundamentals will make the rest of this series much easier.
You don't need to become a Kotlin expert before developing Android applications. However, you should understand the basic building blocks of the language.
In this article, we will learn the fundamentals of Kotlin, including variables, data types, strings, operators, input, and basic expressions.
What Is Kotlin?
Kotlin is a modern, statically typed programming language developed by JetBrains.
It is designed to be concise, expressive, and interoperable with Java.
Kotlin has become an important language for Android development and is the primary language we will use throughout this series.
A simple Kotlin program looks like this:
fun main() {
println("Hello, Kotlin!")
}The output is:
Hello, Kotlin!Don't worry if some parts of this program are unfamiliar. We will understand them step by step.
Why Is Kotlin Important for Android Development?
An Android application isn't just a collection of buttons and screens.
Behind the user interface is programming logic.
For example, imagine an expense tracker.
When a user enters:
Amount: ₹500the application needs programming logic to:
Read the amount.
Store it.
Calculate totals.
Display the result.
Possibly save the information in a database.
Kotlin provides the programming tools needed to perform these operations.
A simplified application structure might look like:
User Interface
↓
Kotlin Logic
↓
Data
↓
Database / APIYour First Kotlin Program
Let's begin with a simple program.
fun main() {
println("Welcome to Kotlin")
}The output will be:
Welcome to KotlinNow let's understand it.
The fun Keyword
The keyword:
funis used to declare a function.
For example:
fun greet() {
println("Hello")
}Here, greet() is a function.
A function is a reusable block of code that performs a particular task.
The main() Function
The main() function is a common entry point for a standalone Kotlin program.
fun main() {
println("Hello")
}When the program starts, execution begins from the main() function.
Android applications have a different application lifecycle, so you won't normally create your Android application around a traditional main() function.
However, understanding main() is useful when learning Kotlin itself.
Printing Information
The simplest way to display information in Kotlin is:
println()For example:
fun main() {
println("Android Development")
println("Kotlin Programming")
}Output:
Android Development
Kotlin ProgrammingEach println() prints its content on a new line.
What Is a Variable?
A variable is a named location used to store a value.
For example:
val name = "Rahul"Here:
nameis the variable."Rahul"is the value.
You can later use the variable:
println(name)Output:
RahulVariables are extremely important in Android applications.
For example, you may need variables to store:
Username
Age
Email
Price
Quantity
Login Statusval and var
Kotlin provides two important keywords for declaring variables:
val
varUnderstanding the difference is essential.
Using val
val is used when a reference should not be reassigned after initialization.
Example:
val name = "Rahul"You cannot later write:
name = "Amit"because the val reference cannot be reassigned.
Using var
var is used when the variable needs to be reassigned.
Example:
var age = 20
age = 21This is valid because age was declared using var.
val vs var
A simple way to remember the difference:
val → cannot be reassigned
var → can be reassignedFor example:
val country = "India"
var score = 50
score = 75The country reference cannot be reassigned, while score can.
As a general programming practice, prefer val when you don't need reassignment.
Understanding Data Types
A data type tells Kotlin what kind of value a variable contains.
Some common Kotlin data types are:
IntLongFloatDoubleStringCharBoolean
Let's examine them.
Integer — Int
An Int stores whole numbers.
Example:
val age: Int = 20Another example:
var score: Int = 100Whole numbers don't contain decimal points.
Long — Long
Long is used for larger whole-number values.
Example:
val population: Long = 1400000000LThe L indicates that the value is a Long literal.
Double
Double is commonly used for decimal numbers.
Example:
val price: Double = 499.99Another example:
val temperature: Double = 32.5Float
Kotlin also provides Float.
Example:
val percentage: Float = 85.5FNotice the F at the end.
For many everyday calculations, Double is the more common choice unless you specifically need Float.
String
A String contains text.
Example:
val name: String = "Shivam"Another example:
val city: String = "Kolkata"Strings are extremely common in Android applications.
You will use them for things such as:
Names
Messages
Labels
URLs
Descriptions
User input
Character — Char
A Char represents a single character.
Example:
val grade: Char = 'A'Notice the difference:
'A'is a character.
While:
"A"is a string.
Boolean
A Boolean contains one of two values:
true
falseExample:
val isLoggedIn: Boolean = trueAnother example:
val isAvailable: Boolean = falseBooleans are extremely useful when creating application logic.
For example:
if (isLoggedIn) {
println("Welcome!")
}Kotlin Can Infer Data Types
You don't always need to explicitly write the data type.
For example:
val age = 20Kotlin understands that age is an integer.
Similarly:
val name = "Shivam"Kotlin understands that name is a String.
This is called type inference.
You can still explicitly specify the type:
val age: Int = 20Both approaches can be valid.
Arithmetic Operators
Kotlin supports the common arithmetic operators.
| Operator | Meaning |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Remainder |
Example:
fun main() {
val a = 20
val b = 5
println(a + b)
println(a - b)
println(a * b)
println(a / b)
println(a % b)
}Output:
25
15
100
4
0Understanding the Modulus Operator
The % operator returns the remainder after division.
Example:
println(10 % 3)Output:
1Because:
10 ÷ 3 = 3 remainder 1The modulus operator is useful for many programming problems.
For example, checking whether a number is even:
val number = 10
if (number % 2 == 0) {
println("Even")
}Comparison Operators
Kotlin provides operators for comparing values.
Common comparison operators include:
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal toExample:
val age = 20
println(age >= 18)Output:
trueLogical Operators
Kotlin also provides logical operators.
Important ones include:
&& AND
|| OR
! NOTExample:
val age = 20
val hasId = true
if (age >= 18 && hasId) {
println("Allowed")
}Both conditions must be true for the && expression to be true.
String Templates
One of Kotlin's convenient features is string templates.
Suppose we have:
val name = "Rahul"
val age = 20Instead of manually joining strings, we can write:
println("My name is $name")
println("I am $age years old")Output:
My name is Rahul
I am 20 years oldYou can also place expressions inside ${}.
For example:
val a = 10
val b = 20
println("Total = ${a + b}")Output:
Total = 30String templates will be very useful when displaying dynamic information in Android applications.
Reading User Input
When learning basic Kotlin outside Android, you may encounter:
readln()For example:
fun main() {
print("Enter your name: ")
val name = readln()
println("Hello $name")
}If the user enters:
Shivamthe output will be:
Hello ShivamThis is useful for learning Kotlin fundamentals.
However, Android applications normally receive user input through UI components rather than using console input.
Converting Data Types
Sometimes you need to convert one type into another.
For example:
val number = "100"Here, number is a String.
To convert it into an integer:
val value = number.toInt()Now value contains the integer:
100Other commonly used conversion functions include:
toInt()
toLong()
toFloat()
toDouble()
toString()For example:
val price = 499.99
val text = price.toString()Comments in Kotlin
Comments are notes written inside the source code.
The compiler ignores them.
A single-line comment begins with:
//Example:
// This stores the user's age
val age = 20For multiple lines, Kotlin supports block comments:
/*
This is a
multi-line comment.
*/Comments can make code easier to understand.
Basic Kotlin Program
Let's combine several concepts.
fun main() {
val name = "Shivam"
val age = 20
val course = "Android Development"
println("Name: $name")
println("Age: $age")
println("Course: $course")
}Output:
Name: Shivam
Age: 20
Course: Android DevelopmentThis small program demonstrates:
Variables
Strings
Integers
String templates
println()
A Simple Calculation Program
Let's create another example.
fun main() {
val price = 500
val quantity = 3
val total = price * quantity
println("Price: ₹$price")
println("Quantity: $quantity")
println("Total: ₹$total")
}Output:
Price: ₹500
Quantity: 3
Total: ₹1500The same programming concepts will later be used inside Android applications.
Why These Fundamentals Matter in Android
You might wonder:
"Why am I learning variables and operators when I want to build Android apps?"
Because Android applications constantly use these concepts.
Imagine a shopping application.
It might contain:
val productName = "Headphones"
val price = 1999
var quantity = 2
val total = price * quantityThe application then needs to display:
Headphones
₹1999
Quantity: 2
Total: ₹3998The user interface may look advanced, but the underlying logic still depends on fundamental programming concepts.
Kotlin and Android: How They Fit Together
Think of Android development as a combination of several layers:
Android Application
│
┌──────────┴──────────┐
│ │
User Interface App Logic
│ │
Jetpack Compose Kotlin
│ │
└──────────┬──────────┘
│
Android
PlatformKotlin handles the programming logic.
Jetpack Compose helps us create the modern user interface.
Android provides the platform and APIs.
Together, these technologies allow us to build complete applications.
Practice Exercises
Before continuing with the series, try these exercises yourself.
Exercise 1: Personal Information
Create a Kotlin program that stores:
Name
Age
City
Course
and displays them.
Exercise 2: Rectangle
Create variables for:
Length = 10
Breadth = 5Calculate:
Area
PerimeterExercise 3: Shopping Bill
Create:
Price = 250
Quantity = 4Calculate the total amount.
Exercise 4: Even or Odd
Create an integer and determine whether it is even or odd using %.
Exercise 5: Age Check
Create an age variable and display:
Eligibleif the age is 18 or above.
Common Beginner Mistakes
While learning Kotlin, beginners often make a few mistakes.
Mistake 1: Confusing val and var
Remember:
val → cannot be reassigned
var → can be reassignedMistake 2: Confusing String and Char
Correct:
val letter: Char = 'A'
val name: String = "Amit"Mistake 3: Forgetting Type Conversion
This:
val number = "100"does not create an integer.
It creates a String.
You can convert it using:
val value = number.toInt()Mistake 4: Learning by Copying
Don't just copy programs from tutorials.
Try writing them yourself.
Then change the values and see what happens.
What You Should Know Before Moving Forward
After completing this article, you should understand the basic purpose of:
fun
main()
println()
val
var
Int
Long
Float
Double
String
Char
Boolean
+
-
*
/
%
Comparison operators
Logical operators
String templatesYou don't need to memorize everything immediately.
Practice is more important than memorization.
What's Next?
We have covered the first layer of Kotlin.
But our programs currently execute instructions sequentially.
Real applications need to make decisions.
For example:
Is the user logged in?
↓
YES → Show Home
↓
NO → Show LoginSimilarly:
Is the password correct?
↓
YES → Login successful
↓
NO → Show errorTo create this kind of logic, we need conditional statements.
In the next article, we will learn:
ifelseelse ifNested conditions
whenMultiple conditions
Practical Kotlin programs
These concepts will later become extremely useful when building Android applications.
Conclusion
Kotlin is the programming foundation of our Android development journey.
In this article, we learned the basic building blocks of Kotlin, including variables, data types, operators, string templates, input, and type conversion.
Don't rush through these concepts.
A strong understanding of programming fundamentals will make advanced Android topics much easier later.
For now, open your Kotlin development environment, write the examples yourself, modify them, and experiment.
The objective is not just to read Kotlin code.
The objective is to become comfortable writing it.
Comments
Post a Comment