Kotlin Int

Introduction

In Kotlin, the Int class represents a 32-bit signed integer. It is one of the most commonly used data types for numerical values in Kotlin. The Int class provides various methods to perform arithmetic operations, comparisons, and type conversions.

Table of Contents

  1. What is the Int Class?
  2. Creating Int Values
  3. Int Operations
  4. Int Functions
  5. Examples of Int
  6. Real-World Use Case
  7. Conclusion

1. What is the Int Class?

The Int class in Kotlin is a wrapper for the primitive int type. It provides methods and properties to work with 32-bit signed integer values. Integers are used for numerical calculations that do not require fractional components.

Syntax

val myInt: Int = 42

2. Creating Int Values

You can create Int values using literals or by converting other numeric types to Int.

Example

fun main() {
    val a: Int = 42
    val b = 100
    val c = "123".toInt()

    println("a: $a, b: $b, c: $c")
}

3. Int Operations

Kotlin supports various operations on Int values, including arithmetic and comparison operations.

Arithmetic Operations

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulus)

Example

fun main() {
    val a: Int = 10
    val b: Int = 3

    val sum = a + b
    val difference = a - b
    val product = a * b
    val quotient = a / b
    val remainder = a % b

    println("Sum: $sum")
    println("Difference: $difference")
    println("Product: $product")
    println("Quotient: $quotient")
    println("Remainder: $remainder")
}

Comparison Operations

  • == (Equal to)
  • != (Not equal to)
  • < (Less than)
  • > (Greater than)
  • <= (Less than or equal to)
  • >= (Greater than or equal to)

Example

fun main() {
    val a: Int = 10
    val b: Int = 20

    println("a == b: ${a == b}")
    println("a != b: ${a != b}")
    println("a < b: ${a < b}")
    println("a > b: ${a > b}")
    println("a <= b: ${a <= b}")
    println("a >= b: ${a >= b}")
}

4. Int Functions

The Int class provides several useful functions:

  • toByte(): Converts the value to a Byte.
  • toShort(): Converts the value to a Short.
  • toLong(): Converts the value to a Long.
  • toFloat(): Converts the value to a Float.
  • toDouble(): Converts the value to a Double.
  • toString(): Converts the value to a String.
  • compareTo(other: Int): Compares this value with another Int.

Example

fun main() {
    val a: Int = 42

    println("toByte: ${a.toByte()}")
    println("toShort: ${a.toShort()}")
    println("toLong: ${a.toLong()}")
    println("toFloat: ${a.toFloat()}")
    println("toDouble: ${a.toDouble()}")
    println("toString: ${a.toString()}")
    println("compareTo 100: ${a.compareTo(100)}")
}

5. Examples of Int

Example 1: Calculating Factorial

This example demonstrates using Int to calculate the factorial of a number.

fun factorial(n: Int): Int {
    return if (n == 1) n else n * factorial(n - 1)
}

fun main() {
    val num = 5
    val result = factorial(num)
    println("Factorial of $num is $result")
}

Output:

Factorial of 5 is 120

Explanation:
This example calculates the factorial of a given number using recursion.

Example 2: Checking if a Number is Prime

This example demonstrates checking if a number is prime using Int.

fun isPrime(n: Int): Boolean {
    if (n <= 1) return false
    for (i in 2..n / 2) {
        if (n % i == 0) return false
    }
    return true
}

fun main() {
    val num = 29
    if (isPrime(num)) {
        println("$num is a prime number")
    } else {
        println("$num is not a prime number")
    }
}

Output:

29 is a prime number

Explanation:
This example checks if a given number is prime by checking divisibility from 2 to half of the number.

Example 3: Finding GCD of Two Numbers

This example demonstrates finding the greatest common divisor (GCD) of two numbers using Int.

fun gcd(a: Int, b: Int): Int {
    return if (b == 0) a else gcd(b, a % b)
}

fun main() {
    val num1 = 56
    val num2 = 98
    val result = gcd(num1, num2)
    println("GCD of $num1 and $num2 is $result")
}

Output:

GCD of 56 and 98 is 14

Explanation:
This example finds the GCD of two numbers using the Euclidean algorithm.

6. Real-World Use Case: Calculating Monthly Installment

In a real-world scenario, you might need to calculate the monthly installment for a loan using Int.

Example: Calculating Monthly Installment

fun calculateMonthlyInstallment(principal: Int, rate: Float, time: Int): Int {
    val r = rate / 1200
    val emi = (principal * r * Math.pow((1 + r).toDouble(), time.toDouble()) / (Math.pow((1 + r).toDouble(), time.toDouble()) - 1)).toInt()
    return emi
}

fun main() {
    val principal = 500000 // Loan amount in rupees
    val rate = 8.5f // Annual interest rate in percentage
    val time = 240 // Loan tenure in months (20 years)

    val monthlyInstallment = calculateMonthlyInstallment(principal, rate, time)
    println("Monthly Installment: ?$monthlyInstallment")
}

Output:

Monthly Installment: ?4340

Explanation:
This example calculates the monthly instalment for a loan given the principal amount, annual interest rate, and loan tenure.

Conclusion

The Int class in Kotlin provides a way to work with 32-bit signed integer values and perform various operations on them. It offers a range of functions to convert between different numeric types, compare values, and perform arithmetic operations. Understanding how to use the Int class and its functions is essential for effective Kotlin programming, especially when dealing with numerical calculations and logical operations.

Comments