CodeGym /행동 /Kotlin SELF /Program execution: args, environment variables, and worki...

Program execution: args, environment variables, and working directory

Kotlin SELF
레벨 17, 레슨 3
사용 가능

1. “Running a program” means: code + environment

When you press the Run button in an IDE or start a program from a terminal, it feels like something simple happens: “execute main”. But in practice, execution almost always includes external parameters. A program can start with command-line arguments, with environment variables, in a specific working directory — and all of that affects the behavior even of the simplest application.

Imagine you wrote the “Guess the Number” game (we already did it earlier). It has settings: the number range and the number of attempts. You can “hardcode” them in the code, and it will work. But as soon as you want to quickly change the range without rewriting the program, a question appears: “How do I pass settings at startup?”. Today we will learn to do exactly that in a grown-up way — but without pain.

To avoid drifting across topics, we will keep in mind a training app GuessNumberApp: the “Guess the Number” game, which can now be configured at launch.

2. Command-line arguments: main(args: Array<String>)

When a program starts, the operating system (and/or the launcher) may pass it a list of strings — arguments. In Kotlin, there is a form of main that accepts an array of strings: fun main(args: Array<String>). This is the officially supported “second form” of the entry point.

It is important to catch the key point right away: arguments are always strings. Even if you passed 10, inside the program it is "10", and if you need a number — you must parse it, which means errors are possible.

First contact: just print the arguments

First, let’s do what any developer does in an unclear situation: print what actually arrived.

package app

fun main(args: Array<String>) {
    println("Args count = ${args.size}")            // e.g.: Args count = 2
    println("Args = ${args.contentToString()}")     // e.g.: Args = [100, 7]
}

Here args.size is the number of arguments, and contentToString() helps print the array nicely.
If you run without arguments, size will be 0, and that is fine: the program should not be offended at the world for not passing it anything.

Why you should not immediately do args[0]

Because args can be empty. Then indexing will lead to an array-out-of-bounds error. And this is the case where the program will crash before it can say: “Hey, user, you forgot the arguments.”

So the rule is simple: check first args.size, then read args[i].

package app

fun main(args: Array<String>) {
    if (args.size == 0) {
        println("No args. Running with defaults.")  // No args. Running with defaults.
        return
    }

    println("First arg = ${args[0]}")               // e.g.: First arg = 100
}

Note: we do not use anything “magical”. Just if and indices — you already know this.

Parsing arguments: “raw strings → preparation → parsing”

Command-line arguments are a classic example of “dirty input”. It is easy to forget them, easy to mix up the order, easy to pass “one hundred” instead of 100. So we apply a familiar pattern: read a string → prepare → try to parse → handle null.

Simple scheme: max and attempts by position

Let’s agree on this:
args[0] — upper bound (max)
args[1] — number of attempts (attempts)

Let’s do the parsing carefully:

package app

fun main(args: Array<String>) {
    val maxRaw = if (args.size > 0) args[0] else null
    val attemptsRaw = if (args.size > 1) args[1] else null

    val max = maxRaw?.trim()?.toIntOrNull() ?: 100
    val attempts = attemptsRaw?.trim()?.toIntOrNull() ?: 7

    println("max=$max attempts=$attempts")          // e.g.: max=100 attempts=7
}

Three things matter here.

First, trim() saves you from accidental spaces (yes, they can be passed “by accident”, especially in some shells or when copy-pasting).
Second, toIntOrNull() does not throw an exception; it returns null if the string is not a number.
Third, the Elvis operator ?: provides default values. This makes the program “resilient”: even if the arguments are malformed, it still starts.

Connecting parameters to the application

Assume that somewhere in your project you already have the game function (we are not rewriting the whole game — we are learning to run it with parameters):

package app

fun runGuessNumberGame(max: Int, attempts: Int) {
    println("Game started: max=$max, attempts=$attempts")
    // Game logic would be here; you already wrote it earlier
}

Now main becomes the “front door”: it reads the launch environment and passes clean parameters into the logic.

package app

fun main(args: Array<String>) {
    val maxRaw = if (args.size > 0) args[0] else null
    val attemptsRaw = if (args.size > 1) args[1] else null

    val max = maxRaw?.trim()?.toIntOrNull() ?: 100
    val attempts = attemptsRaw?.trim()?.toIntOrNull() ?: 7

    runGuessNumberGame(max, attempts)
}

This is an important architectural feeling: main is where you “glue” the external world and your program together. The logic itself (functions) should receive already-normal values.

3. Environment variables: System.getenv

Arguments are convenient when there are few parameters and you change them “on the fly” often. But there is another channel: environment variables. These are KEY=VALUE pairs that the system passes to the process at startup. In everyday terms, this looks like “settings next to the launch” that you do not have to type on the command line every time.

On Kotlin/JVM, environment variables are read via System.getenv("NAME"). And there is a nuance that fits perfectly with null-safety: if the variable does not exist, you will get null.

Minimal example: read and diagnose

package app

fun main() {
    val raw = System.getenv("GUESS_MAX")
    println("GUESS_MAX = $raw") // e.g.: GUESS_MAX = 200 (or: GUESS_MAX = null)
}

If you see null — it is not an error. It simply means: “the variable is not set”.

Safely parse a number from an env variable

Do the same as with arguments: normalization → parsing → default.

package app

fun main() {
    val max = System.getenv("GUESS_MAX")
        ?.trim()
        ?.toIntOrNull()
        ?: 100

    println("max=$max") // e.g.: max=100
}

This is a very “Kotlin-ish” style: a chain of ?. reads as “if the value exists — process it, otherwise do not touch it”.

Source priority: args over env, env over default

In real applications, this logic is common:

1) if the user explicitly passed an argument — respect it;
2) otherwise check the environment variable;
3) otherwise use the default.

Let’s implement this without introducing any new scary concepts. We will create a helper function that resolves max.

package app

fun resolveMax(args: Array<String>): Int {
    val fromArgs = if (args.size > 0) args[0].trim().toIntOrNull() else null
    if (fromArgs != null) return fromArgs

    val fromEnv = System.getenv("GUESS_MAX")?.trim()?.toIntOrNull()
    if (fromEnv != null) return fromEnv

    return 100
}

And use it in main:

package app

fun main(args: Array<String>) {
    val max = resolveMax(args)
    println("Resolved max = $max") // e.g.: Resolved max = 150
}

Why is this convenient? Because you “packaged” the selection policy into a single function. main does not turn into a long sheet of ifs.

4. Working directory: System.getProperty("user.dir")

The working directory is the folder relative to which relative paths are interpreted. Even if you are not working with files yet, it is worth understanding this concept now, because it regularly shows up as “it works on my computer, but not on my friend’s”.

On the JVM, it is often convenient to read the working directory like this: System.getProperty("user.dir"). This is not “Kotlin magic”; it is just access to platform properties, and we use System.* as a ready-made tool without diving into how the JVM implements it.

Print the working directory for diagnostics

package app

fun main() {
    val dir = System.getProperty("user.dir")
    println("Working directory: $dir") // e.g.: Working directory: /Users/alice/projects/guess
}

If you run from an IDE, the working directory will often (but not always) be the project root. If you run from a terminal, it is usually equal to “the current terminal folder”.

Thought experiment: relative paths are “anchored” to "user.dir"

We are not touching files yet (that will be on other days), but we can demonstrate with strings: imagine you want to access "data/config.txt". A relative path can be “mentally” turned into an absolute one by concatenating it with the working directory.

package app

fun main() {
    val dir = System.getProperty("user.dir")
    val relative = "data/config.txt"
    val full = "$dir/$relative"

    println(full) // e.g.: /Users/alice/projects/guess/data/config.txt
}

Yes, this is not a universal way to work with paths (there are dedicated APIs for that), but as an illustration of the idea it is great: the working directory defines the “reference point”.

5. Settings sources scheme and a mini refactor

Now we have three sources of “external data at startup”: arguments, environment variables, and (as a last resort) defaults in code. Sometimes people also add interactive input readln(), but that is “during execution”, not “startup parameters”.

It is handy to think of it as a small pipeline:

flowchart TD
    A[Program start] --> B{Are there args?}
    B -->|yes| C[Parse args: String -> Int?]
    B -->|no| D{Is there env?}
    D -->|yes| E[Parse env: String -> Int?]
    D -->|no| F[Use default]
    C --> G["Run logic: runGuessNumberGame(...)"]
    E --> G
    F --> G

And this is a truly “grown-up” habit: do not mix the game/app logic with the logic of reading launch parameters.

When a program is started not from an IDE but somewhere else, it is useful to quickly understand: “What did it decide?”. So people often add small diagnostics: print parameters, where they were taken from, what the working directory is. We will do it neatly, with short functions, without overcomplication.

A function for attempts with the same priority

package app

fun resolveAttempts(args: Array<String>): Int {
    val fromArgs = if (args.size > 1) args[1].trim().toIntOrNull() else null
    if (fromArgs != null) return fromArgs

    val fromEnv = System.getenv("GUESS_ATTEMPTS")?.trim()?.toIntOrNull()
    if (fromEnv != null) return fromEnv

    return 7
}

Assemble a compact main

package app

fun main(args: Array<String>) {
    val max = resolveMax(args)
    val attempts = resolveAttempts(args)

    val dir = System.getProperty("user.dir")
    println("dir=$dir")                          // e.g.: dir=/Users/alice/projects/guess
    println("max=$max attempts=$attempts")       // e.g.: max=100 attempts=7

    runGuessNumberGame(max, attempts)
}

Note: here main reads like a scenario. First we prepared parameters, then printed a bit of diagnostics, then called the main logic.

Quick reference: args vs env vs working directory

To avoid confusion, it is useful to distinguish these channels not by “how it is customary on Linux”, but by meaning.

Channel What it is When it is convenient Main risk
args (Array<String>) Explicit launch parameters, a list of strings Quickly change the value on each run Easy to forget an argument or mix up the order
env (System.getenv) Settings that “live next to the launch” Keep defaults for the environment (e.g., “on this PC max=200 always”) The variable may not exist → you get null
working directory ("user.dir") Context of “where it was started from” Diagnostics and understanding why relative paths behave strangely Can differ between IDE and terminal

6. Common mistakes

Mistake #1: accessing args[0] without checking the array size.
This is one of the most frequent causes of “crashing out of nowhere”: you run without arguments, and the code immediately tries to read the first element. The right habit: first if (args.size > 0), then index access.

Mistake #2: parsing numbers with toInt() without a safety net.
If you use toInt() for arguments or environment variables, then for any non-numeric string the program will throw an exception and terminate. For input data, almost always prefer toIntOrNull() and then normal handling via if (x != null) or ?:.

Mistake #3: assuming an env variable “definitely exists”.
System.getenv("NAME") returns a nullable value for a very honest reason: the variable may not exist. Even if you configured it “on your machine”, on another computer or another run it may be missing. That is why ?: and a clear default are not a luxury but a way to avoid mysterious crashes.

Mistake #4: ignoring the working directory and being surprised “why the file/folder cannot be found”.
Even if you are not reading files yet, you can already run into situations where a relative path is used indirectly (for example, in launch parameters or in output). The habit of printing System.getProperty("user.dir") during debugging often saves hours — and some nerves.

Mistake #5: mixing “reading the environment” and “business logic” in one function.
If main parses args, reads env, prints diagnostics, plays “guess the number”, and also cracks jokes — it will be hard to debug. It is much calmer when main only assembles input parameters, while the core logic lives in a separate function and receives already-prepared values.

1
과제
Kotlin SELF, 레벨 17, 레슨 3
잠금
실행 보고서
실행 보고서
1
과제
Kotlin SELF, 레벨 17, 레슨 3
잠금
전시 모드
전시 모드
1
과제
Kotlin SELF, 레벨 17, 레슨 3
잠금
기본값을 사용하는 직사각형
기본값을 사용하는 직사각형
1
과제
Kotlin SELF, 레벨 17, 레슨 3
잠금
실행 구성
실행 구성
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION