Question #159EasyDart Basics

Data types in Kotlin or Java?

Answer

Overview

Kotlin is JetBrains' modern language for Android development (and JVM in general). Java is its predecessor. Both compile to JVM bytecode and interoperate.


Kotlin Data Types

Basic Types

kotlin
// Integer types
val age: Int = 25         // 32-bit
val bigNum: Long = 9_000_000_000L  // 64-bit
val small: Short = 1000   // 16-bit
val byte: Byte = 127      // 8-bit

// Floating point
val price: Double = 9.99  // 64-bit (preferred)
val weight: Float = 70.5f // 32-bit (f suffix)

// Boolean
val isActive: Boolean = true

// Character
val letter: Char = 'A'

// String
val name: String = "Alice"
val multiLine = """
  Hello,
  World!
""".trimIndent()

Collections

kotlin
// Immutable (read-only)
val fruits: List<String> = listOf("apple", "banana", "cherry")
val scores: Map<String, Int> = mapOf("Alice" to 95, "Bob" to 87)
val tags: Set<String> = setOf("kotlin", "android")

// Mutable
val mutableList: MutableList<String> = mutableListOf("a", "b")
val mutableMap: MutableMap<String, Int> = mutableMapOf("x" to 1)
val mutableSet: MutableSet<Int> = mutableSetOf(1, 2, 3)

mutableList.add("c")
mutableMap["y"] = 2

Nullable Types

kotlin
var email: String? = null   // Nullable
var phone: String? = "+91-9876543210"

// Safe call
println(phone?.length)     // Prints length or null

// Elvis operator (?? equivalent)
val display = phone ?: "No phone"

// Smart cast
if (phone != null) {
  println(phone.length)    // Smart cast to String (non-null)
}

Java Data Types

java
// Primitive types (not objects -- lower case)
int age = 25;           // 32-bit integer
long bigNum = 9_000_000_000L;  // 64-bit
float price = 9.99f;    // 32-bit float
double height = 5.11;   // 64-bit float
boolean isActive = true;
char letter = 'A';
byte b = 127;
short s = 256;

// Wrapper classes (Objects -- for collections)
Integer ageObj = 25;    // Autoboxed from int
Double priceObj = 9.99;
Boolean flag = true;

// Collections (use generics -- wrapper types only)
List<Integer> numbers = new ArrayList<>();
Map<String, Integer> scores = new HashMap<>();
Set<String> tags = new HashSet<>();

Kotlin vs Java vs Dart Comparison

ConceptJavaKotlinDart
Integer
text
int
/
text
Integer
text
Int
text
int
Long
text
long
/
text
Long
text
Long
(use
text
int
-- 64-bit)
Float
text
float
/
text
Float
text
Float
(no Float -- use double)
Double
text
double
/
text
Double
text
Double
text
double
Boolean
text
boolean
/
text
Boolean
text
Boolean
text
bool
String
text
String
text
String
text
String
List
text
List<T>
text
List<T>
text
List<T>
Map
text
Map<K,V>
text
Map<K,V>
text
Map<K,V>
NullUnchecked
text
T?
text
T?

Key Difference: Java has primitive types (

text
int
,
text
boolean
) AND wrapper classes (
text
Integer
,
text
Boolean
). Kotlin and Dart only have object types (Kotlin compiles primitives to JVM primitives automatically).