0% found this document useful (0 votes)
9 views67 pages

Lecture 02 - Introduction To Mobile Programming

Mobile programming lecture!! The top university bfcai, actually benha university who made it. Cheers!

Uploaded by

Omar Rnr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views67 pages

Lecture 02 - Introduction To Mobile Programming

Mobile programming lecture!! The top university bfcai, actually benha university who made it. Cheers!

Uploaded by

Omar Rnr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Development of Native Android Apps

Kotlin Variables and Operators

Dr. Ahmed Tawfik


Computer Science Department
Agenda
 Variables

 Data Types

 Constants and Type Inference

 Naming Conventions

 Null Safety

 Late Initialization (lateinit)

 Casting And Data Type Conversions

 Comments

2
Agenda, Cont.
 Taking Input From User

 Arithmetic Operators

 Assignment Operators

 Increment And Decrement Operators

 Comparison Operators

 Logical Operators

 Range Operator

 Bitwise Operators

 Operators Precedence

3
KOTLIN
Your First Kotlin Program
Your First Kotlin Program

 Here is the first simple program.

 The print() function outputs text without appending a newline character, whereas the
println() function adds a newline character after the text.

5
KOTLIN
Variables
Kotlin Variable
 A Kotlin variable is a container that stores a meaningful value, which can be

utilized throughout a program. Before using a variable, it must be declared.

 This declaration allocates memory space to hold values of the specified type.

 In Kotlin, variables are declared using either the val or var keywords:

 val: Immutable variables whose values cannot be changed once initialized.

 var: Mutable variables that can be reassigned new values after initialization.

7
Kotlin Variable, Cont.

 The basic syntax for declaring a variable in Kotlin is:

 var variableName: variableType = value

 Kotlin variables have three key characteristics:

 Variable Name (Identifier): Represents the name of the variable.

 Data Type: Specifies the type of data (e.g., Int, String).

 Value: Holds the actual data assigned to the variable.

8
Kotlin Variable Name
 In Kotlin, A variable name is an identifier, which is a sequence of characters

consisting of: Letters, Digits, Underscores "_", and Dollar signs "$".

 It must start with: Letter, Underscore "_“, or Dollar sign "$"

 Kotlin is "case-sensitive", meaning that uppercase and lowercase letters are

treated as distinct.

 The identifier cannot match any of Kotlin's reserved words, such as public, class,

or static.

9
Kotlin Variable, Cont.
 Here's an example demonstrating variable declaration and
initialization:

fun main() {
var id: Int = 5

println(id)

// Modifying the value of a mutable variable


id = 2
println("Updated id: $id")

// Can't Modify the value of val


}

10
KOTLIN
Data Types
Kotlin Data Types

 Kotlin, like many programming languages, supports various data types

to represent different kinds of values.

 Primitive Data Types: These are basic data types that store single values such as

Integers, Floating-Point Numbers, Characters, Booleans, and more.

 Non-Primitive Data Types: These are more complex data types built using primitive

data types. The most common non-primitive data type in Kotlin is String, which

represents a sequence of characters.

12
Integers

 Integers in Kotlin represent whole numbers without any fractional or

decimal parts.

 These numbers can be both positive and negative.

 Signed integers in Kotlin include both positive and negative numbers. Kotlin

supports signed integer types like Byte, Short, Int, and Long.

 Unsigned integers are a special category introduced in Kotlin 1.3 that can only hold

non-negative values (zero and positive numbers).

13
Signed Integers

Type Bits Value Range

Byte 8 -128 … 127

Short 16 -32768 … 32767

Int 32 -231 …231-1

Long 64 -263 …. 263-1

14
Unsigned Integers

Type Bits Value Range

UByte 8 0 … 255

UShort 16 0 … 65535

UInt 32 0 …232-1

ULong 64 0 …. 264-1

15
Floating-Point Numbers

 Floating-point numbers are used to represent numbers with decimal points. Kotlin

supports two types: Float and Double (default).

Type Bits Type

Float 32 Float

Double 64 Double

16
Characters

 In Kotlin, Characters are represented using the keyword Char.

 Char types are declared using single quotes ' '.

Type Bits

Char 16

17
Boolean

 The Boolean data type represents logical values and can hold only two possible values:

true or false.

Type Byte

Boolean 1

18
String

 In Kotlin, the Char type represents a single character, while the String type is used to

represent a sequence of characters, making it suitable for representing strings of text.

Type Byte

Variable depends on the number of characters (each character


String
typically 2 bytes for Unicode)

19
KOTLIN
Constants and Type Inference
Constants
 In Kotlin, constants are declared using the val keyword and the const modifier.

 The val keyword is used for declaring runtime constants with immutable values that can be

initialized at runtime.

 On the other hand, the const keyword is specifically used for declaring compile-time constants

with immutable values known at compile time.

const val PI = 3.14159


fun main() {
println("Value of PI: $PI")
}

21
Type Inference
 Kotlin supports type inference, allowing the compiler to automatically infer the data type based

on the value assigned to the variable.

 This reduces the need for explicit type declarations, making the code more concise.

fun main() {
val text = "Hello, Kotlin!" // Compiler infers text is of type String
val count = 10L // Compiler infers count is of type Long by using 'L'
after the number
println(text::class) // Prints class [Link]
println(count::class) // Prints long
}

22
KOTLIN
Naming Conventions
Kotlin Naming Conventions

 Naming conventions in Kotlin are essential for writing clear and readable code.

 Variables:

 Start with a lowercase letter.

 Use camelCase for multi-word names.

 Use descriptive names that convey the purpose of the variable.

 Example: ‘emailAddress', 'userName', 'totalAmount'.

24
Kotlin Naming Conventions, Cont.

 Naming conventions in Kotlin are essential for writing clear and readable code.

 Constants:

 Use all uppercase letters.

 Separate words with underscores "_" for readability.

 Use meaningful names that describe the constant's purpose.

 Example: MAX_VALUE, MIN_SCORE, PI.

25
Kotlin Naming Conventions, Cont.

 Data Types:

 Use the names of the data type correctly.

 Start with an uppercase letter.

 Example: String, Int, Boolean.

26
KOTLIN
Null Safety
Null Safety
 In Kotlin, there are only a few scenarios that can lead to a NullPointerException:

 Explicit invocation of throw NullPointerException().

 Use of the not-null assertion operator ‘!!’.

 Interaction with Java code: Accessing a member of a null reference.

 Kotlin introduced a clear difference between references that can handle null values and those that cannot:

 For instance, a standard variable of type String cannot accept null values: var firstName: String = “Omar“

 The question mark (?) symbol is used to declare a nullable variable: var anyString: String? = null

28
Null Safety, Cont.
1. Safe Calls (?) Kotlin provides safe operators like the safe call operator '?' for accessing a property on a nullable variable

 Example: val text: String? = null  println(text?.length) // Print null

2. Elvis Operator (?:) If the expression to the left of '?:' is not null, the Elvis operator returns it; otherwise, it returns the expression to

the right.

 Example: val text: String? = null  val length: Int = text?.length?: -1  println("The length is

$length") // Prints The length is -1

3. The Double Bang (!!) Operator the not-null assertion double bang operator (!!) converts any value to a non-nullable type and

throws an exception if the value is null.

 Example: val text: String? = null  val length: Int = text!!.length  println("The length is $length") //

Exception in thread "main" [Link]

29
KOTLIN
Late Initialization (lateinit)
Late Initialization (lateinit)
 Kotlin allows non-null properties to be initialized later in the code using the lateinit modifier.

 This is especially useful when the property's value cannot be assigned during declaration but will be provided at runtime.

 The property must be initialized before it is accessed; otherwise, accessing it will result in an Exception.

 Note that the lateinit modifier can only be used with mutable (var) properties of non-primitive types.

 It is not allowed for properties of primitive types like Int, Double, etc.

lateinit var name: String


fun main() {
name = "Ahmed"
print(name) // Prints Ahmed
}

31
KOTLIN
Casting And Data Type Conversions
Casting and Data Type Conversions

 Kotlin offers several ways to convert between different data types:

 Explicit type conversion using toType() functions such as toInt(), toString(), toDouble(), etc.

 Unsafe casts using the as operator. If the cast is invalid, it throws a ClassCastException at runtime.

 Safe casts using the as? operator. If the cast fails, it returns null instead of throwing an exception.

 Smart casts, where the compiler automatically casts a variable to the target type after a type check (e.g.,

using is or !is).

These features enhance both safety and flexibility when working with different types in Kotlin.

33
Type Casting
 Type casting in Kotlin can be performed using the 'toType()' functions.

 These functions attempt to convert a value to a specific type. If the cast fails at runtime, a

ClassCastException is thrown.

fun main() {
val gpa: Double = 3.5
val n: Int = [Link]() // Explicit type casting
println(n) // Output: 3
}

34
Unsafe Casts
 Unsafe casts in Kotlin are performed using the 'as' operator.

 If the cast fails, it throws a ClassCastException at runtime.

 This is considered unsafe because it doesn't provide compile-time safety checks, and the

developer must ensure that the cast will always succeed at runtime.

fun main() {
val n: Int = 123
val s: String? = n as String // Unsafe cast using as
println(s) // Output: ClassCastException
}

35
Safe Casts
 Kotlin offers a safe cast operator 'as?' for type casting, ensuring safety during casting

operations.

 If the casting is not feasible, it returns null instead of throwing a ClassCastException exception.

fun main() {
val n: Int = 123
val s: String? = n as? String // Unsafe cast using as
println(s) // Output: null
}

36
Smart Casts
 Smart casts in Kotlin occur automatically based on type checks within a specific code block.

 The compiler automatically casts variables to their specific type within that block.

 When employing 'is' or '!is' to check a variable's type, the compiler monitors this information and

internally converts the variable to the target type within the scope if 'is' or '!is' evaluates to true.
fun main() {
val obj: Any = "Kotlin"
if(obj is String) {
// No Explicit Casting needed.
println("String length is ${[Link]}") // Output: String length is 6
}
}

37
KOTLIN
Comments
Kotlin Comments
 Comments in Kotlin are similar to those in Java and other programming languages, providing a way to

document code and improve its readability.

 Kotlin supports single-line comments using '//' and multi-line comments using ‘/* */’.

 Additionally, Kotlin supports documentation comments using ‘/** */' for generating API documentation.

// This is a single-line comment

/*
This is a multi-line comment
*/

/**
* This is a documentation comment
*/

39
KOTLIN
Taking Input From User
Taking Input from User
 Handling user input is a common requirement in many applications.

 In Kotlin, the readLine() function is used to read input from the standard input stream (stdin).

 It reads an entire line entered by the user and returns it as a String.

 If the input is expected to be a different data type (such as Int, Double, etc.), you must explicitly convert the

string using appropriate conversion functions like toInt() or toDouble().


fun main() {
print("Enter your id: ")
val id: Int? = readLine()?.toInt()
println("Your id is $id") // Output: Your id is 5
}

41
KOTLIN
Arithmetic Operators
Arithmetic Operators

Operator Meaning Example

+ Addition c = a + b;

- Subtraction c = a - b;

* Multiplication c = a * b;

/ Division c = a / b;

% Reminder c = a % b;

43
Arithmetic Operators, Cont.
 Example of arithmetic operators:
fun main() {
val a = 5
val b = 2
val sum = a + b
val difference = a - b
val product = a * b
val quotient = a / b
val remainder = a % b
println("Sum: $sum") // Output => Sum: 7
println("Difference: $difference") // Output => Difference: 3
println("Product: $product") // Output => Product: 10
println("Quotient: $quotient") // Output => Quotient: 2
println("Remainder: $remainder") // Output => Remainder: 1
}

44
KOTLIN
Assignment Operators
Assignment Operators

Operator Example Equivalent

+= x += 5; x = x + 5;

-= y -= 2; y = y – 2;

*= z *= 10; z = z * 10;

/= a /= b; a = a / b;

%= c %= 3; c = c % 3;

46
Assignment Operators, Cont.
 Example of assignment operators:
fun main() {
var x = 10
x += 5 // equivalent to x = x + 5
println("x: $x") // Output: x: 15
x *= 2 // equivalent to x = x * 2
println("x: $x") // Output: x: 30
x -= 10 // equivalent to x = x - 10
println("x: $x") // Output: x: 20
x /= 2 // equivalent to x = x / 2
println("x: $x") // Output: x: 10
}

47
KOTLIN
Increment And Decrement Operators
Increment and Decrement Operators

Operator Name Description

Increments 'x' by 1 and evaluates to the new value in 'x'


++x Pre-increment
after the increment.
Evaluates to the original value in 'x' and increments 'x'
x++ Post-increment
by 1.
Decrements 'x' by 1 and evaluates to the new value in
--x Pre-decrement
'x' after the decrement
Evaluates to the original value in 'x' and decrements 'x'
x-- Post-decrement
by 1.

49
Increment and Decrement Operators, Cont.

 Example of increment and decrement operators:


fun main() {
var x = 0
println(“X: ${x++}") // Output: X: 0

println(“X: $x") // Output: X: 1


x--
println(“X: $x") // Output: X: 0

var y = ++x
println(“Y: $y") // Output: Y: 1
}

50
KOTLIN
Comparison Operators
Comparison Operators

Operator Name

== Equal to

!= Not equal to

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

52
Comparison Operators, Cont.
 Example of comparison operators:
fun main() {
val x = 5
val y = 10
println(x == y) // Output: false
println(x < y) // Output: true
println(x >= y) // Output: false
println(x != y) // Output: true
}

53
KOTLIN
Logical Operators
Logical Operators

Operator Name

! Logical NOT

&& Logical AND

|| Logical OR

55
Logical Operators, Cont.
 Example of logical operators:
fun main() {
val a = 10
val b = 20
val c = 30
println((a < b) && (b < c)) // Output: true
println((a < b) && (b > c)) // Output: false
println((a < b) || (b > c)) // Output: true
println(!(a == b)) // Output: true
}

56
KOTLIN
Range Operator
Range Operator

 In Kotlin, a range represents a sequence of values from a starting point to an ending point.

 You can create a range using the ‘..’ operator, which defines an inclusive interval (i.e., both the
start and end values are included).

 The ‘in’ and ‘!in’ operators are used to check whether a value falls within or outside the range.

 A value belongs to the range if it is greater than or equal to the start and less than or equal to the
end.

 Ranges are commonly used in loops and iteration tasks, such as for loops or conditional checks.

58
Range Operator, Cont.
 Example of range operator:
fun main() {
val range = 1..5
println("2 in range is ${2 in range}") // 2 in range is true
val range2 = 5..1
println("2 in range is ${2 in range2}") // 2 in range is false
val range3 = 5 downTo 1
println("2 in range is ${2 in range3}") // 2 in range is true
val range4 = 1 until 8 step 2
val result = [Link](" ") // the joinToString to
concatenate the values into a string
println(result) // Output: 1 3 5 7
}

59
KOTLIN
Bitwise Operators
Bitwise Operators
 Bitwise operators allow you to perform operations directly on the binary representations of integer
values for handling sensitive tasks such as encryption.
 The supported bitwise operators in Kotlin include:
 Bitwise AND (and): & — Sets each bit to 1 if both bits are 1

 Bitwise OR (or): | — Sets each bit to 1 if at least one of the bits is 1

 Bitwise XOR (xor): ^ — Sets each bit to 1 if only one of the bits is 1

 Bitwise Complement (inv()): ~ — Inverts all the bits

 Left Shift (shl): << — Shifts bits to the left, filling with 0s

 Right Shift (shr): >> — Shifts bits to the right, preserving the sign bit

These operators are commonly used with integer types such as Int and Long.

61
Bitwise Operators, Cont.
 Example of bitwise operators:
fun main() {
val x = 5 // Binary: 0101
val y = 3 // Binary: 0011
println(x and y) // Output: 1 (Binary: 0001)
println(x or y) // Output: 7 (Binary: 0111)
println(x xor y) // Output: 6 (Binary: 0110)
println([Link]()) // Output: 10 (Binary: 1010)
println(x shl 1) // Output: 10 (Binary: 1010)
println(x shr 1) // Output: 2 (Binary: 0010)
}

62
KOTLIN
Operators Precedence
Operators Precedence
 Operator precedence defines the order in which operators are evaluated in an expression.

 Below is a simplified list of Kotlin operators, ordered from highest to lowest precedence:

 Postfix Operators: ++, -- (e.g., a++, b--)

 Unary Operators: +, -, !, ++, -- (e.g., -a, !flag, ++count)

 Multiplicative Operators: *, /, % (e.g., a * b, x % y)

 Additive Operators: +, - (e.g., a + b, c - d)

 Range Operator: .. (e.g., 1..10)

 Comparison Operators: <, >, <=, >= (e.g., a < b, x >= y)

 Equality Operators: ==, != (e.g., a == b, x != y)

 Logical AND (Conjunction): && (e.g., a && b)

 Logical OR (Disjunction): || (e.g., a || b)

 Elvis Operator: ?: (e.g., val result = name ?: "Unknown")

 Assignment Operators: =, +=, -=, *=, /=, %= (e.g., a += 1, x = y)

Use parentheses () to group operations and explicitly control evaluation order when needed.

64
Operators Precedence, Cont.
 Example of operator precedence in Kotlin:

fun main() {
val result = 10 + 5 * 2 % 4 // Multiplication has higher
precedence than addition

println(result) // Output: 12
}

65
Questions

66
67

You might also like