IntelliJ IDEA in Practice: Your First Java Project, Compile and Run

bee2026-10-0830 min read0 views
From installing IDEA to running your first project: layout, SDK setup, breakpoints, Maven sync and six beginner traps handled in one pass.
1 / 132
Section
0. The 30-second version
2 / 132

IDEA is not "Notepad with colours". It is a machine that performs all the mechanical steps in order for you: save a file and it compiles; change a dependency and it fetches from a repository; press Run and it turns .java into .class, assembles the classpath, starts a JVM and calls main. This article covers three things: installing and finding your way around (the UI and six terms), getting something to run (project layout / SDK / run configuration), and spotting the moment the tool is lying to you (caches, encodings, red code, a greyed-out Run button).

3 / 132
类比|Analogy

writing Java without an IDE is like hand-writing a newspaper and expecting the print shop to notice your revisions — you rewrite three pages, but the shop still has yesterday's type set, so tomorrow's edition prints the old text. IDEA's job is exactly "re-typeset after the draft changes": before every Run it incrementally re-typesets only the pages you touched (compilation) and hands the finished copy to the reader (the JVM). Once that clicks, oddities like "I changed the code but the output is stale" become obvious at a glance.

4 / 132
Diagram
Figure · From pressing Run to running main
Figure · From pressing Run to running main
5 / 132

After this article you should be able to answer:

6 / 132
  • What are Project / Module / SDK / Artifact, and which one decides which JDK I use?
  • When I press Run, what does IDEA do first, and what second? Which folder does the output land in?
  • Why is red code not necessarily my fault? Why did the Run button suddenly turn grey?
7 / 132
Section
1. Choosing the right IDEA: Community or Ultimate
8 / 132

IntelliJ IDEA is the most widely used IDE among Java developers. It ships in two editions, and choosing wrong adds pointless detours to your learning:

9 / 132
Table
AspectCommunityUltimate
PriceFreePaid (trials and educational licenses available)
Plain Java / Maven / GradleSupportedSupported
Spring / Spring BootNone (plugins needed)Full built-in support
Database tools, HTTP ClientNoneBuilt in
Web (Servlet / JSP / Thymeleaf)NoneBuilt in
Best forLearning Java basics, plain Java projectsSpring enterprise development
10 / 132

The conclusion is simple: the rest of this course involves heavy Spring work, so use Ultimate; if you are only learning Java syntax for now, Community is more than enough.

11 / 132
Section
1.1 Should you switch to a localized UI?
12 / 132

IDEA ships an official Chinese Language Pack. Install it via Settings → Plugins, search Chinese, then restart. An honest recommendation:

13 / 132
  • While learning, a localized UI reduces the frustration of not finding menus
  • But shortcuts, error messages and Stack Overflow answers are all in English, so in the long run the English UI pays off more
  • A middle ground: start in your own language, and immediately note the English menu name for every unfamiliar concept
14 / 132
Tip

in either language, the command palette is Ctrl+Shift+A (Cmd+Shift+A on Mac). When you forget where a feature lives, type its English name and search — ten times faster than hunting through menus.

15 / 132
Section
2. Project layout: six terms explained once and for all
16 / 132

Beginners get lost in the pile of terms inside Project Structure. They actually form a chain from largest container to final product:

17 / 132
Table
TermIn one sentenceEveryday analogy
ProjectThe top-level container managing a set of modules and configA building
ModuleThe unit that actually holds source code; there can be severalEach apartment in the building
SDKThe software development kit — here, the JDK the project usesEach apartment's utility standard
LibraryA set of external dependency jarsAppliances you bring in
FacetMarks what technology a module uses (e.g. Web)Labeling a room's purpose
ArtifactThe packaged jar/war and where it is writtenThe finished product after renovation
18 / 132

In one sentence: one Project can contain several Modules; each Module binds an SDK, references Libraries, may carry Facets, and finally produces an Artifact.

19 / 132
Section
2.1 The secret of the .idea folder
20 / 132

After creating a project, the root gains a .idea/ folder and a *.iml file, holding:

21 / 132
text
.idea/├── workspace.xml        # window layout, recent files, transient run state├── modules.xml          # the module list├── misc.xml             # project-level JDK config (often worth sharing)└── *.iml                # module definition (JDK, dependencies, output dir)
22 / 132

Should they be committed to Git? There is no single answer — it depends on the content:

23 / 132
  • workspace.xml holds your personal window state, so it must be excluded; committing it causes daily conflicts
  • misc.xml / *.iml may contain the JDK version and module dependencies, so they can be committed when the team wants consistency
  • The easiest approach: ignore the entire .idea/ in .gitignore and let everyone regenerate it from Maven's pom.xml
24 / 132
Key point

to "commit some, ignore the rest", write .idea/* in .gitignore then re-include with !.idea/misc.xml — ignoring the whole folder and whitelisting a file is cleaner than excluding entry by entry.

25 / 132

IDEA never explains these nouns, yet each one maps to a concrete thing. Play a round: the left column is what you click in a menu, the right column is what it actually does — a wrong pick explains the gap on the spot:

26 / 132
Match
MatchThat menu item — what did it really changeMatched 0/6 · Missed 0
Six hard mappings of action to effect. Both columns are shuffled, so positions tell you nothing
Pick a card on the left first
27 / 132
Section
3. Creating and running your first project
28 / 132
Animation
Animation · First project in five steps
Animation · First project in five steps
29 / 132

Follow the wizard: File → New → Project, choose Java, pick "IntelliJ" as the build system (skip Maven for now to reduce variables), and choose JDK 17 or 21 from the dropdown — if the dropdown is empty you have no JDK yet; click Add SDK → Download JDK and let IDEA fetch one for you.

30 / 132

Once created, right-click the src directory, go New → Package (enter com.example.demo), then on the package New → Java Class (enter Hello), and write:

31 / 132
java
package com.example.demo;public class Hello {    public static void main(String[] args) {        // psvm is an IDEA live template: type psvm and press Enter for this line        String name = "Spring";        int year = 2024;        System.out.println("Hello, " + name + "!");        System.out.printf("The Spring Framework was born in %d%n", 2003);        System.out.println("Current study year: " + year);    }}
32 / 132

A small green triangle appears to the left of the line numbers; click it and choose Run 'Hello.main()', or just press Shift+F10. The Run window prints the result.

33 / 132
Section
3.1 What a Run/Debug Configuration really is
34 / 132

The first time you press Run, IDEA creates a "Run/Debug Configuration" for you, recording how to run this class. Open Run → Edit Configurations and you will see these key items:

35 / 132
Table
FieldPurposeCommon beginner mistake
Main classWhich class's main to start fromPicking the wrong class, causing "main not found"
Program argumentsValues passed to String[] argsSwapped with VM options
VM optionsJVM flags such as -Xmx512mPutting -D system properties in args
Working directoryThe process's working directoryRelative paths then cannot find files
Use classpath of moduleWhich module's classpath to useChoosing the wrong module in a multi-module build
36 / 132
Note

Program arguments go to your program; VM options go to the JVM. Swapping them is a frequent incident: putting --spring.profiles.active=dev into VM options makes it fail as a JVM argument at startup.

37 / 132
Section
4. After you press Run: what compile-and-run actually does
38 / 132

Beginners think "Run means run the Java code", but IDEA first finishes the "compile" step behind the scenes. The full chain is:

39 / 132
  1. Incremental compile: IDEA recompiles only the .java files you changed instead of everything, so the second run is always fast
  2. Write bytecode: output goes to the output directory — out/ for a non-Maven project, target/classes for a Maven one
  3. Class loading: a JVM starts and a ClassLoader reads the main class's bytecode
  4. Run main: the JVM invokes the entry method and the program runs
40 / 132
类比|Analogy

a revised draft must be re-printed. Your manuscript (.java) changed, but the copy readers hold (.class) was set from yesterday's type — unless both sit on the same table, you can never spot the difference. Incremental compilation is "re-typeset only the pages you touched", which is why it is fast; Rebuild Project re-typesets the whole paper, worth doing only when you suspect the type case itself is dirty. This same analogy explains two traps in Section 7: "code changes that never take effect" and "classes disappear after deleting out/".

41 / 132
Section
4.1 The difference between out/ and target/
42 / 132

This is the pair most often confused; keep them straight:

43 / 132
Table
Aspectout/ (IntelliJ build)target/ (Maven build)
Who creates itIDEA's built-in builderMaven plugins
Triggered byBuild Project / Runmvn compile / mvn package
Layoutout/production/<module>/target/classes/
DeletableYes, rebuilt on demandYes, emptied by mvn clean
Common trapDeleting out without rebuilding → class not foundEditing code without clean → you run the old build
44 / 132
Section
4.2 Two builders, two copies of your bytecode
45 / 132

That last row of the table is the hardest one to notice yourself. This animation shows how two copies of your bytecode come to coexist — watch frame 5: what Run reads and what the shell reads may not be the same file:

46 / 132
Animation
Animation · Two builders, two copies of your bytecode
Animation · Two builders, two copies of your bytecode
47 / 132

There is also a real number hiding in IDEA's build: its builder runs in a separate process that gets 700 MiB by default. As the project grows and annotation processors pile on, the build output starts showing java.lang.OutOfMemoryError: Java heap space — note that it crashes in the build phase, while your program itself runs perfectly. Drag that number:

48 / 132
Tuner
TunerHow much memory does the build process get
The default 700 MiB is the number on the slider. Stay at 700 first to see what a small project does, then drag it up by module count; apply with Build → Rebuild to feel the difference
Settings → Build → Compiler → Shared build process heap size
700MiBNow 256 – 8192
Default 700 MiB: enough for single-module exercises
  • Course examples and one or two modules never reach the ceiling
  • When they do, the symptom is that line in the build output: java.lang.OutOfMemoryError: Java heap space
  • The build crashes, not the runtime — the program you launched is fine, which is why people fix the wrong thing
  • No machine restart needed: this number exists exactly for that case
Build memory pressure35%
Build time70%
Order of reasoning: is it the build or the runtime that crashed? Then move up one step per module count — enough is enough.
49 / 132
Section
4.3 Incremental versus full: the two build buttons
50 / 132

Build Project vs Rebuild is equally worth remembering:

51 / 132
  • Build Project (Ctrl+F9): incremental, compiling only changed files — your everyday choice
  • Rebuild Project: wipes all output and recompiles everything — use it only when you suspect a stale cache; slow but clean
52 / 132
Trap

when you change code and still see old results, nine times out of ten the incremental build cache is stale. Build → Rebuild Project fixes it — no need to restart your machine.

53 / 132

Now spread that chain out as a single-step run. Six events on the left after you click Run, on the right the variables and the call stack as they change — pay attention to beats 2 and 4: the grey button in Section 11 comes from beat 2, and the package does not exist in Section 12 comes from beat 4:

54 / 132
Stepper
StepperStep by step: from clicking Run to the first printed line1 / 6
Six beats. Beat 3 decides whether you run new bytecode; beat 4 decides whether your imports are red
Code under debug
1Click the green Run triangle # it starts from a Run/Debug Configuration
2IDEA validates: SDK / module / main? # fail any of them and the button is grey
3Incremental compile of the changed files # into out/production or target/classes
4Assemble the classpath: module deps + jars # Use classpath of module decides the content
5Fork a JVM: java -cp ... Hello # this is where IDEA steps out
6Load the class, call Hello.main(String[]) # your code finally starts
Variables now
config sourceRun → Edit Configurations
existing configHello.main()
first clickcreates one automatically
Call stack
1click Run
1Your very first click silently created a run configuration. It is not a button state but a command line you can export and paste into a terminal — every strange behaviour later on can be explained by reading that line.
55 / 132
Section
5. Hands-on debugging: six moves you can learn today
56 / 132

Debugging is IDEA's real productivity engine. Press Shift+F9 to start in Debug mode — same effect as Run, except it stops at breakpoints.

57 / 132

Click in the gutter next to a line to place one; a red dot means the breakpoint is set. Then memorize this set:

58 / 132
Code
Codejava
public static int sum(int[] nums) {    int total = 0;    for (int i = 0; i < nums.length; i++) {        total += nums[i];      // ← set a conditional breakpoint here: i == 3    }    return total;}
Notes
  • Conditional breakpoint: right-click the breakpoint, set Condition to i == 3, and it stops only then — a lifesaver on the thousandth loop iteration
  • Step Over (F8): execute the current line without entering method calls
  • Step Into (F7): step into the called method
  • Step Out (Shift+F8): jump back out to the caller
  • Evaluate Expression (Alt+F8): a pop-up calculator that evaluates any expression live, e.g. nums.length
  • Watches: add variables to the watch list to see their latest value on every stop
59 / 132

Here is one rarely used but superb trick: while stopped you can double-click a variable in the Variables panel, press Enter, and change its value, then Resume. To test "what if this parameter were empty", you don't change and rerun the code — just change the value.

60 / 132
Tip

when debugging multithreaded code, don't chase threads with Step Over — they jump around. Use the breakpoint's Suspend: Thread setting instead, and add a log output (Breakpoint → More → Evaluate and log) to print traces without blocking the thread.

61 / 132
Section
6. Using Maven projects inside IDEA
62 / 132

Real projects are almost always Maven projects. Open one with File → Open and pick the directory containing pom.xml; IDEA recognizes it as a Maven project and imports it automatically.

63 / 132

After import a Maven tool window appears on the right. A few frequent actions to know:

64 / 132
  • Automatic sync: when pom.xml changes, a small icon appears at the top right prompting Reload; one click fetches the new dependencies
  • Reload All Maven Projects: the refresh button at the top-left of the Maven panel, equivalent to re-reading all poms and re-resolving dependencies
  • Yellow warnings: a yellow squiggle under a dependency usually means "this artifact is not in the local repo" or "the version is overridden by dependencyManagement"; hover for the explanation
65 / 132
Code
Codexml
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId>    <!-- Common cause of the yellow mark: the parent POM already manages the version via         dependencyManagement, so no version is needed here --></dependency>
Notes

Trap: when everything is red in IDEA yet mvn clean package clearly succeeds, IDEA's Maven index is usually broken. Run Maven panel → Reload All Maven Projects; if that fails, File → Invalidate Caches → Invalidate and Restart. Always trust the command-line build result — IDEA's red is only its own view.

66 / 132

The reverse reading matters just as much: every checkbox in File → New → Project ends up as a <dependency> in pom.xml. Tick them once and compare with the generated file, and you will know what IDEA wrote on your behalf — so that next time it writes nothing, you can do it yourself:

67 / 132
Generator
GeneratorWhat the IDEA wizard's checkboxes become in pom.xmlpom.xml2 / 7
Start from Web and Test as the baseline, then add DevTools and Lombok: notice devtools arrives optional and lombok arrives provided — two details the wizard never explains
Output
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.4</version> <!-- 版本由 BOM 统管,子依赖不写 version -->
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>demo-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>17</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Why each choice matters
parentInheriting 3.3.4 starter-parent means no spring-boot-starter-* needs a version; the moment someone adds an explicit version to one starter, that one wins — the most common source of dependency drift.
WebAnything that serves HTTP needs it: DispatcherServlet, embedded Tomcat and JSON mapping come inside this starter.
Testscope=test: @SpringBootTest, MockMvc and AssertJ live here; without it @Test is unresolved.
68 / 132
Section
7. Six beginner traps to dodge early
69 / 132
Table
SymptomRoot causeFix
Every Java class is red and cannot runProject SDK not configuredFile → Project Structure → SDK, pick a JDK
Chinese output is mojibakeFile encoding is GBK, not UTF-8Set everything to UTF-8 in Settings → File Encodings
package xxx does not correspond to the file pathPackage name mismatches the folder pathMark src as a Source Root, or fix the package name
Code changes simply don't take effectStale cache / stale outputInvalidate Caches and Restart or rebuild
Lombok @Data compiles but getters are missingThe Lombok plugin is not installedInstall Lombok in Plugins and enable annotation processing
Startup fails with Port 8080 was already in useA previous process never exitedKill the process, or change the port
70 / 132

The fastest way to find a port hog is one command:

71 / 132
Code
Codebash
# Windows: who is holding port 8080?netstat -ano | findstr :8080# macOS / Linuxlsof -i :8080
Notes
  • The trailing number is the process PID; end it via the task manager or taskkill /PID <pid> /F
  • Don't just reboot — that hides the problem and it returns next time

Warning: Settings → File Encodings only affects the current project. Set Project Encoding and Default encoding for properties files to UTF-8 too, and check Transparent native-to-ascii conversion, otherwise Chinese comments in application.properties still come out garbled.

72 / 132
Section
8. Shortcut cheat sheet
73 / 132
Table
ActionWindowsmacOS
Run / DebugShift+F10 / Shift+F9Ctrl+R / Ctrl+D
Build projectCtrl+F9Cmd+F9
Find anything (command palette)Ctrl+Shift+ACmd+Shift+A
Search files / classes globallyCtrl+Shift+NCmd+Shift+O
Generate code (getters, constructor)Alt+InsertCmd+N
Rename (safe refactor)Shift+F6Shift+F6
Reformat codeCtrl+Alt+LCmd+Opt+L
Go to definition / implementationsCtrl+B / Ctrl+Alt+BCmd+B / Cmd+Opt+B
Step in debuggingF8 / F7F8 / F7
The Alt key (multi-cursor, column select)Hold Alt and dragHold Opt and drag
74 / 132
Tip

don't memorize all of these at once. First make "run, debug, command palette, global search, generate code" muscle memory — that alone doubles your daily speed; look the rest up when needed.

75 / 132
Section
9. Decision card
76 / 132
Decision
Decisionon the team, everyone's IDEA window layout, font and indentation differ, and newcomers get their code rejected in review over "inconsistent formatting". How far should the team unify things?
77 / 132
Section
10. Hands-on labs: spread out the steps IDEA hides
78 / 132

The first lab is the animated version of Section 4: how many steps sit between saving and a live process. "Compile output" shows how target/classes gets filled; "hot reload" shows why editing one string does not need a restart; "debug" maps the six moves from Section 5 onto what happens inside the process:

79 / 132
Kernel lab
TeaVMFrom save to run in IDEA: four steps unpackedidle
Press build → run → reload → debug in order, and note who touches the disk and who touches memory
Scenario
Click “Run demo” to execute the AOT-compiled Java kernel right in your browser, step by step.
80 / 132

The second answers a more fundamental question: how does the JVM get your class into memory? The "class loading" step shows it resolving the fully qualified name (com.example.demo.Hello) into a path on disk — which is exactly where the Package ... does not correspond to the file path error in Section 12 comes from: a package name is not decoration, it is part of a path.

81 / 132
Kernel lab
TeaVMClass loading: how a fully qualified name becomes a disk pathidle
Cross-check with the package error in Section 12 to see the file shape the JVM expects
Scenario
Click “Run demo” to execute the AOT-compiled Java kernel right in your browser, step by step.
82 / 132

The third targets "my code is fine but it says class not found". On "ClassNotFoundException" you watch it walk each entry on the classpath; whenever target/classes is empty or stale, any java command ends up on this dead street:

83 / 132
Kernel lab
TeaVMWhy an uncompiled target/classes is guaranteed to crashidle
Then reread Section 7 to understand the IDE-versus-terminal path difference
Scenario
Click “Run demo” to execute the AOT-compiled Java kernel right in your browser, step by step.
84 / 132

The fourth prepares you for the next article: a Spring Boot startup has several more steps than a bare main. A Runner is Boot's hook for "do something once the app is up" (CommandLineRunner / ApplicationRunner), and the last experiment shows how to actually read that wall of text when startup fails:

85 / 132
Kernel lab
TeaVMSpringApplication.run(): the eight steps and the Runnersidle
Start with full for the overview, then runners to see where your own code gets called
Scenario
Click “Run demo” to execute the AOT-compiled Java kernel right in your browser, step by step.
86 / 132
Kernel lab
TeaVMReading a failed start: walk up to the first Caused byidle
The deepest caused-by line is the real root cause
Scenario
Click “Run demo” to execute the AOT-compiled Java kernel right in your browser, step by step.
87 / 132

The fifth lab covers the most infuriating class of problem in this chapter: works in the IDE, dies in the terminal — because the two are not using the same JDK at all. Open "who wins" to watch the shell walk PATH in order, then "several JDKs installed" to see IDEA's Project SDK and the terminal's java drift apart:

88 / 132
Kernel lab
TeaVMThe JDK inside IDEA and the JDK in your terminal may be different filesidle
Try which first, then multi, and compare with the last row of Section 12
Scenario
Click “Run demo” to execute the AOT-compiled Java kernel right in your browser, step by step.
89 / 132
Kernel lab
TeaVMHow to verify: the Java version printed by mvn -v is the one building youidle
This mode is why the rule is 'trust the mvn result, not the IDE colour'
Scenario
Click “Run demo” to execute the AOT-compiled Java kernel right in your browser, step by step.
90 / 132

Time to type. This console is wired to the same in-browser kernel and every reply is computed there — start with lab idebuild build, then work down:

91 / 132
Console
92 / 132
Tip

run lab idebuild run and lab idebuild debug back to back — the two outputs differ by a single JVM parameter. That one parameter is what makes all six debugging moves from Section 5 possible.

93 / 132

And keep this comparison in mind. The left column is what beginners do every day, the right column is the same task done correctly — the difference is not speed but whether the tool fools you:

94 / 132
Diagram
Figure · Right habits vs wrong ones in IDEA
Figure · Right habits vs wrong ones in IDEA
95 / 132
Section
11. Sandbox: the Run button is grey — whose fault is it?
96 / 132

A greyed-out Run triangle never means "IDEA is broken"; it means IDEA has decided pressing it would certainly fail. Pick the module state on the left and the SDK state on the right, and the panel tells you exactly where to click to recover:

97 / 132
Diagram
Figure · The five checks before the Run greys out
Figure · The five checks before the Run greys out
98 / 132
Animation
Animation · Where Run and Debug diverge
Animation · Where Run and Debug diverge
99 / 132
Sandbox
SandboxWhy the Run button is grey
Result
No matching result
100 / 132
Note

the easiest cell to miss is no-main — IDEA only draws a green triangle for an entry point it recognises. The main signature is a hard contract: public, static, void, parameter String[]; fail any one of the four and there is no Run gutter icon.

101 / 132
Section
12. Common errors, searchable by exact wording
102 / 132
Table
Error text (excerpt)Real cause30-second fixDig deeper in
Class 'Hello' is public, should be declared in a file named 'Hello.java'Public class name and file name differ (case counts as a difference)Rename the file, not the class; they must match character by character#1 Section 4
Package com.example.demo does not correspond to the file path 'com/example/hello'Folder case disagrees with the package, or src is not marked as Sources RootRight-click the folder → Mark Directory as → Sources Root, then re-check each package levelSection 2 · sandbox above
Exception in thread "main" java.lang.ClassNotFoundException: com.example.demo.Hello (fails in the terminal, fine in IDEA)target/classes was never compiled, or your hand-typed -cp omits the output directoryRun mvn compile (or Ctrl+F9 in IDEA), then java -cp target/classes com.example.demo.Hello#2 Maven lifecycles
java: 程序包 xxx 不存在 / Cannot resolve symbol 'springframework'pom changed but was never Reloaded, so dependencies are not on the module classpathMaven panel → Reload All Maven Projects; if still broken, File → Invalidate CachesSection 6
Run / Debug buttons greyed outNo Project SDK, no recognised main, or the module is not marked as a source rootWork through the three cases in the Section 11 sandbox; the usual one is Project Structure → SDKSection 11
Shift+F10 triggers something else instead of RunAnother program grabbed the key (NVIDIA driver hotkey, input method, screenshot tool)Resign it under Settings → Keymap, searching Run…; or confirm the config is fine by clicking the gutter triangleSection 8 hotkey trap
Console shows mojibake like 锟斤拷 or ??????Source encoding, compiler -encoding and console charset disagreeSet all of Settings → File Encodings to UTF-8; add -Dfile.encoding=UTF-8 to VM options#35 logging
Port 8080 was already in useThe previous process is still alive and holding the port`netstat -ano \findstr :8080 for the PID, then taskkill /PID <pid> /F`Section 7
103 / 132
Trap

ClassNotFoundException almost never appears inside IDEA but constantly appears in the terminal — because IDEA runs against its own build output (possibly out/production/...) while your hand-typed command points at target/classes. Two output directories drifting apart is the root of "this class is found sometimes and not others".

104 / 132

That trap deserves a real stack to close it. Notice the guilty frame is not the top line, and not the Exception in thread sentence either:

105 / 132
Triage
Error triageClassNotFoundException: com.example.demo.Hello
Runs fine in IDEA, but the terminal's java says it cannot find that class

You compiled with Ctrl+F9 and Run works; then you type java -cp target/classes com.example.demo.Hello in the terminal and it throws.

Exception in thread "main" java.lang.ClassNotFoundException: com.example.demo.Hello
at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:445)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:592)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:525)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:534)
at sun.launcher.LauncherHelper.loadMainClass(LauncherHelper.java:802)
Click the frame you blame — guessing is allowed
No pressure: guess the exception first, then which line actually made the call.
106 / 132
Section
13. Check yourself
107 / 132
Quiz
Check yourselfYou change one printed line in Hello.java inside IDEA, press Run, and the console still shows the old text. Which explanation is impossible?
Pick one — you get feedback right away
108 / 132
Quiz
Check yourselfA class starts with `package com.example.demo;` but the file sits at `src/Hello.java`, and `src` is not marked as a Sources Root. What happens?
Pick one — you get feedback right away
109 / 132
Section
14. Practice in three levels
110 / 132
Section
Level 1 · Follow along
111 / 132

Goal: reproduce and repair the three classic "IDEA tricked me" scenes.

112 / 132
java
package com.example.demo;public class DebugLab {    public static int sum(int[] nums) {        int total = 0;        for (int i = 0; i < nums.length; i++) {            total += nums[i];          // ← breakpoint here, condition i == 3        }        return total;    }    public static void main(String[] args) {        int[] data = {1, 2, 3, 4, 5, 6};        int result = sum(data);        System.out.println("sum = " + result);   // ← breakpoint here, then set result to 0        System.out.println("result * 2 = " + (result * 2));    }}
113 / 132

Do these three things in order, writing one sentence of observation for each:

114 / 132
  1. Put a conditional breakpoint on line 8 with condition i == 3, start with Shift+F9, and confirm it stops only on the fourth iteration.
  2. Stopped at line 15, double-click result in the Variables panel, change it to 0, then Resume. Expected output: the second line prints result * 2 = 0 — proof that editing a value really changes execution.
  3. With Evaluate Expression (Alt+F8), compute data.length + result without touching the code, then evaluate nums[0] outside the loop context and observe what exception surfaces.
115 / 132

Done when: you can say why a conditional breakpoint beats println debugging, and how changing a runtime value differs from editing code and rerunning.

116 / 132
Section
Level 2 · Variants
117 / 132

Three small edits, each reproducing one frequent failure — the skill being practised is spotting which layer broke:

118 / 132
  1. Keep package com.example.demo; but move the file to the root of src. You will observe IDEA complaining that the package does not match the path, and the "fully qualified name → disk path" mapping from the Section 10 lab breaking on the spot.
  2. Delete the whole out or target directory, do not Build, and run java -cp target/classes com.example.demo.DebugLab from the terminal. You will observe ClassNotFoundException; one mvn compile or Ctrl+F9 restores it.
  3. Turn off auto-save under Settings → Appearance & Behavior → System Settings, edit a print line without pressing Ctrl+S, then hit Run. You will observe IDEA's prompt, and why it synchronises changes to disk before compiling.
119 / 132

Tip: after variant 3 you will internalise that "save ≠ compile ≠ run" are three separate events.

120 / 132
Section
Level 3 · Build something
121 / 132

Create a two-module Maven project that links this article with #2:

122 / 132
text
lab-ide/                 <- parent pom, packaging=pom├── lab-core/            <- SumUtil plus one custom exception└── lab-app/             <- depends on lab-core, contains main and a CommandLineRunner
123 / 132

Requirements: ① import it with File → Open on the parent directory (not New Project) and confirm two modules appear in the Maven panel; ② leave a deliberate null dereference in lab-app's main and use an exception breakpoint (Run → View Breakpoints → Java Exception Breakpoints) so IDEA stops at the throw site instead of you stepping around looking for it; ③ add a CommandLineRunner printing one statistics line after startup; ④ run it once with Run and once with Debug and write down three concrete differences; ⑤ finally launch it manually from the terminal with java -cp and notice what IDEA had been assembling for you.

124 / 132

Acceptance checklist: mvn clean install is green; Debug halts exactly at the exception; the manual java -cp launch also works — meaning you genuinely know how that classpath was built.

125 / 132
Section
15. Self-check
126 / 132
Self-check

among Project / Module / SDK / Artifact, which decides "which JDK do I use" and which decides "what do I package into"?

127 / 132
Self-check

who writes out/production/<module> and who writes target/classes? Why do they drift apart?

128 / 132
Self-check

Run and Debug share the same chain except for one extra step — which step, what capability does it buy, and at what cost?

129 / 132
Self-check

who receives Program arguments and who receives VM options? What goes wrong if you put --spring.profiles.active=dev in the wrong box?

130 / 132
Self-check

IDEA shows red everywhere yet mvn clean package succeeds. Whom do you believe, and why?

131 / 132
Mnemonic

save belongs to the disk, compile to bytecode, run to the classpath, debug to breakpoints — four layers, four switches; when something breaks, first ask which layer you are standing in.

132 / 132
Summary

this article straightened out IDEA's three main threads — structure (the layered relationship of Project / Module / SDK), running (incremental compile into out/ or target/, then a JVM loads and runs main), and debugging (breakpoints, stepping, evaluation, changing values). Combined with dodging the six beginner traps, your development environment is now stable and you can focus on writing code.