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
kotlinvar 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
| Concept | Java | Kotlin | Dart |
|---|---|---|---|
| Integer | text text | text | text |
| Long | text text | text | (use text |
| Float | text text | text | (no Float -- use double) |
| Double | text text | text | text |
| Boolean | text text | text | text |
| String | text | text | text |
| List | text | text | text |
| Map | text | text | text |
| Null | Unchecked | text | text |
Key Difference: Java has primitive types (
,textint) AND wrapper classes (textboolean,textInteger). Kotlin and Dart only have object types (Kotlin compiles primitives to JVM primitives automatically).textBoolean