Home [Kotlin] Basic types
Post
Cancel

[Kotlin] Basic types

[Kotlin] Basic types

1. Numbers

  • 숫자형은 정수 (integers)소수 (fractional)로 크게 나뉜다.

Integer numbers

  • …, -1, 0, 1, …
  • 4가지 타입 : Long, Int, Short, Byte (큰 수부터 작은 순서대로)
  • 각각의 타입은 다른 크기와 다른 범위의 값들을 표현할 수 있다.
  • 정수 타입의 범위는 \(-2^{n-1} \sim 2^{n-1} - 1\) (where n is the number of bits)
    • Byte
      • size 8 bits (1 byte)
      • \[-128 \sim 127\]
    • Short
      • size 16 bits (2 byte)
      • \[-32768 \sim 32767\]
    • Int
      • size 32 bits (4 byte)
      • \[-2^{31} \sim 2^{31} - 1\]
    • Long
      • size 64 bits (8 byte)
      • \[-2^{63} \sim 2^{63} - 1\]
1
2
3
4
5
6
7
8
9
10
val zero = 0 // Int
val one = 1  // Int
val oneMillion = 1_000_000  // Int

val twoMillion = 2_000_000L // Long, because it is tagged with L
val bigNumber = 1_000_000_000_000_000 // Long, Kotlin automatically choose it (Int is too small)
val ten: Long // Long, because the type is specified

val shortNumber: Short = 15 // Short, because the type is specified
val byteNumber: Byte = 15   // Byte, because the type is specified

Floating-point types

  • Float (32 bits)
  • Double (64 bits)
1
2
3
val pi = 3.1415  // Double
val e = 2.71828f // Float, because it is tagged with f
val fraction: Float = 1.51 // Float, because the type is specified

MIN_VALUE and MAX_VALUE

1
2
3
4
5
6
7
8
9
// To display the maximum and minimum value of a numeric type (including Double and Float)

println(Int.MIN_VALUE)  // -2147483648
println(Int.MAX_VALUE)  // 2147483647
println(Long.MIN_VALUE) // -9223372036854775808
println(Long.MAX_VALUE) // 9223372036854775807

println(Int.SIZE_BYTES) // 4
println(Int.SIZE_BITS)  // 32

2. Characters

  • Each character is just a single letter enclosed in single quotes.
  • Short 타입과 크기가 같다. (2 bytes = 16 bits)
1
2
3
4
5
val lowerCaseLetter = 'a'
val upperCaseLetter = 'Q'
val number = '1'
val space = ' '
val dollar = '$'

3. Booleans

  • Boolean 은 오직 true 아니면 false 만 보관할 수 있다.
  • It represents only one bit of information, but its size is not precisely defined.
1
2
val enabled = true
val bugFound = false

4. Strings

  • A sequence of characters enclosed in double quotes.
1
2
val creditCardNumber = "1234 5678 9012 3456"
val message = "Learn Kotlin instead of Java."

References

This post is licensed under CC BY 4.0 by the author.

[Kotlin] Data types

여러 개의 Github 계정을 한 곳에서 동시에 사용하기