kotlin.math
packageBoolean
. There are only two possible values of this type: true and false.Char
. A value of this type takes up two bytes of storage and represents a 16-bit Unicode character.Byte
, Short
, Int
, and Long
. A Byte value takes up one byte of storage; a Short value takes up two bytes of storage; an Int value takes up four bytes of storage; and a Long value takes up eight bytes of storage.Float
and Double
. A Float value takes up four bytes of storage, while a Double value takes up eight bytes of storage.wrapper type
!0b1100
12
0xC
There are two kinds of type that an integer literal can have, either Int
or Long
. Kotlin chooses the smallest type that can contain the value. It is an error if the intended integer value of what you write is too large to fit in a Long
. Examples:
>>> 12345678232323291110
error: the value is out of range
12345678232323291110
^
>>> 1234567890
res1: kotlin.Int = 1234567890
>>> 1234567823232329111
res2: kotlin.Long = 1234567823232329111
An Int
literal can be assigned to a Byte
or Short
variable without getting a compile-time error if the value is within range. Examples:
>>> val a: Byte = 256
error: the integer literal does not conform to the expected type Byte
val a: Byte = 256
^
>>> val a: Byte = -128
>>> a
res1: kotlin.Byte = -128
An integer literal can be forced to have type Long
by appending the suffix L
, e.g., -1L
has a Long
type.
>>> val a = -1L
>>> a
res0: kotlin.Long = -1
3.134
2.1e10
, 3e-7
Double
by default.Float
literal, add a suffix ‘f’ or ‘F’. E.g. 3.14F
has a Float
type.One cannot write an overflowing floating-point literal because any floating-point literal that overflows becomes Infinity
or -Infinity
. Also, floating-point numbers cannot be represented precisely. Examples:
>>> 1.2e1111
res0: kotlin.Double = Infinity
>>> -1.2e1111
res1: kotlin.Double = -Infinity
>>> 1.2e-1111
res2: kotlin.Double = 0.0
u
followed by four hex digits specifying a unicode character.Escape Sequence | Unicode | Meaning |
---|---|---|
‘\b’ | ‘\u0008’ | backspace |
‘\t’ | ‘\u0009’ | horizontal tab |
‘\n’ | ‘\u000a’ | linefeed |
‘\r’ | ‘\u000d’ | carriage return |
‘\"’ | ‘\u0022’ | double quotation mark |
‘\'’ | ‘\u0027’ | single quotation mark |
‘\$’ | ‘\u0024’ | dollar sign |
‘\\’ | ‘\u005c’ | backslash |
2+3*4
is actually ambiguous, i.e., it has more than one possible interpretation, and thus meaning. In one interpretation the +
is done before *
; In the other interpretation the +
is done after *
.2+3*4
, multiplication is performed before addition since the * operator has higher precedence than +.1-3-4
will be parsed by the Kotlin compiler as if we had written (1-3)-4
due to the fact that the minus operator is left-associative.Type | Size in Bits | Sample Operators | Literals |
---|---|---|---|
Boolean | unspecified | && || ! | true false |
Byte | 8 | + \(-\) * / % | |
Char | 16 | + | ‘a’ ‘0’ ‘\\’ |
Short | 16 | + \(-\) * / % | |
Int | 32 | + \(-\) * / % | 321 0x3A 0b11 |
Long | 64 | + \(-\) * / % | 3L |
Float | 32 | + \(-\) * / % | 2F 14.2e23f |
Double | 64 | + \(-\) * / % | 3.21 14.2e23 |
String | + | “Hello” | |
Array | [] |
Here is a list of the hard keywords
as as? break class continue do else false for fun
if in !in interface is !is null object package return
super this throw true try typealias val var when while
There are other kinds of keywords. We may encounter some of them later.
ticketNumber
BigInteger
MAX_LINE_LENGTH
An assignment statement starts with name of the variable, followed by the = symbol, followed by an expression. E.g.
a = 2 * b + 6
Thus, the variable name appearing on the LHS denotes memory location while any variable name appearing on the RHS denotes value.
val
.Example declaration and usage:
val c: Char = 'A'
val digit: Char = '9'
val greeting: String = "Hi"
val person: String = "Alice"
println(greeting + " " + person)
var
.Example declaration, usage, and reassignment:
var n: Int = 1
var f: Float = 0F
var d: Double = 2.1
f = f * 3.1F
d = 3e-2
var greet : String = "Hello!"
greet = "Hi"
The simplest kind of expression consists of literals, variables, and function calls joined together by operators.
b * 2 / 3 + kotlin.math.sin(4.0)
There are other kinds of expressions. We’ll come to them soon.
In an arithmetic expression involving mixed types of numeric operands, Kotlin has overloaded the operators so it seems as if to convert the values in the following direction to make both operands have the same type as the “biggest” type.
Byte → Short → Int → Long → Float → Double
Examples:
3 + 4.2 // value: 7.2, type: Double
1 + 7L - 2 // value: 6L, type: Long
The user can also explicitly requests the compiler to convert a value of one type into another type. E.g.
val a: Int = 2
val b: Byte = (a + 3).toByte()
val s: Short = 4.toShort()
toBoolean()
toChar()
toByte()
toShort()
toInt()
toLong()
toFloat()
toDouble()
toString()
Example usage:
"TrUe".toBoolean() ⇒ true
66.toChar() ⇒ 'B'
25.toByte() ⇒ a Byte type with value of twenty-five
265.toByte() ⇒ a Byte type with value of nine
print()
— outputs its argument.println()
— outputs its argument and a newline, and flushes the output buffer.print()
and println()
functions take exactly one argument. Their argument can be of any type, and it is automatically converted to the String type (if necessary) before being output.abs
— for Double, Float, Int, and Longmin
, max
— for Double, Float, Int, and Longfloor
, ceil
, round
, truncate
— for Double and Floatsin
, cos
, tan
— for Double and Floatexp
, ln
, log10
, log2
, log
— for Double and Floatpow
— for Double and Floatsqrt
— for Double and FloatroundToInt
, roundToLong
— for Double and FloatE
— the famous \(e\) (the base of natural logarithm)PI
— \(\pi\) (the circle constant: circumference \(\div\) diameter)When a java class starts running, it also receives command line arguments as an array of strings. For example, when you type
$ java MyClass zero ein deux
MyClass
gets its zeroth argument args[0]
as the string “zero”, its first argument args[1]
as the string “ein”, and its second argument args[2]
as the string “deux”.exitProcess()
function. This function takes an integer argument and returns that value to denote the success or failure result of running the program.The exitProcess()
function belongs to the kotlin.system
package, which is not automatically loaded in by default. Therefore, you should include the line
import kotlin.system.exitProcess
exitProcess()
.Another way to do error checking is to use the try {...} catch {...}
statement. This involves exception, a concept we’ll study later.
Kotlin provides pseudo-random number generators in the kotlin.random
package. To use this package, you include the line
import kotlin.random.*
You call a function to generate a random number through the Random
object. These functions include nextBoolean()
, nextInt()
, nextLong()
, nextFloat()
, nextDouble()
.
/*
* This program demonstrates how to process command line arguments, and shows
* how to call some random number generating functions.
* See
*
* https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.random/-random/index.html
*
* for all possibilities.
*/
import kotlin.system.exitProcess
import kotlin.random.*
fun main(args: Array<String>) {
val lo: Int
val hi: Int
if (args.size != 2) {
println("Please give me exactly two nonnegative integers as arguments.")
exitProcess(1)
}
try {
lo = args[0].toInt()
}
catch (e: NumberFormatException) {
println("'${args[0]}' is not an integer.")
exitProcess(2)
}
try {
hi = args[1].toInt()
}
catch (e: NumberFormatException) {
println("'${args[1]}' is not an integer.")
exitProcess(2)
}
if (lo < 0 || lo > hi) {
println("Please give me 2 nonnegative integers lo and hi, with lo <= hi.")
exitProcess(3)
}
// a pseudo-random integer
var k = Random.nextInt()
println("Your random integer is: $k")
// a pseudo-random integer between 0 and hi-1
k = Random.nextInt(hi)
println("Your random integer between 0 and ${hi-1} inclusive is: $k")
// a pseudo-random integer between lo and hi
k = Random.nextInt(lo..hi)
println("Your random integer between $lo and $hi inclusive is: $k")
// a pseudo-random real between 0.0 and 1.0
val r = Random.nextDouble()
println("Your random real number in [0, 1) is: $r")
}