1. Kotlin/JVM and the Java standard library: what is actually happening
When you write Kotlin code for a “regular” console application, you are almost certainly writing Kotlin/JVM: your code compiles to bytecode and runs on the JVM (Java Virtual Machine). That means that next to your code there is always the JDK (Java Development Kit) with the standard packages java.*: strings, collections, system functions, UUID, and a lot more. In essence, Kotlin does not “replace” the Java world—it lives pragmatically alongside it and calmly uses ready-made tools from the JDK.
So you do not get scared by the scale, remember a simple idea: the Java API for Kotlin is just “another library”, only very large and already installed almost everywhere there is a JVM.
The Java API in Kotlin looks “normal”: dot, parentheses, and no rituals
If you expect that to call Java code you need to open a portal to hell, recite a spell, and sacrifice a couple of parentheses—you will be pleasantly disappointed. In Kotlin, calling the Java API looks as everyday as it gets: create an object via a “type call” and call methods via a dot.
It helps to build intuition: a Java class is just a type you can import, instantiate via a constructor, and use like any other object. A Java method is just a method: obj.method(...). And a Java “static method” is simply a call through the class name: Type.staticMethod(...). Yes, it is that boring—and that is the point.
2. Packages and import: how Kotlin finds Java classes
When a project is small, you want to write “short and without extra words”. But the compiler is not telepathic: if you use the class UUID, it needs to know which UUID (from which package) you mean. So we have two main ways to refer to a Java type: via import or via a fully qualified name.
Think of it like an address: a package is like a “street”, a class is like a “house”. If you did not write import, you can “walk there” by the full address: java.util.UUID. And if you wrote import, then you can talk briefly afterwards: UUID. This is the same principle you have already used with your own functions and packages—only now packages start with java..
Method #1: fully qualified name
A fully qualified name is convenient when you are making a tiny example, trying something in a sandbox, or just do not want to clutter the file with imports yet. This especially helps beginners: you see the entire path and you connect “class → package” in your head faster.
fun main() {
val id = java.util.UUID.randomUUID().toString()
println(id) // for example: 6c6f3a7a-0a51-4b4e-9a61-1dbd7c2f0fb2
}
Here java.util.UUID is a Java class from the JDK. The method randomUUID() is “static” (called through the class name), and toString() converts the UUID to a string.
Method #2: import
import makes code cleaner and shorter, especially when a class is used many times. In normal projects this is the main approach: you import the types you need and calmly work with short names.
import java.util.UUID
fun main() {
val id = UUID.randomUUID().toString()
println(id) // for example: 1c0d6e2a-9d0d-4e1a-9e84-63aaf1c30a24
}
If IntelliJ IDEA highlights UUID in red, it usually means one of two things: either you forgot import, or you misspelled the name.
3. Constructors and Java static methods: basic practice
When you see a Java class, you do not need to think “this is different”. In Kotlin, creating an object via a constructor looks like calling a function: Type(...). This applies to Kotlin classes (later in the course) and to Java classes (already now). The good news: the syntax is exactly the same.
It is only important to remember that many Java objects by style are mutable: you create an object and then “add to it” via methods like add, append, put, and so on. Kotlin can do this too (for example, MutableList), but today it is especially noticeable.
Example: StringBuilder() as a Java class
You may have already seen StringBuilder as a tool for assembling long strings. On the JVM it is a class from the Java world, and Kotlin works with it without any issues.
fun main() {
val sb = StringBuilder()
sb.append("Kotlin ")
sb.append("and Java are friends.")
println(sb.toString()) // Kotlin and Java are friends.
}
Notice the style: append mutates the sb object “in place”. This is normal and expected for the Java API.
Java static methods: call through the type name
In Java there is the concept of static: a method belongs not to a specific object but to the class itself. Kotlin in the general case does not force you to think of static as a separate entity: you simply call the method via the type name—and that is it.
Why does this matter? Because many utilities in the JDK are built exactly like this: System.getenv(...), System.getProperty(...), UUID.randomUUID(), etc. This is a very common pattern in real applications: “give system information”, “generate an identifier”, “get current settings”.
Example: System.getProperty(...) — learn something about the environment
System is a Java class that helps communicate with the outside world (operating system, JVM properties, environment). For a CLI program this is useful at least for a friendly “hello, user”.
fun main() {
val user = System.getProperty("user.name")
println("Hello, $user!") // Hello, alex!
}
There are many properties. Two commonly used ones: "user.name" and "user.dir" (the process working directory). We are not talking about files today, but the directory as a string can already be useful for diagnostics.
Mini table: “static” vs “regular” method
To stop your brain from getting confused, it helps to keep a table like this in mind:
| What we do | How it looks | Example |
|---|---|---|
| Call a method through the class | |
|
| Create an object | |
|
| Call a method through an object | |
|
This scheme is simple, but it covers 80% of “why does this not compile?!” when you are getting started.
4. Java collections: ArrayList and “mutation is normal”
By this point you are already confidently using Kotlin collections (List, MutableList, Map), and that is great. But on the JVM there is a huge layer of code and libraries that use Java collections: ArrayList, HashMap, HashSet, etc. Kotlin can work with them directly. Moreover, on the JVM this is so common that sometimes you will not even notice where Kotlin ends and Java begins.
The key practical difference for a beginner: Java collections by design are mostly mutable, and that is considered normal. So the add method will mutate the list instead of returning a new one.
Example: create an ArrayList and add elements
import java.util.ArrayList
fun main() {
val xs = ArrayList<Int>()
xs.add(10)
xs.add(20)
println(xs.size) // 2
}
Compare this to the Kotlin style listOf(10, 20): there the list is read-only (by reference), while here it is “alive” and mutable.
Why touch Java collections at all if there are Kotlin collections?
In this lecture we will not dive into compatibility details (it is a separate big topic). But the practical reason is simple: a huge amount of APIs in the JVM world historically accept and return Java collections. And if you want to use libraries confidently, you need to at least not be afraid of ArrayList.
5. Mini project: “Text Analyzer” grows up
Up to today we were writing fairly autonomous programs: input text → count → print a report. Today we will take a small but very “real” step: we will add service information to the report—the kind of information you usually want to see in logs and reports. For example: a run identifier, the user name, and the working directory. All of this will be provided by the Java API from the JDK—for free, without dependencies, and without magic.
To connect the examples into a single whole, we will assume that we already have a simplified text analyzer (in the style of lectures about pipelines): tokenization, frequency counting, printing top-N.
Generate a run ID via UUID.randomUUID()
In long scenarios it is useful to be able to say: “This report corresponds to a specific run of the program.” Especially if a user sends you a screenshot or a piece of a log. A UUID is just a unique string that is easy to generate and almost impossible to repeat by accident.
Let us make a function newRunId() that returns a string. Inside we use the Java class UUID and its static method.
import java.util.UUID
fun newRunId(): String {
return UUID.randomUUID().toString()
}
fun main() {
println(newRunId()) // for example: 9a9dbb6c-2c92-40bb-9c5c-2ee7d4c8d77b
}
We are not discussing “why it is designed this way” yet—we care about something else: you saw that a Java static method in Kotlin is called completely naturally.
Get environment info via System.getProperty(...)
When a program runs on different machines, sometimes you want to understand: “Where am I even working?”. This is especially relevant when the user says “it does not work for me” and you say “it works for me”. Simple system properties help you at least start the conversation concretely: which user, which run directory.
Let us make a small function that collects a couple of values.
fun runtimeInfo(): String {
val user = System.getProperty("user.name")
val dir = System.getProperty("user.dir")
return "user=$user, dir=$dir"
}
fun main() {
println(runtimeInfo()) // user=alex, dir=/Users/alex/projects/analyzer
}
There is still nothing “Kotlin-specific” here: these are regular Java API calls and regular Kotlin strings.
Build the report header using StringBuilder
When you print a report to the console, you quickly want to format multi-line text nicely: a header, metadata, and then the analysis result. String concatenation with + works, but for large text it is easier and clearer to assemble everything in a StringBuilder and return the finished string. This is a classic approach on the JVM (and yes, it is a Java class).
Let us make a function buildHeader(...) that returns a multi-line header.
fun buildHeader(runId: String, info: String): String {
val sb = StringBuilder()
sb.appendLine("=== Text Analyzer Report ===")
sb.appendLine("runId: $runId")
sb.appendLine("env: $info")
return sb.toString()
}
The appendLine method adds a line plus a newline. If you do not have it (depending on the environment), you can replace it with append("...\n"); the idea is the same.
Where import is not needed—and why that is normal
Beginners are often confused by the fact that we import some Java things and not others. For example, we did not import System. That is not because “we felt like it”, but because on the JVM some packages are included automatically (in particular, java.lang). But at the practical level the rule is simple: if the compiler cannot resolve a name, add import (or temporarily write the fully qualified class name) and move on.
As practice, you can rewrite System.getProperty as java.lang.System.getProperty yourself—it will work the same way.
Use Java ArrayList as a “string buffer” before the final output
Sometimes it is convenient to build a report not as one string, but as a list of strings: add a line, then join. This “buffering” approach shows up everywhere in older Java code. We will do it on purpose so you feel the Java API style: create a mutable structure, fill it, then transform it.
import java.util.ArrayList
fun buildLines(): ArrayList<String> {
val lines = ArrayList<String>()
lines.add("line 1")
lines.add("line 2")
return lines
}
fun main() {
println(buildLines().size) // 2
}
The point is not that this is “better than Kotlin”. The point is that this is often the case in the APIs you will run into, and you need to feel confident.
Put it all together: a mini main for our analyzer
Now we will glue the ideas into one small scenario: generate a runId, get runtimeInfo, print the header, then read a line of text and print its length (as the simplest “analysis stub”). We will not re-implement tokenization and frequencies—they are already in your project from previous days.
import java.util.UUID
fun main() {
val runId = UUID.randomUUID().toString()
val info = runtimeInfo()
println(buildHeader(runId, info))
val text = readln()
println("chars: ${text.length}") // chars: 12
}
If you are thinking right now, “Wait, runtimeInfo() and buildHeader() are somewhere above, but they are not here”—that is correct: this is one project; the functions are just in the same file or imported from another one. We keep evolving the application step by step, just like we did before.
6. Diagram: Kotlin → JVM → JDK
After the first encounters with the Java API, it can feel like Kotlin “suddenly became Java”. In reality, it simply stands on the shoulders of the JVM and uses the JDK as the standard toolbox. It is convenient to imagine this as a simple block diagram: you write Kotlin, it compiles, and at runtime the JDK classes are right there, and you call them freely.
flowchart TD
A[Kotlin code] --> B[Kotlin compiler]
B --> C[JVM bytecode]
C --> D[JVM]
D --> E[JDK / java.* classes]
D --> F[Your application: text analyzer]
E --> F
This diagram matters psychologically: you do not “connect Java separately”. You are already inside the JVM world—you have just started consciously taking useful things from it.
7. Common mistakes when calling the Java API from Kotlin
Mistake #1: you forgot import and decided “Kotlin does not have that class”.
Most often the class exists; the compiler just does not know where to get it. If you see Unresolved reference, try writing the fully qualified name first (java.util.UUID), then press Alt+Enter in the IDE and add import. This is the fastest way to stop guessing and start moving.
Mistake #2: you mixed up calling a static method and an instance method.
If you write UUID.toString() and expect a string, the compiler will not be happy: toString() is an instance method, not a class method. The correct chain is: first get an object (for example, UUID.randomUUID()), then call its method (.toString()).
Mistake #3: you expect Java collections to “behave like a read-only List”.
If you created an ArrayList and passed it somewhere, other code can mutate it—and that is not a bug; it is the Java style. In practice this means you need to be more careful about mutability with Java objects: if you need a snapshot of data, you typically make a copy (for now, it is enough to understand the problem).
Mistake #4: you try to “fix” the problem by copy-pasting the fully qualified name everywhere.
Fully qualified names are convenient for a one-off example, but they turn real code into a wall of text. If you use a class more than once, it is better to honestly add import. The code becomes shorter, and you start seeing the program logic instead of house addresses on java.util street.
Mistake #5: you think the Java API “is not for Kotlin” and avoid it even where it simplifies your life.
Paradoxically, sometimes a beginner does not want to touch System or UUID on principle, because “that is Java”. On the JVM this is not “foreign”; it is the standard library of the runtime environment. If a task is solved more easily via the JDK—use the JDK and do not torture yourself (and the future reader of your code).
GO TO FULL VERSION