Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

Kotlin Fundamentals You Need Before Building Serious Android Apps

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: ₹500

the application needs programming logic to:

  1. Read the amount.

  2. Store it.

  3. Calculate totals.

  4. Display the result.

  5. 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 / API

Your First Kotlin Program

Let's begin with a simple program.

fun main() {
    println("Welcome to Kotlin")
}

The output will be:

Welcome to Kotlin

Now let's understand it.


The fun Keyword

The keyword:

fun

is 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 Programming

Each 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:

  • name is the variable.

  • "Rahul" is the value.

You can later use the variable:

println(name)

Output:

Rahul

Variables are extremely important in Android applications.

For example, you may need variables to store:

Username
Age
Email
Price
Quantity
Login Status

val and var

Kotlin provides two important keywords for declaring variables:

val
var

Understanding 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 = 21

This 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 reassigned

For example:

val country = "India"

var score = 50
score = 75

The 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:

  • Int

  • Long

  • Float

  • Double

  • String

  • Char

  • Boolean

Let's examine them.


Integer — Int

An Int stores whole numbers.

Example:

val age: Int = 20

Another example:

var score: Int = 100

Whole numbers don't contain decimal points.


Long — Long

Long is used for larger whole-number values.

Example:

val population: Long = 1400000000L

The L indicates that the value is a Long literal.


Double

Double is commonly used for decimal numbers.

Example:

val price: Double = 499.99

Another example:

val temperature: Double = 32.5

Float

Kotlin also provides Float.

Example:

val percentage: Float = 85.5F

Notice 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
false

Example:

val isLoggedIn: Boolean = true

Another example:

val isAvailable: Boolean = false

Booleans 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 = 20

Kotlin 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 = 20

Both approaches can be valid.


Arithmetic Operators

Kotlin supports the common arithmetic operators.

OperatorMeaning
+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
0

Understanding the Modulus Operator

The % operator returns the remainder after division.

Example:

println(10 % 3)

Output:

1

Because:

10 ÷ 3 = 3 remainder 1

The 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 to

Example:

val age = 20

println(age >= 18)

Output:

true

Logical Operators

Kotlin also provides logical operators.

Important ones include:

&&   AND
||   OR
!    NOT

Example:

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 = 20

Instead 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 old

You can also place expressions inside ${}.

For example:

val a = 10
val b = 20

println("Total = ${a + b}")

Output:

Total = 30

String 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:

Shivam

the output will be:

Hello Shivam

This 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:

100

Other 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 = 20

For 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 Development

This 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: ₹1500

The 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 * quantity

The application then needs to display:

Headphones
₹1999
Quantity: 2
Total: ₹3998

The 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
                  Platform

Kotlin 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 = 5

Calculate:

Area
Perimeter

Exercise 3: Shopping Bill

Create:

Price = 250
Quantity = 4

Calculate 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:

Eligible

if 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 reassigned

Mistake 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 templates

You 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 Login

Similarly:

Is the password correct?
        ↓
    YES → Login successful
        ↓
     NO → Show error

To create this kind of logic, we need conditional statements.

In the next article, we will learn:

  • if

  • else

  • else if

  • Nested conditions

  • when

  • Multiple 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

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? 📌 Readability – Comments make code easier to understand for you and others. 📌 Maintenance – When you revisit your code after months, comments remind you what you were doing. 📌 Collaboration – In team projects, comments explain code to fellow developers. 📌 Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . 💻 Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } 🧠 Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

💡 Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. 🧑‍💻 Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...