Kotlin Short

Introduction

In Kotlin, the Short class represents a 16-bit signed integer. It is used for numerical values that require less range than the Int class but more than the Byte class. The Short class provides various methods to perform arithmetic operations, comparisons, and type conversions.

Table of Contents

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

1. What is the Short Class?

The Short class in Kotlin is a wrapper for the primitive short type. It provides methods and properties to work with 16-bit signed integer values. Short integers are used for numerical calculations that require a smaller range than Int.

Syntax

val myShort: Short = 42

2. Creating Short Values

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

Example

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

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

3. Short Operations

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

Arithmetic Operations

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

Example

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

    val sum = (a + b).toShort()
    val difference = (a - b).toShort()
    val product = (a * b).toShort()
    val quotient = (a / b).toShort()
    val remainder = (a % b).toShort()

    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: Short = 10
    val b: Short = 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. Short Functions

The Short class provides several useful functions:

  • toByte(): Converts the value to a Byte.
  • toShort(): Converts the value to a Short.
  • toInt(): Converts the value to an Int.
  • 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: Short): Compares this value with another Short.

Example

fun main() {
    val a: Short = 42

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

5. Examples of Short

Example 1: Calculating Factorial

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

fun factorial(n: Short): Short {
    return if (n == 1.toShort()) n else (n * factorial((n - 1).toShort())).toShort()
}

fun main() {
    val num: Short = 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 with Short values.

Example 2: Checking if a Number is Prime

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

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

fun main() {
    val num: Short = 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 using Short values.

Example 3: Calculating the Power of a Number

This example demonstrates calculating the power of a number using Short.

fun power(base: Short, exponent: Short): Short {
    if (exponent == 0.toShort()) return 1.toShort()
    var result: Short = 1
    for (i in 1..exponent) {
        result = (result * base).toShort()
    }
    return result
}

fun main() {
    val base: Short = 5
    val exponent: Short = 3
    val result = power(base, exponent)
    println("$base^$exponent is $result")
}

Output:

5^3 is 125

Explanation:
This example calculates the power of a number using a loop with Short values.

6. Real-World Use Case: Calculating Simple Interest

In a real-world scenario, you might need to calculate the simple interest for a loan using Short.

Example: Calculating Simple Interest

fun calculateSimpleInterest(principal: Short, rate: Float, time: Short): Float {
    return (principal * rate * time / 100).toFloat()
}

fun main() {
    val principal: Short = 10000 // Principal amount in rupees
    val rate: Float = 5.0f // Annual interest rate in percentage
    val time: Short = 2 // Loan period in years

    val simpleInterest = calculateSimpleInterest(principal, rate, time)
    println("Simple Interest: ?$simpleInterest")
}

Output:

Simple Interest: ?1000.0

Explanation:
This example calculates the simple interest for a loan given the principal amount, annual interest rate, and loan period using Short values.

Conclusion

The Short class in Kotlin provides a way to work with 16-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 Short class and its functions is essential for effective Kotlin programming, especially when dealing with numerical calculations that require a smaller range than Int.

Comments