Numbers

5 0 0
                                        

Different types of numbers - kindly check the specification for the upper and lower limit. An error will occur if for example, you declare a double but you set a value of type integer.

1. Byte

2. Short

3. Int - A whole number. For hexadecimals, prefix the value with 0x while binaries with 0b.

4. Long - for this number, just add a suffix L at the end of the values to differentiate with integer.

5. Float - single floating decimal. just add a suffix f on the values.

6. Double - double floating decimal.

Note: 

1. If you null to be included in the values, you have to specify it in the declaration by adding a question mark as suffix in the data type.

================

var x: Long? = 100L

================

2. For explicit conversions of numbers, you can use the predefined functions in the library.

===============

var x: Long = 100L

var y: Int = x.toInt()

================

3. For arithmetic operations, the following is use:

a. Addition (+)

b. Subtraction (-)

c. Multiplication (*)

d. Division (/) - you need to be careful when dividing. The type of numbers should be correct.

===============

fun main(){

     println(checkDivision(5, 2))

}

fun checkDivision(x: Int, y: Int): Double{

     val z = y.toDouble()

     return x/z

}

===============

Result:

2.5

Note: Using Int for both operands and expecting a Double in result would create a mismatch type error. So, variable y was converted to Double for the compiler to infer that it was a Double type.

e. Remainder (%)

4. Bitwise operation is used in Int and Long. Bitwise since decimal is converted to bits and process by the operation specified. I will just give one example.

===============

fun main(){

     println(processedBits(5, 2))

}

fun processedBits(x: Int, y: Int): Int{

     return x shr y

}

=============== 

Result:

1

Note: 5 in binary is 0b0000 0101. The shr means signed shift right. The 2 means it needs to shift all one's and zero's to the right by 2. So, the x now has 0b0000 0001. All one's that has been shifted will be remove. So, if you convert the x now

============

128 - 64 - 32 - 16 - 8 - 4 - 2 - 1

     0  -  0   -  0  -  0 - 0 - 0 - 0 - 1

============

The equivalent of one's and zero's is on top. So, the answer is one.

5. Comparison operators like == or != and so on is the same in java. But kotlin added one which is range(..). Range uses two dots as a symbol. Like saying letters from a to z is a..z using range. You can use the operator in to test if the value is within range. The in keyword is an operator and not just a keyword. Meaning it functions like the arithmetic operators.

================

fun main(){

     println(checkIfInRange(2, 5))

}

fun checkIfInRange(x: Int, y: Int): Boolean{

     return x in 0..y

}

================

Result:

true

Kotlin ProgrammingWhere stories live. Discover now