enterprise-java
The Enterprise Java Ecosystemβ
JVM, JRE, JDKβ
In languages like C or C++, source code is compiled directly into machine code (binary instructions: 010101...) that only runs on a specific operating system and processor architecture (e.g., Windows x86_64, macOS ARM64).
Java introduced the famous motto: "Write Once, Run Anywhere" (WORA). To achieve this, Java does not compile to native machine code. Instead:
- Source code (
.javaor.kt) is compiled into Bytecode (.class). - Bytecode is a standardized intermediate instruction set.
- The Java Virtual Machine (JVM) is a software runtime installed on your OS that reads this bytecode and translates it on-the-fly (via Just-In-Time compilation / JIT) into native CPU instructions.
+------------------+ +-------------------+
| Java Code | | Kotlin Code |
| (HelloWorld.java) | (HelloWorld.kt) |
+--------+---------+ +---------+---------+
| |
javac | kotlinc
v v
+----+--------------------------+----+
| Bytecode (.class files) |
| (e.g., HelloWorld.class) |
+-----------------+------------------+
|
v
+-----------------+------------------+
| Java Virtual Machine (JVM) |
+-----------------+------------------+
|
+----------------+----------------+
| |
v v
[Windows x64] [Linux ARM64]
You will constantly see these three acronyms. Here is the hierarchy:
| Term | Full Name | What it Contains | Who Needs It? |
|---|---|---|---|
| JVM | Java Virtual Machine | Just the execution engine that runs .class bytecode. | Computers running JVM apps. |
| JRE | Java Runtime Environment | JVM + standard libraries (e.g., java.lang, java.util). | End users running pre-compiled apps (largely deprecated in favor of packaged JDKs). |
| JDK | Java Development Kit | JRE + JVM + Compilers (javac, kotlinc), Debuggers, and tools (jar, javap). | Developers and build tools (like Maven & Gradle). |
π‘ Key Takeaway: As a developer, you always install a JDK, not just a JRE or JVM.
JVMβ
You can create bytecode from java files using JVM, and that bytecode can run on any machine that has the JVM.
The JVM does not care what language you wrote in. As long as a compiler produces valid JVM bytecode, the JVM will execute it!
- Java (
.java): The original static, object-oriented language compiled withjavac. - Kotlin (
.kt,.kts): Modern, concise, null-safe language developed by JetBrains, compiled withkotlinc. Fully interoperable with Java (Kotlin can call Java classes, and Java can call Kotlin classes without wrappers!). - Groovy (
.groovy): Dynamic, flexible scripting language historically used in Gradle build scripts and Jenkins pipelines. - Scala (
.scala): Advanced object-functional language popular in big data (Apache Spark).
Kotlin is fully interoperable with Java, which means Kotlin works great with all existing JavaΒ source codeΒ and libraries. It also allows companies to make a gradual migration from Java to Kotlin because Java code can access Kotlin code, too. At the same time, developers can use Kotlin as the only language for their projects without Java at all.
AΒ build toolΒ is a program that automates the process of creating executable applications from source code.
Here are the two main build tools: Maven and Gradle.
kt vs ktsβ
.kt: Standard Kotlin source file. Intended to be compiled into classes and packaged into applications/libraries..kts: Kotlin Script file. Intended to be executed directly as a script (e.g., TeamCity'ssettings.ktsor Gradle'sbuild.gradle.kts).
Distributable file typesβ
There are three main distributable files:
.class: A single compiled file containing the bytecode for one class or interface..jar: A.jarfile is simply a standard ZIP archive containing:- Compiled
.classfiles. - Resource files (images, configs, XML, JSON).
- A
META-INF/MANIFEST.MFfile (which can specify metadata and theMain-Classto run).
- Compiled
.war: A.jarstructured specifically for deployment into a Java Servlet container (like Apache Tomcat, Jetty, or WildFly), containing web assets (WEB-INF/web.xml, HTML, JS).
AΒ Java Archive (JAR)Β is a platform-independent file format to pack multiple files together and distribute them as a single unit. So it comes in handy if your application contains lots of files.
These are the main benefits of a JAR file:
- it can aggregate multiple files of different types;
- it is a compressed archive (with aΒ ZIPΒ algorithm) that reduces the size of the application and makes it easier to move it over a network;
- you can digitally sign it (this feature won't be discussed in this topic).
NOTE
A JRE can start an application packed into a JAR, but to create a JAR you need to use a JDK.
A JAR file is simply an aggregation of bytecode files (.class), configuration files (e.g.,Β .json,Β .xml), images, and even sound clips into a single compressed file.
- All files except bytecode files are usually calledΒ resources.
- It is also recommended that a JAR file contains a special file namedΒ
MANIFEST.MFΒ in a special folder namedΒMETA-INF. This file should describe the JAR file itself (a manifest is a kind of metadata): its version, the author, and so on.
Here is the example of a structure of a JAR file:
example.jar
βββ META-INF
β βββ MANIFEST.MF
βββ second
β βββ Main.class
β βββ MyIcon.png
βββ third
βββ another
βββ OneMore.class
my-library.jar (ZIP format)
βββ META-INF/
β βββ MANIFEST.MF
βββ com/
β βββ example/
β βββ App.class
β βββ utils/
β βββ Helper.class
βββ application.properties
Classpathβ
In Python, you have sys.path. In Node.js, you have node_modules.
In Java and Kotlin, you have the Classpath.
The Classpath (-cp or -classpath options on the java CLI command) is a list of directories and .jar files telling the JVM and compiler where to look when resolving imported classes.
For example, when your Kotlin file has:
import jetbrains.buildServer.configs.kotlin.v2019_2.Template
The compiler asks: "Where on my classpath is a .jar containing the package jetbrains/buildServer/configs/kotlin/v2019_2/Template.class?"
- If found on the classpath Compilation succeeds & IDE shows clean code.
- If NOT found on the classpath Compilation fails with
Unresolved reference& IDE paints the code RED!
NOTE
What build tools solve
Managing this Classpath manually (downloading 50 JARs and linking them with java -cp lib1.jar;lib2.jar...) is nightmare fuel. This is why Build Tools (Maven & Gradle) exist!
Build tools introβ
Why use build tools?β
AΒ build toolΒ is a program that automates the process of creating executable applications from source code. The build process includes compiling sources and linking and packaging the code into a usable or executable form.
In small projects (like projects for learning), developers can manually invoke the build process. However, this approach is not efficient for larger projects, when it is pretty hard to keep track of what needs to be built.
Here are the three main benefits of using build tools:
- Automating the build process minimizes the risk of human error.
- Additionally, an automated build tool typically runs faster than someone performing the same steps manually.
- As a consequence, an automated build process improves the quality of the product and saves time and money.
Modern build tools can perform a wide variety of tasks that software developers do in their day-to-day activities:
-
Downloading and adding dependencies.Β This is especially convenient when your project depends on a large number of libraries.
-
Compiling source code into bytecode. Build tools will invoke the compiler for all the files in your project.
-
Packaging compiled code.Β You will have a production-ready application archive like JAR, APK, or some other.
-
Running tests.Β For example, testing the application archive every time to check if it works correctly. It allows programmers to avoid bugs after modifying the application.
-
DeployingΒ to a production environment.
There are three main build tools for Java-based projects:Β Apache Ant,Β Apache Maven, andΒ Gradle.
-
Apache AntΒ was released in 2000. It is the oldest of these three build tools. Coders rarely useΒ AntΒ in new projects but it still occurs in practice. You can use this tool together withΒ Apache IvyΒ to manage dependencies.
-
Apache MavenΒ was released in 2004, and now it is one of the most popular choices for Java developers (especially for server-side development). Many projects, both old and new, use Maven as a build tool because of its powerful dependency management possibilities.
-
MavenΒ follows theΒ Convention Over ConfigurationΒ concept which means that a developer needs to specify only unconventional aspects of the application, and all standard aspects work by default.
-
GradleΒ is a new tool compared to Ant and Maven. It was released in 2007 and is now standard for Android applications. Also, developers use it for server and desktop development.Β GradleΒ aims toΒ βcombine the power and flexibility of Ant with the dependency management and conventions of Maven into a more effective way to build.β
NOTE
Apache MavenΒ andΒ GradleΒ are more than simply build tools. They manage almost the entire lifecycle of an application.
DSL vs GPLβ
Please note that DSL is a computer language specialized to a particular application domain (like build automation). This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains.
- DSL: stands for "domain specific language", and is not turing-complete.
- GPL: stands for "general purpose language", and is turing-complete.
Maven introβ
Apache Maven is the grandmaster of JVM build tools. It introduced declarative dependency management, standardized project structures, and a global repository ecosystem.
Maven is governed by a single configuration file in the project root: pom.xml (Project Object Model).
Instead of writing custom build scripts that manually compile files, Maven is declarative: you declare what the project is, what it needs (dependencies), and what plugins to execute. Maven handles the how.
Gradle introβ
Gradle is a build automation tool. Think of it as the project manager for your code.
The key features of Gradle are as follows:
-
Settings files.Β Gradle uses several types of settings files to describe how to build a project.
-
Build-by-convention.Β A programmer doesn't need to specify every building step that needs to be done. Instead, Gradle uses default settings and behavior. Although, every step of the default build process can be customized if necessary.
-
Dependency management.Β Gradle automatically downloads specified external libraries and solves conflict cases with dependencies. You can declare as many dependencies as you need for a project.
-
Builds. Gradle allows programmers to design well-structured and easily maintained comprehensible builds. It also supports complex cases such as multi-project or partial builds.
-
Ease of migration. Gradle can easily adapt to any project structure you have. Therefore, you can always develop your project exactly the way you want.
-
DSLΒ (based on Groovy and Kotlin) for writing scripts in settings files.
GradleΒ is a modern automation tool that helps build and manage projects written in Java, Kotlin, Scala, and other JVM-based languages. It describes project dependencies and determines how to build a project. Gradle uses a well-designed plugin system, which is why it is a highly extensible tool. You can use plugins for automatic versioning, automatic testing, reporting about the build, and so on.
One of the best things about Gradle is itsΒ Groovy-basedΒ domain-specific language (DSL) that gives developers a specific way to form custom build scripts. The Kotlin developers are especially lucky since Gradle also started to support Kotlin for such scripts. So, there are two languages to write the Gradle build scripts (Groovy and Kotlin) and you can choose any of them.
For example, instead of manually downloading a JSON library, you tell Gradle:
dependencies {
implementation("com.fasterxml.jackson.core:jackson-databind:2.19.0")
}
- Gradle is a DSL (domain-specific language) that is based on Groovy.
- Groovy is a programming language that was traditionally used to write Gradle build scripts.
Historically, Gradle files looked like this, which uses the Gradle Groovy DSL
plugins {
id 'org.jetbrains.kotlin.jvm' version '2.2.20'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib'
}
NOTE
What makes gradle so great is that you can specify as many dependencies as you want, and gradle will install them all and handle any conflicts for you
There are two different versions of the gradle language: the newer kotlin version and the groovy version:
apply plugin: "application" // for Groovy DSL
apply(plugin = "application") // for Kotlin DSL
// β Groovy
implementation 'com.google.guava:guava:33.0.0-jre'
// βοΈ Kotlin
implementation("com.google.guava:guava:33.0.0-jre")
Nowadays, especially for Kotlin projects, many developers prefer the Kotlin DSL, because instead of the gradle file being called build.gradle, you use build.gradle.kts, which means the build script itself is written in Kotlin.
Here's an example of using Kotlin DSL:
plugins {
kotlin("jvm") version "2.2.20"
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib")
}
Mavenβ
pom.xmlβ
Every single library, plugin, and project in the Java/Kotlin universe is uniquely identified by three coordinates: GAV (GroupId, ArtifactId, Version).
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>1.9.20</version>
</dependency>
| Coordinate | Analogy | Description |
|---|---|---|
groupId | Organization / Domain (reversed) | E.g. com.google.guava, org.jetbrains.kotlin, org.jetbrains.teamcity. |
artifactId | Specific Project / Library Name | E.g. guava, kotlin-stdlib, configs-dsl-kotlin. |
version | Release Version | E.g. 1.0.0, 2022.10, 1.0-SNAPSHOT. |
You also have these optional coordinates:
<scope>: decides the scope of where to install the plugincompile(default): Required at both compile-time and runtime.provided: Needed to compile, but assumed to be provided by the host environment at runtime.test: Only placed on the classpath during unit test execution (e.g., JUnit).runtime: Only needed to run, not to compile.
The SNAPSHOT keyword is a variable for dynamic build numbers:
- Release version (e.g.,
1.8.0): Immutable. Once published, the code never changes. - Snapshot version (e.g.,
1.0-SNAPSHOT): Work-in-progress. Maven will periodically check the remote repository for newer daily/hourly builds.
Let's dissect the essential sections of a real pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
<modelVersion>4.0.0</modelVersion>
<!-- 1. Coordinates of THIS project -->
<groupId>PrismModern</groupId>
<artifactId>PrismModern_dsl</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 2. Parent POM (Inheritance) -->
<parent>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<!-- 3. Remote Repositories (Where to find dependency JARs) -->
<repositories>
<repository>
<id>jetbrains-all</id>
<url>https://download.jetbrains.com/teamcity-repository</url>
</repository>
<repository>
<id>teamcity-server</id>
<url>https://teamcity.jetbrains.com/app/dsl-plugins-repository</url>
</repository>
</repositories>
<!-- 4. Plugin Repositories (Where to find build tool plugins) -->
<pluginRepositories>
<pluginRepository>
<id>JetBrains</id>
<url>https://download.jetbrains.com/teamcity-repository</url>
</pluginRepository>
</pluginRepositories>
<!-- 5. Dependencies (Libraries our code imports) -->
<dependencies>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin</artifactId>
<version>${teamcity.dsl.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<!-- 6. Build & Plugins (Tools that compile or process the code) -->
<build>
<sourceDirectory>${basedir}</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals><goal>compile</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<parent>: Maven supports object-oriented inheritance for builds! Child projects inherit dependencies, properties (like${kotlin.version}), and plugin configurations from parent POMs.<repositories>: Public Maven Central (repo.maven.apache.org) only hosts open-source packages. Proprietary or vendor-specific libraries (like JetBrains TeamCity DSL plugins) must have their repository URLs declared here.<pluginRepositories>: Maven separates libraries your code uses (<repositories>) from build plugins that run during compilation (<pluginRepositories>). Both must be reachable!
Repositoriesβ
Where do downloaded JARs actually go on your computer?
- On Windows:
C:\Users\<YourUsername>\.m2\repository\ - On Mac/Linux:
~/.m2/repository/
βββββββββββββββββββββββββββββββββββββββββββ
β Remote Repositories β
β - Maven Central (repo1.maven.org) β
β - JetBrains (download.jetbrains.com) β
β - TeamCity Server (teamcity.jetbrains) β
ββββββββββββββββββββββ¬βββββββββββββββββββββ
β
1. Download over HTTPS
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββ
β Local Maven Cache β
β (~/.m2/repository/) β
β - Cached .jar, .pom, .sha1 files β
ββββββββββββββββββββββ¬βββββββββββββββββββββ
β
2. Classpath Injection
β
βΌ
βββββββββββββββββββββββββββ΄ββββββββββββββββββοΏ½οΏ½βββββββ
β β
βΌ βΌ
ββββββββββββββββββββββββ ββββββββββββββββββββββββ
β Maven CLI Build β β IntelliJ IDEA IDE β
β (javac / kotlinc) β β (Code Intelligence) β
ββββββββββββββββββββββββ ββββββββββββββββββββββββ
Within this top level ~/.m2/repository directory, Maven organizes the folder structure strictly according to the GAV coordinates in this format:
~/.m2/repository/<groupId>/<artifactId>/<version>
Here's an example:
- Library:
org.jetbrains.teamcity:configs-dsl-kotlin:2022.10 - Folder on disk:
C:\Users\amallick.ENGINEERS\.m2\repository\org\jetbrains\teamcity\configs-dsl-kotlin\2022.10\ - Files inside:
configs-dsl-kotlin-2022.10.jar(The compiled bytecode)configs-dsl-kotlin-2022.10.pom(Metadata & transitive dependencies)configs-dsl-kotlin-2022.10.jar.sha1(Checksum validation)
Maven CLIβ
Maven builds follow an ordered sequence of phases, where each CLI command in the chain implicitly runs the dependent CLI commands before it in the chain.
NOTE
When you run mvn compile, Maven executes validate β compile.
validate ββ> compile ββ> test ββ> package ββ> verify ββ> install ββ> deploy
Therefore you have these maven CLI commands:
validate: Checks that the project structure andpom.xmlare valid.compile: Compiles source code (src/main/java,src/main/kotlin) intotarget/classes.test: Runs unit tests (e.g. Surefire plugin).package: Packages compiled classes into a.jaror.warintarget/.install: Copies the packaged.jarinto your local~/.m2/repositoryso other local projects on your machine can consume it.deploy: Uploads the final.jarto a remote corporate artifact server (e.g. Nexus, Artifactory).
| Command | What it Does | When to Use It |
|---|---|---|
mvn compile | Resolves dependencies and compiles all source code. | Basic build check. |
mvn clean | Deletes the target/ directory. | When you want a 100% fresh, clean build. |
mvn test | Runs unit tests. | Verification before committing. |
mvn compile -U | Forces Maven to re-check and download snapshot/failed dependencies. | When libraries failed to download earlier. |
mvn dependency:tree | Prints a visual tree of all dependencies and transitive dependencies. | Troubleshooting version conflicts. |
mvn -X compile | Runs compilation with maximum debug logging. | Diagnosing download or plugin crashes. |
mvn compileβ
The mvn compile command reads the pom.xml at the root of the current directory and compiles the source code into .class files.
mvn compile
You have these additional flags you can set:
-f <path-to-pom-xml>: lets you point to a different pom XML file by filepath to compile based on that.-U: always bypass cache, reload it. Prevents stale cache errors.-X: Maximum debug output (prints full stack traces and HTTP requests)
# Maximum debug output (prints full stack traces and HTTP requests)
mvn compile -X
# Force re-download of snapshots and failed releases
mvn compile -U
# Build offline (prevents remote network checks)
mvn compile -o
mvn dependencyβ
mvn dependency:tree: print all dependencies as a tree
# Print all dependencies as a tree
mvn dependency:tree
Bad cache: The Dreaded .lastUpdated Fileβ
When Maven tries to download a library and fails (due to a 404, offline server, or blocked HTTP):
- Maven writes a tracking file:
configs-dsl-kotlin-parent-1.0-SNAPSHOT.pom.lastUpdated. - Inside
.lastUpdated, Maven records: "Failed to download at timestamp X from URL Y". - Important Cache Rule: By default, Maven will NOT retry downloading failed dependencies on subsequent runs until a timeout expires (often 24 hours), unless you explicitly pass the
-Uflag (mvn compile -Uforces update check)!
NOTE
It's very important to always consider your compilation could be failing because of a stale cache of your libraries, so always run mvn compile -U.
There are all kinds of reasons trying to download a library fails:
- timeout error: takes too long to download, a 404 or 500 timeout request came back.
- HTTP blocking: Modern Maven versions (3.8.1+) strictly block unencrypted
http://repositories for security (to prevent Man-in-the-Middle attacks).
Gradleβ
Gradle combines the declarative dependency management of Maven with the scripting power of full programming languages (Groovy and Kotlin).
Key Gradle Features:
- Build Cache & Incremental Builds: If you modify 1 file out of 1,000, Gradle only recompiles that 1 file.
- Gradle Daemon: A background JVM process that stays warm in memory so subsequent builds execute in milliseconds.
- Gradle Wrapper (
gradlew,gradlew.bat): A lightweight script bundled directly with the repo that automatically downloads the exact correct Gradle version, requiring zero installation from the developer.
Gradle installation and guideβ
There are two ways to use gradle:
- Method 1 -
gradleCLI: install thegradleCLI on your laptop and initialize projects with that and use the CLI for building projects. - Method 2 - IntelliJ managed Gradle: IntelliJ will create gradle configuration for you and
./gradleew(Linux and Mac) and./gradleew.bat(Windows) scripts files to install gradle and run it in the context of your project, removing the need for a globalgradleCLI.
Core gradle structureβ
Let's start with an introduction to the key concepts in Gradle:Β projectsΒ andΒ tasks.
-
AΒ projectΒ might represent eitherΒ something to be builtΒ (e.g. a JAR file or ZIP archive) orΒ a thing to doΒ (e.g. deploying the application). Every Gradle build contains one or more projects.
-
AΒ taskΒ is a single piece of work that a build performs. This can include compiling classes, running tests, generating docs, and so on. Every project is essentially a collection of one or several tasks.
Here are the steps to setup a project in gradle:
- Create a new gradle project with
gradle init:
gradle init
- You should now see a structure like so:
.
βββ build.gradle
βββ gradle
β βββ wrapper
β βββ gradle-wrapper.jar
β βββ gradle-wrapper.properties
βββ gradlew
βββ gradlew.bat
βββ settings.gradle
Here is brief info about all the generated files:
-
TheΒ
build.gradleΒ file is a primary file that specifies the Gradle's project, including its tasks and external libraries. Here, it is located in theΒgradle-demoΒ folder and can be created after invoking theΒgradle initΒ command. For now, this file doesn't contain anything useful, but in real projects it is often updated with new information. -
The filesΒ
gradle-wrapper.jar,Βgradle-wrapper.properties,ΒgradlewΒ andΒgradlew.batΒ belong to Gradle Wrapper which allows you to run Gradle without its manual installation. -
TheΒ
settings.gradleΒ file specifies which projects to include in your build. This file is optional for a build that has only one project, but it is mandatory for a multi-project build.
NOTE
You can also invokeΒ buildΒ and other commands likeΒ ./gradlew buildΒ for Unix-based systems andΒ gradlew.bat buildΒ for Windows. It will automatically download Gradle and run the specified command. Using wrappers allows developers to start working with a Gradle-based project without having to install it manually.
Gradle CLIβ
# Force refresh of all dynamic/cached dependencies
./gradlew build --refresh-dependencies
# Print stacktrace on failure
./gradlew build --stacktrace
# Print info/debug logs
./gradlew build --info
./gradlew build --debug
# Stop background Gradle Daemons if stuck
./gradlew --stop
./gradlew build: builds the project./gradlew test: tests the project./gradlew run: run the app./gradlew clean: delete build output
Gradle library storageβ
Unlike Maven which uses ~/.m2/repository/, Gradle stores its downloaded dependency cache at:
- Windows:
C:\Users\<Username>\.gradle\caches\modules-2\files-2.1\ - Mac/Linux:
~/.gradle/caches/modules-2/files-2.1/
NOTE
Gradle uses SHA-1 content-addressable hash directories to ensure that multiple projects on your machine never corrupt each other's downloaded libraries.
Using gradle with Groovy DSLβ
Groovy DSL is more obsolete and relies on the build.gradle file:
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.9.20'
}
repositories {
mavenCentral()
maven { url 'https://download.jetbrains.com/teamcity-repository' }
}
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.9.20'
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0'
}
Using gradle with kotlin DSLβ
Kotlin DSL with gradle is so much better because of these three main reasons:
- Type Safety & Auto-complete: In IntelliJ IDEA, pressing
Ctrl+Spacein a.ktsfile gives you full autocomplete, type checking, and instant documentation. - Refactoring: Renaming symbols across your codebase safely updates
.ktsbuild scripts. - Compile-time Error Detection: Syntax or type mistakes are highlighted in red before running the build.
Here's how to create a project with Kotlin DSL and Gradle
- Open IntelliJ IDEA
- Click New Project
- Select Kotlin
- Select Gradle
- Choose Kotlin DSL
- Click Create
You'll get a project structure similar to:
my-project/
βββ build.gradle.kts
βββ settings.gradle.kts
βββ gradlew
βββ gradlew.bat
βββ src
βββ main
β βββ kotlin
βββ test
βββ kotlin
gradlew: bash script CLI for linux and MacOS to control gradle project dependencies, including installation, running scripts, and uninstallationgradlew.bat: the windows script version of thegradlewbash script.build.gradle.kts: the main gradle config, and where you add plugins, repositories, and dependencies.
// list of plugins to use
plugins {
kotlin("jvm") version "2.2.20"
}
// list of code repos to add
repositories {
mavenCentral()
}
// list of dependencies to install
dependencies {
testImplementation(kotlin("test"))
}
settings.gradle.kts: project settings:
rootProject.name = "my-project"
basicsβ
In Maven, you had <scope>compile</scope>, <scope>test</scope>, etc. In Gradle, dependencies are assigned to Configurations:
| Configuration | What it Means | Maven Equivalent |
|---|---|---|
implementation | Used to compile and run your code. Hidden from downstream projects depending on you. | <scope>compile</scope> |
api | Used to compile and exposed transitively to downstream projects. | <scope>compile</scope> |
compileOnly | Needed at compile-time only (not packaged at runtime). | <scope>provided</scope> |
runtimeOnly | Needed to run the app, but not needed to compile source code (e.g., database JDBC drivers). | <scope>runtime</scope> |
testImplementation | Needed only when running tests. | <scope>test</scope> |
Gradle pluginsβ
Gradle plugins
The plugins section adds plugins to the gradle project
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("kotlin-parcelize")
// 1. install ksp plugin
id("com.google.devtools.ksp") version "1.9.0-1.0.13"
}
Gradle repositoryβ
Gradle repository
The repository section in your settings.gradle.kts allows you to specify any online repositories to pull dependencies from.
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
Gradle dependenciesβ
Here are the steps to add new dependencies and install them so you can use third-party packages in your Kotlin project:
- Add a new dependency to the
dependenciesblock in thebuild.gradle.kts:
dependencies {
implementation("com.google.code.gson:gson:2.13.1")
}
- Save the file
- Click Load Gradle Changes in IntelliJ or click the Gradle refresh button, which then downloads the library automatically.
- Import the library into your code and use it:
import com.google.gson.Gson
fun main() {
val gson = Gson()
println(gson.toJson(listOf(1, 2, 3)))
}
All togetherβ
- Write your main kotlin code in
main.kt
fun main() {
println("Hello Gradle + Kotlin!")
}
- Add configuration to the
build.gradle.ktsand specify theapplicationblock entrypoint to beMainKt
plugins {
kotlin("jvm") version "2.2.20"
application
}
repositories {
mavenCentral()
}
dependencies {
testImplementation(kotlin("test"))
}
application {
mainClass.set("MainKt")
}
- Run the app (which automatically builds it)
./gradlew run
Maven vs Gradleβ
| Concept | Maven | Gradle (Kotlin DSL) |
|---|---|---|
| Build Configuration File | pom.xml | build.gradle.kts (or build.gradle) |
| Project Settings / Submodules | <modules> in root pom.xml | settings.gradle.kts (include("subproject")) |
| Local Cache Directory | ~/.m2/repository/ | ~/.gradle/caches/ |
| Add Central Repository | Built-in by default | repositories { mavenCentral() } |
| Add Custom HTTPS Repo | <repository><url>https://...</url></repository> | repositories { maven("https://...") } |
| Compile Code | mvn compile | ./gradlew compileKotlin or ./gradlew assemble |
| Clean Output | mvn clean | ./gradlew clean |
| Run Tests | mvn test | ./gradlew test |
| Full Build & Package | mvn package or mvn install | ./gradlew build |
| Force Dependency Refresh | mvn compile -U | ./gradlew build --refresh-dependencies |
| View Dependency Tree | mvn dependency:tree | ./gradlew dependencies |
IntelliJ basicsβ
Code actionsβ
Most common actionsβ
CTRL + ENTER: code completionALT + ENTER: apply quick fix or apply "intention"
Command paletteβ
Press shift twice or CTRL + SHIFT + A to bring up the command palette. Within the command palette, you can search in these subcategories:
CTRL + N: search classesCTRL + SHIFT + N: search filesCTRL + ALT + SHIFT + N: search symbols
In summary:
- classes: to search class names only, do
CTRL + N, then when hovering over a class definition, you can pressCTRL + Qto view documentation of the class, then pressescto close th epopup - symbols:
Logpointsβ
Log points allow you to do dynamically add print statements that get outputted to the console without you writing any code, and you can add log points during runtime as well.
IntelliJ CLIβ
You can launch IntelliJ IDEA directly from the terminal or command prompt using its command-line launcher. This is useful for quickly opening projects, files, or even jumping to a specific line in a file.
# Open a project folder
idea ~/MyProject
# Open a specific file at line 42
idea --line 42 ~/MyProject/scripts/app.js
The basic syntax is as follows:
idea <path-to-project-or-file>
You have these options:
-
--waitβ Waits until the file is closed before returning control to the terminal. -
--nosplashβ Skips the splash screen. -
--disableNonBundledPluginsβ Starts without custom plugins (useful for troubleshooting). -
--line <n>: open a file at a specific line number
IntelliJ Project basicsβ
IntelliJ environmentβ
IntelliJ is not just a text editor; it maintains a living, semantic symbol graph of your entire codebase.
To do this, IntelliJ maintains its own internal configuration in the .idea/ folder:
| File / Folder | Purpose in IntelliJ |
|---|---|
.idea/misc.xml | Defines the Project SDK (which JDK is used, e.g. JDK 19) and language level. |
.idea/modules.xml | Lists all modules that make up the project. |
*.iml (e.g. PrismModern_dsl.iml) | Module definition: lists source folders, test folders, excluded folders (target/), and attached library JARs. |
.idea/jarRepositories.xml | Caches remote Maven repository URLs extracted from pom.xml. |
.idea/libraries/*.xml | XML descriptors pointing to exact .jar paths inside ~/.m2/repository/. |
There is a difference between IntelliJ and traditional build tools like Maven:
- Maven / Gradle CLI: reads a configuration file like
pom.xmland wraps something likekotlincorjavacto provide the classpath behind the scenes for you- example: When you run
mvn compile, Maven runs independently in a separate JVM process.
- example: When you run
- IntelliJ: reads configuration from the
.ideafolder in the project directory to surface compiler errors in the UI.- example: When you edit code in the editor, IntelliJ uses its own in-memory index of configured libraries to highlight syntax and check types.
The Bridge: IntelliJ imports your pom.xml (or build.gradle.kts) and automatically generates its internal .idea library descriptors based on what Maven declared.
Fixing bad importsβ
When your imports are red (Unresolved reference: jetbrains...), one of these 6 things is broken:
WHY IS MY CODE RED?
β
βββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββ
βΌ βΌ βΌ
[1. Missing JDK/SDK] [2. Failed Dependency] [3. Unsynced Maven]
Project Structure has no pom.xml has dead URL, pom.xml was edited,
JDK assigned (red JDK). JAR never reached ~/.m2/. IDE hasn't reloaded yet.
β β β
βΌ βΌ βΌ
[4. Unmarked Sources] [5. Blocked HTTP Repo] [6. Corrupt Index]
Folder is plain yellow/gray, Maven 3.8+ refused HTTP; IntelliJ cache desynced
not blue "Sources Root". JAR download aborted. from disk state.
-
Cause 1: Missing or Incompatible JDK / Project SDK
- Symptom: Even basic Java/Kotlin classes (
String,List,println) are red. - Check: Press
Ctrl+Alt+Shift+S(Project Structure) Project Verify SDK is set to a valid JDK (e.g., JDK 17 or JDK 19).
- Symptom: Even basic Java/Kotlin classes (
-
Cause 2: Failed Dependency Download (The
.teamcityIssue!)- Symptom: Standard Kotlin works, but
import jetbrains.buildServer...is red. - Why: Maven could not download the
.jar(due to network timeout, wrong URL, or HTTP block). Since the.jaris not in~/.m2/repository/, IntelliJ has nothing to index!
- Symptom: Standard Kotlin works, but
-
Cause 3: Maven Project Not Imported / Out of Sync
- Symptom: You added a
<dependency>topom.xml, but IntelliJ still shows the class in red. - Why: IntelliJ does not auto-reindex instantly on every keystroke in
pom.xml.
- Symptom: You added a
-
Cause 4: Source Roots Not Configured
- Symptom: Files in your project cannot see classes in adjacent folders.
- Why: The directory is not marked as a Sources Root (marked in blue in IntelliJ's project tree).
-
Cause 5: Maven 3.8+ Security Blocking Insecure
http://URLs- Symptom: Maven refuses to connect with
Blocked mirror for repositories. - Why: Modern Maven versions disable plain HTTP repositories by default for security.
- Symptom: Maven refuses to connect with
-
Cause 6: Stale / Corrupted IDE Cache
- Symptom: The JAR exists in
~/.m2/repository,mvn compilepasses in the terminal, but the IDE editor still shows red lines.
- Symptom: The JAR exists in
Here are three techniques to fix these causes:
- method 1 - reload maven project: reload all maven projects via IntelliJ toolbar
- Click the Maven tool window tab.
- Click the Reload All Maven Projects button (the two circular arrows π at the top left of the Maven pane).
- Watch the bottom status bar: IntelliJ will read
pom.xml, download any missing JARs, and update its library indexes.
- method 2 - register
pom.xmlas a maven project: Right-clickpom.xmlin the Project Explorer β Select Add as Maven Project (or Maven β Reload Project). - method 3 - invalidate caches: If the terminal passes
mvn compilebut the IDE editor remains stuck, then go toFileInvalidate Caches...Check all options Click Invalidate and Restart.
Whenever you face a build issue in any Java/Kotlin repository in the future, follow this 5-step checklist:
- Check Java Version: Run
java -versionandjavac -version(ensure matching JDK 17/21). - Check Repository URLs: Ensure all URLs in
pom.xmlorbuild.gradle.ktsusehttps://and are reachable in a browser/terminal. - Run CLI Build with Debug Logs: Run
mvn compile -Xor./gradlew build --infoto see the exact HTTP failure or missing GAV. - Purge Failed Downloads: Delete any
.lastUpdatedfiles in~/.m2/repositoryand runmvn compile -U. - Sync IntelliJ: Click the π Reload All Maven Projects button in the IntelliJ Maven tool window.
IntelliJ with Gitβ
Basicsβ
1 - Clone a projectβ
You can clone a project like so: you go to File, then to New, then to Project from Version Control.

You can either authenticate with a repository URL and SSH or with a Github or Gitlab account so you have direct integration with your remote Github/Gitlab account and your local IDE and git.
2 - Make a commit, view changes, create a branchβ
When clicking on the top bar branch view, you have three categories of branch groupings available:
- Recent: shows you the top 5 most recently accessed branches
- Local: shows you all your local branches
- Remote: shows you all the remote branches
A cool feature that IntelliJ offers on top of Git is the ability to group branches into folders via a <foldername>/<branchname> syntax, which is semantically meaningless in normal git, but in IntelliJ, it lets you group branches into subfolders.

- Once you make a change, you can press Alt + 0 to open the commit view (shows staged and modified/unstaged files) or just manually go to the commit sidebar.
2. You can create a new branch if you don't want to commit on Main. You can do so manually by clicking on the branch picker, or by pressing CTRL + ALT + N

Git Log Viewβ
The Git Log View at the bottom can be used tot view the log to undo, squash, and drop specific commits for any individual commit.
NOTE
You can also open up the git log view with ALT + 9
Here's what you can do for individual commits:
- undo commit: removes the commit by performing a
git reset --soft HEAD~1 - edit commit message: amends the commit with a new message
Undoing commitsβ

IntelliJ with AIβ
Setting up completionβ
- Go to Tools -> AI -> JetBrains AI and then fill out the completion endpoint with an OpenAI compatible endpoint or connect your Jetbrains AI account

Setting up skillsβ

THen in a chat you can use slash commands to refer to specific skills and force AI to use those skills.