Skip to content

Exploring Basic Kotlin Syntax and Structure – Day 2 Android 14 Masterclass

Exploring Basic Kotlin Syntax and Structure - Day 2 Android 14 Masterclass
Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

Exploring Basic Kotlin Syntax and Structure – Day 2 Android 14 Masterclass

Welcome to Day 2 of our Android 14 Masterclass, where we dive into the Basic Kotlin Syntax and Structure. As you embark on this coding journey, understanding Kotlin’s syntax and structure is paramount. Today, we’re peeling back the layers of this intuitive language, starting with variables and data types, maneuvering through user input and control flows, and mastering loops and operators. Whether you’re a seasoned developer or a novice in the app-making realm, our guide will solidify your foundation and equip you with the essential tools for crafting robust Android applications.

 

1. What are Variables?

Variables are fundamental building blocks in Kotlin programming (and programming in general), allowing developers to store, modify, and manage data within their applications. Variables can hold various types of data, such as numbers, characters, strings, or even more complex data structures like lists or objects.

Creating Variables: Exploring Basic Kotlin Syntax and Structure

In Kotlin, variables can be defined using either var or val keyword, followed by the variable name, an optional data type, and an assignment. The assignment operator is represented by the equals sign (=). The assignment operator is used to assign a value to a variable.

More examples:

val vs. var :

val: Stands for “value” and it’s immutable, which means once you assign a value to a val variable, you cannot change or reassign it.

Preferred when you have a variable whose value shouldn’t change once initialized, like constants or properties that should remain unchanged.

var: Is mutable, meaning after you assign an initial value, you can change or reassign that variable to a new value as many times as you want.

Used when you anticipate the value of a variable will change, like counters in a loop or a value being updated based on user input.

 

2. What are Datatypes?

When you’re programming, you work with different kinds of information or data, like numbers, words, or true/false values. Datatypes in Kotlin are like labels that tell the computer what kind of data you’re dealing with so it knows how to handle them properly.

You need to tell the computer the datatype of your information (like number, word, true/false) when you first create a variable. Once you set the type, it stays the same.

Integers (Int and Long)

Description: Integer types can hold whole numbers, both positive and negative. The most commonly used integer type is Int.For larger integer values, Long can be used.

Syntax and Examples:

Floats and Doubles (Float and Double)

Description: Floats and Doubles are used to represent decimal numbers. Double has higher precision and is generally used as the default for decimal numbers.

Syntax and Examples:

Booleans (Boolean)

Description: Booleans are like light switches in programming. They can only have two values: true (on) or false (off). They are used to make decisions in code, allowing parts of your program to run based on whether a condition is true or false.

Logical Operators:

  • || (Logical OR): Returns true if at least one condition is true.
  • && (Logical AND): Returns true only if both conditions are true.
  • ! (Logical NOT): Negates the value; turns true into false and vice versa.

Syntax and Examples:

| vs. || Operators

Both | and || operators are used with boolean values (true or false) in Kotlin, but they serve different purposes and behave differently.

  • Evaluation:
    • | always evaluates both operands.
    • || performs short-circuit evaluation, skipping the second operand if the first is true.
  • Use Cases:
    • | is versatile, used for bitwise or logical OR operations.
    • || is solely used for logical OR operations to control the flow of programs based on conditions.
  • Efficiency:
    • || can be more efficient due to short-circuit evaluation, as it may skip the evaluation of the second operand.
    • | might be slightly less efficient in logical operations as it always evaluates both operands.

Char

The char data type in Kotlin represents a single character. A character could be a letter, a number, a punctuation mark, or even a symbol like $ or &. Let’s break it down!

Characters are surrounded by single quotes (' ').

Unicode Characters:

Characters in Kotlin can also represent Unicode characters, allowing you to use a wide range of symbols and letters from various languages.

Example:

Special Characters:

There are also special escape characters in Kotlin, which allow you to represent special values such as a new line or a tab.

Example:

  • New line: '\\n' – moves to the next line
  • Tab: '\\t' – adds a tab space

Strings

Strings are sequences of characters enclosed within double quotes (” “). They are used to manage and manipulate text in Kotlin.

Strings are immutable, meaning once a string is created, it cannot be changed, but you can create a new string based on modifications of the original string.

String Concatenation:

Strings can be joined together using the + operator.

 

3. Type Conversion

Type conversion, also known as type casting, is a process where the type of a variable is converted to another datatype. Explicit conversion is often necessary when you want to work with variables of incompatible types together.

Common Type Conversions

Numbers:

You might want to convert between different number types, like from Int to Double, or Long to Int.

Numbers to Strings:

Numbers can be converted to strings when you want to display them as text or concatenate them with other strings.

Strings to Numbers:

If a string contains a number, you can convert that string into an actual number type, like Int or Double.

 

 

4. User Input

Getting input from the user is essential in programming when you want your application to interact with the user by receiving data that the user provides. In Kotlin, you can receive user input from the console using the standard library functions, making your programs interactive and dynamic.

If you want to ask the user for input and display it, you can use the combination of println() to show a message and readLine() to get the user’s response.

Here’s a simple way to do it:

 

5. Basic Kotlin Syntax – Understanding if and else if Statements

if and else if statements are used in Kotlin to make decisions in your code based on conditions. They allow your program to execute different blocks of code based on whether certain conditions are true or false.

  • if Statement:

An if statement checks a condition and executes a block of code if that condition is true.

In this example, since the age is 20 (which is greater than or equal to 18), the message “You are eligible to vote.” will be printed to the console.

  • The if-else Statement:

You can use an else statement following an if statement to execute a block of code when the condition in the if statement is false.

Here, because the age is 15 (which is less than 18), the condition in the if statement is false, so the message “You are not eligible to vote.” will be printed.

  • The else if Statement:

An else if statement follows an if statement and checks another condition if the previous condition was false.

In this example, since the number is not greater than 0, it checks the next condition (number == 0), which is true, so it prints “The number is zero.”

  • Combining if, else if, and else:

You can combine if, else if, and else to handle multiple conditions and a default case.

Here, the program checks multiple conditions:

  • If the number is positive, it prints “The number is positive.”
  • If the number is negative (which it is), it prints “The number is negative.”
  • If none of the above conditions are true, it defaults to printing “The number is zero.”

 

6. Basic Kotlin Syntax – Understanding when Statements

  • when is like a decision-maker in your code.
  • You give when a value, and it picks a result based on that value.
  • It makes your code cleaner and easier to understand when you have many choices.

So, you can think of the when statement as a smarter, more organized way of making decisions in your code compared to the if statement!

Example:

 

7. Basic Kotlin Syntax – Understanding while Loops

Imagine you have a robot that can repeat a task for you, like clapping hands or counting numbers. A while loop in Kotlin is like that robot. It keeps doing a task over and over as long as a certain condition is true.

How It Works:

Let’s say you want the robot to clap hands five times. You can tell the robot:

  1. Start counting from one.
  2. Clap your hands.
  3. If you haven’t clapped five times, go back to step 2.

In Kotlin, you write this like:

Warning: Be Careful of Infinite Loops! 

If you forget to tell the robot when to stop (like forgetting the count++), the robot will keep clapping hands forever!

This is called an “infinite loop,” and it can make your program run forever and not work correctly.

So, a while loop helps you repeat tasks in your code, but remember to always give it a stopping condition! More examples:

Basic Kotlin Syntax for Counting to Ten

In this example, as long as the variable number is less than or equal to ten, it will keep printing the number and then adding one to it.

Countdown

Here, the loop starts at five and counts down, subtracting one each time until it gets to one. Then it prints “Blast off!”

 

8. Basic Kotlin Syntax – Operators

Operators are special symbols or keywords that are used to perform operations. You have already seen some operators in the boolean section of this summary and in the code examples.

Let’s discuss some common categories of operators:

Arithmetic Operators

These are used for mathematical operations:

  • Addition +: 5 + 3 results in 8
  • Subtraction : 5 - 3 results in 2
  • Multiplication : 5 * 3 results in 15
  • Division /: 5 / 2 results in 2.5
  • Modulus %: 5 % 2 results in 1 (Remainder of 5 divided by 2)

Comparison Operators

These operators compare two values:

  • Equals ==: 5 == 3 results in false
  • Not Equals !=: 5 != 3 results in true
  • Greater Than >: 5 > 3 results in true
  • Less Than <: 5 < 3 results in false
  • Greater Than or Equal To >=: 5 >= 5 results in true
  • Less Than or Equal To <=: 5 <= 3 results in false

Assignment Operators

Used to assign values to variables:

  • Equals =: val x = 5
  • Plus Equals +=: x += 3 (Equivalent to x = x + 3)
  • Minus Equals =: x -= 3 (Equivalent to x = x - 3)
  • Multiply Equals =: x *= 3 (Equivalent to x = x * 3)
  • Divide Equals /=: x /= 3 (Equivalent to x = x / 3)

Logical Operators

Used for boolean logic (true or false values):

  • AND &&: true && false results in false
  • OR ||: true || false results in true
  • NOT !: !true results in false

 

Conclusion: Exploring Basic Kotlin Syntax and Structure – Day 2 Android 14 Masterclass

As we wrap up Day 2 of our Android 14 Masterclass, we’ve journeyed through the essential Basic Kotlin Syntax and structures that make Kotlin such a powerful and efficient tool for developers. From the versatility of variables to the logic of control statements and the persistence of loops, we’ve covered a breadth of fundamental concepts that are crucial for creating dynamic Android apps. Remember, these building blocks are just the starting point; with practice, you’ll continue to hone your skills and unlock the full potential of Kotlin in your Android development adventures. Keep experimenting, coding, and learning – your path to becoming a Kotlin connoisseur is well underway!

 

If you want to skyrocket your Android career, check out our  The Complete Android 14 & Kotlin Development Masterclass. Learn Android 14 App Development From Beginner to Advanced Developer. Build Apps like Trello, 7Min Workout, Weather App.

 

Check out Day 3 of this course here.

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide