Git for Java Projects

Updated · 9 min read
mediumGit 2.53gitjavamavengradlegitignoregitattributesci

A well-set-up Java repository contains exactly what another developer, or a CI server, needs to build the project from a fresh clone, and nothing that the build produces. For Maven and Gradle projects, that means the source code, the build files (pom.xml or build.gradle.kts), the build wrapper scripts, a .gitignore for build output and IDE files, and a .gitattributes that keeps line endings consistent between Windows, macOS and Linux. The Java course's lesson Git Basics for Java Projects introduces the idea; this page sets it up completely.

Think of a recipe box handed to a new cook. It should hold the recipes and the list of tools, not yesterday's leftovers or the previous cook's personal notes.

What Belongs in a Java Repository

CommitDon't commit
src/main/java, src/test/java, src/main/resourcestarget/ (Maven) and build/ (Gradle)
pom.xml, or build.gradle.kts and settings.gradle.kts.gradle/ (Gradle's local cache)
mvnw, mvnw.cmd, .mvn/wrapper/.idea/, *.iml, out/ (IntelliJ IDEA)
gradlew, gradlew.bat, gradle/wrapper/.vscode/ (unless the team shares settings), .settings/, .project, .classpath (Eclipse)
.gitignore, .gitattributes, README.md*.class, *.jar, *.war that the build makes
CI workflow files, such as .github/workflows/ci.ymlLocal settings with passwords (application-local.properties, .env)
Commit the sources and the wrapper, ignore the build

Example 1: The .gitignore

Navika starts a Maven project for the Fee Tracker. Build output and IDE files already exist on her computer:

Terminal
mkdir fee-tracker
cd fee-tracker
git init --quiet
mkdir -p src/main/java/school target/classes .idea .mvn/wrapper
echo "public class FeeCalculator {}" > src/main/java/school/FeeCalculator.java
echo "<project/>" > pom.xml
echo "binary" > target/classes/FeeCalculator.class
echo "<module/>" > fee-tracker.iml
echo "<project/>" > .idea/workspace.xml
printf '#!/bin/sh\necho "Maven wrapper"\n' > mvnw
echo "@echo Maven wrapper" > mvnw.cmd
echo "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip" > .mvn/wrapper/maven-wrapper.properties
cat > .gitignore <<'EOF'
# Build output
target/
build/
.gradle/
*.class
 
# IntelliJ IDEA, Eclipse and VS Code
.idea/
*.iml
out/
.settings/
.project
.classpath
.vscode/
 
# Operating systems
.DS_Store
Thumbs.db
 
# Local settings and secrets
.env
application-local.properties
EOF
git add .
git status --short
Output
A  .gitignore
A  .mvn/wrapper/maven-wrapper.properties
A  mvnw
A  mvnw.cmd
A  pom.xml
A  src/main/java/school/FeeCalculator.java

Explanation: the staged files are exactly the source, the build file, the wrapper scripts with their settings file, and .gitignore itself. target/, fee-tracker.iml and .idea/ were left out by .gitignore. Ignoring all of .idea/ is the simplest rule; some teams commit a few shared files from it, such as code style settings, with rules like !.idea/codeStyles/.

Example 2: The Wrapper and Its Executable Bit

The Maven Wrapper (mvnw) and Gradle Wrapper (gradlew) are small scripts that download the exact build tool version the project uses, so nobody needs to install Maven or Gradle. Commit them. On macOS and Linux, they must be executable. Files created on Windows, or by some tools, don't have that permission:

Terminal
git ls-files --stage mvnw
Output
100644 982b291a149adf8362b7a43d8cc549032ad8d3d3 0	mvnw

Explanation: the mode 100644 means a normal, non-executable file. A teammate on Linux, or a CI server, would get Permission denied when running ./mvnw test. Git stores the executable bit, so set it in the index. This works on Windows too, where there is no chmod:

Terminal
git update-index --chmod=+x mvnw
git ls-files --stage mvnw
git commit --quiet -m "Set up the Maven project"
Output
100755 982b291a149adf8362b7a43d8cc549032ad8d3d3 0	mvnw

100755 is an executable file. Every clone now gets mvnw ready to run. Do the same for gradlew.

Example 3: .gitattributes for Java

Line endings cause problems in Java projects in two places: shell scripts such as mvnw and gradlew break with Windows line endings (/bin/sh^M: bad interpreter), and Windows batch files (mvnw.cmd, gradlew.bat) expect them. Binary files, such as a JAR, must never be converted. A .gitattributes file settles this for everyone, whatever their core.autocrlf setting (see "Git .gitattributes and Line Endings"):

Terminal
cat > .gitattributes <<'EOF'
# Normalize text files to LF in the repository
* text=auto
 
*.java text diff=java
*.properties text
*.xml text
*.kts text
 
# Shell scripts must keep LF, batch files need CRLF
mvnw text eol=lf
gradlew text eol=lf
*.sh text eol=lf
*.cmd text eol=crlf
*.bat text eol=crlf
 
# Never convert binary files
*.jar binary
*.png binary
EOF
git check-attr eol -- mvnw mvnw.cmd
git check-attr diff -- src/main/java/school/FeeCalculator.java
git add .gitattributes
git commit --quiet -m "Add line ending rules for Java"
Output
mvnw: eol: lf
mvnw.cmd: eol: crlf
src/main/java/school/FeeCalculator.java: diff: java

Explanation: git check-attr confirms the rules: mvnw is always checked out with LF and mvnw.cmd with CRLF. diff=java makes Git use its Java rules to find the enclosing method or class for the @@ line of each diff hunk. binary stops conversion and diffs for JAR files. The Gradle Wrapper's own gradle wrapper task writes similar lines for gradlew and gradlew.bat.

Example 4: Running the Tests on Every Pull Request

A CI workflow builds and tests every push and pull request (see "Git and CI/CD"). For GitHub Actions, the file is .github/workflows/ci.yml:

.github/workflows/ci.yml
name: CI
on:
  push:
    branches: [main]
  pull_request:
 
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-java@v5
        with:
          distribution: temurin
          java-version: 25
          cache: maven
      - run: ./mvnw --batch-mode verify

Explanation: actions/checkout clones the repository, actions/setup-java installs Java 25 and caches Maven's downloads between runs, and ./mvnw verify compiles, runs the unit tests and any checks configured in pom.xml. For Gradle, use cache: gradle and ./gradlew build. Turn on branch protection (see "Git Best Practices") so that a pull request can only be merged when this job passes. GitLab (.gitlab-ci.yml) and Bitbucket (bitbucket-pipelines.yml) run the same command in their own file formats.

Terminal
mkdir -p .github/workflows
printf "%s\n" "name: CI" "on: [push, pull_request]" > .github/workflows/ci.yml
git add .github
git commit --quiet -m "Run the tests in CI"
git ls-files
Output
.gitattributes
.github/workflows/ci.yml
.gitignore
.mvn/wrapper/maven-wrapper.properties
mvnw
mvnw.cmd
pom.xml
src/main/java/school/FeeCalculator.java

The repository now holds everything a fresh clone needs, and nothing more.

Common Mistakes

Committing target/ or build/. The repository grows with every build, and merges conflict on generated files. If it already happened, run git rm -r --cached target, add it to .gitignore and commit (see "Common Git Errors: Setup and Access").

Not committing the wrapper. Every developer then needs the right Maven or Gradle version installed. Commit mvnw, mvnw.cmd and .mvn/wrapper/ (or the Gradle equivalents).

./mvnw: Permission denied in CI. The executable bit isn't stored. Run git update-index --chmod=+x mvnw and commit.

/bin/sh^M: bad interpreter. The script has Windows line endings. Add mvnw text eol=lf to .gitattributes, then git add --renormalize . and commit.

Committing IDE files. .idea/workspace.xml changes constantly and contains local paths. Ignore it.

Under the Hood

Git records only two permission modes for files: 100644 (normal) and 100755 (executable). On macOS and Linux, git add reads the file's permission from disk. On Windows, where files have no executable bit, Git keeps the mode already in the index (core.fileMode is false), which is why git update-index --chmod=+x is the reliable way to set it from any computer. Line-ending conversion happens when files move between the repository and the working folder: with text, Git stores LF in the repository and writes the eol you chose on checkout. diff=java selects a built-in pattern that recognizes Java method and class lines, so hunk headers read @@ ... @@ public int lateFee(int days).

Interview Corner

What should a Java project's .gitignore contain?

Build output (target/, build/, .gradle/, *.class), IDE files (.idea/, *.iml, out/, Eclipse and VS Code folders), operating system files (.DS_Store) and local settings with secrets.

Should you commit the Maven or Gradle wrapper?

Yes. mvnw/gradlew, their Windows scripts and the wrapper folder let anyone build with the exact tool version without installing it. Make the shell scripts executable with git update-index --chmod=+x.

How do you fix ./gradlew: Permission denied on a CI server?

Set the executable bit in Git: git update-index --chmod=+x gradlew, commit and push.

Why use .gitattributes in a Java project?

To keep line endings consistent: LF for shell scripts such as mvnw, CRLF for .cmd and .bat, normalized LF for source files, and no conversion for binary files such as JARs.

Practice

Challenge: the Gradle wrapper. Add a gradlew script, make it executable in Git, and give it LF line endings in .gitattributes, then print its mode and its eol attribute.

What does Git print? Before you open the solution, decide which mode and which eol value Git shows.

Show solution
Terminal
printf '#!/bin/sh\necho "Gradle wrapper"\n' > gradlew
git add gradlew
git update-index --chmod=+x gradlew
git ls-files --stage gradlew
git check-attr eol -- gradlew
Output
100755 175d77cf3ef9bfd7b479119893dfd2671698bbad 0	gradlew
gradlew: eol: lf

Mode 100755 (executable), and eol: lf, because the .gitattributes file already has the line gradlew text eol=lf.

Checkpoint. Put a Maven project on GitHub with a correct .gitignore, .gitattributes, an executable mvnw and a CI workflow that runs ./mvnw verify, then open a pull request and watch the check run.

Quick check: Git for Java projects

4 questions
1Which folder should a Maven project ignore?
2A teammate gets Permission denied running ./mvnw. What fixes it for everyone?
3Which .gitattributes line keeps gradlew working on Linux when edited on Windows?
4What does diff=java do?

Key Takeaways

Quick reference

CommandIt is used to
git update-index --chmod=+x mvnwMake a script executable in Git
git ls-files --stage <file>Show a file's mode
git check-attr eol -- <file>Check a line-ending rule
git rm -r --cached targetStop tracking build output
git add --renormalize .Apply new line-ending rules to tracked files

Was this tutorial helpful?

Lesson 100 of 106