Git records changes to the authored files of a Java project. It helps you review edits, recover earlier versions, and collaborate, but it does not replace a build or test suite. A useful Java repository contains source, build configuration, documented setup, and selected project-tool files. It normally excludes compiled class files and generated build directories. This lesson follows a small local change through status, diff, staging, and a commit without requiring you to publish a repository or send anything to another person.
Identify authored files and generated output
For a Maven project, commit pom.xml, src, documentation, and appropriate wrapper files. Exclude target, compiled .class files, and local caches that can be recreated. For Gradle, build is normally generated output. Some editor settings can be shared if they express team conventions, while personal paths and machine-specific state should remain local. An ignore file prevents untracked matches from appearing normally; it does not automatically remove a file already tracked by Git.
Initialize and inspect a local repository
git init creates the local repository metadata. git status shows untracked, staged, and modified files. Before committing, read that list carefully to ensure secrets and generated artifacts are absent. A Git repository does not imply a remote server or a published project. You can use its history locally while learning. Record author identity through the appropriate Git configuration only when needed; do not invent a collaborator's identity for your commits.
Review the actual patch
git diff shows unstaged changes, while git diff --staged shows the patch selected for the next commit. This separation matters because a file can contain both staged and unstaged edits. Read the selected patch as if you were reviewing someone else's code. A successful Java build does not prove every changed file belongs in the commit. Keep unrelated experiments out so the history explains one coherent improvement.
Stage deliberately and commit one change
git add selects file content for the staging area. Adding named paths is often easier to review than adding everything blindly. git commit records that staged snapshot with a message explaining the behavior or purpose. A commit should include any required tests and build configuration for its change. Avoid messages such as update when a concrete message like handle empty customer names would explain what a later reader can expect.
Use branches for isolated work
A branch identifies a line of development and lets you work on a change without immediately moving another branch's tip. git switch -c creates and selects a new branch. Branching does not create a different copy of every uncommitted file, so check status before switching contexts. When collaborating, follow the project's review and merge workflow. Do not force-push shared history simply to make a local log look tidier.
Verify a build from tracked inputs
After a change, run the project's documented build and tests before treating the commit as ready. A fresh checkout should rebuild from tracked source and declared dependencies without your target directory. Keep credentials and environment-specific configuration outside versioned source, using documented placeholders when appropriate. Git protects recorded history, not files you never committed, and it is not a substitute for securely managing secrets or backing up unrelated local work.
Practice tasks and checks
Initialize a small local Maven repository, add suitable ignore rules, and inspect status before your first commit. Compile a source file and confirm the .class file is not offered as an untracked authored file. Change one validation rule and add its test. Read both the unstaged diff and the staged diff, then commit only that coherent change. Next, create a feature branch and make another small edit without publishing it. Explain which files belong in the repository and which a collaborator can regenerate. Finally, inspect a sample configuration for credentials before staging it. The goal is a reviewable, reproducible local history, not a collection of build artifacts or an accidental publication.
Java Summary
- Review the staged diff before recording a commit.
- Commit reproducible source and configuration rather than generated classes.
- A local commit does not publish a repository.
- Continue with repeatable builds when these examples are clear.
Java Examples
Each example shows the code, the output it produces and what each part does.
Create Java-appropriate ignore rules
Use the following text commands or configuration.
What to expect: Generated build directories and local .env files stay untracked unless already tracked.
Save these sample rules in .gitignore at the repository root and adapt them to the actual project. target is Maven output and build is common Gradle output. The .env rule reflects a project that keeps local credentials there; still inspect other configuration files for secrets. Do not ignore every JAR automatically if the repository intentionally contains a required binary fixture or documented tool artifact. Ignore rules express repository policy, not universal Java syntax.
target/
build/
*.class
.env
Review and stage a small change
Use the following shell commands or configuration.
What to expect: Git records the staged snapshot if repository identity and all required paths are configured.
Run these commands inside an initialized project, using only paths that actually exist. status and diff are read-only inspection steps. add stages selected files, and the staged diff lets you review the exact snapshot before commit. The message should fit your real change rather than being copied uncritically. A commit is local; it does not publish the repository or send a notification to another person.
git status
git diff
git add pom.xml src .gitignore README.md
git diff --staged
git commit -m "Add validated delivery fee calculation"Confirm source still builds independently
Save this program as TrackedSourceCheck.java. Compile it with javac TrackedSourceCheck.java and run it with java TrackedSourceCheck.
Expected output:
Commit this source as an authored file, compile it, and confirm its generated .class file is ignored by the sample rule. Another checkout can reproduce the class file from the source and JDK. The print itself is not a Git operation; it is a minimal artifact whose source and generated output are easy to distinguish. Real projects should replace this demonstration with their documented build and test commands.
public class TrackedSourceCheck {
public static void main(String[] args) {
System.out.println("Source can be rebuilt");
}
}Source can be rebuiltJava FAQ
Does .gitignore untrack a file already committed?
No. Ignore rules mainly affect untracked files. Removing a generated file from tracking requires an explicit reviewed repository change; do not assume adding its name to .gitignore erases it from history.
Is a commit the same as publishing?
No. A commit records a local snapshot. Sending history to a remote involves separate operations and the project's collaboration policy. Learn local review and commit steps before changing shared branches.
How do I write a good commit message?
Start with a short summary line in the imperative, such as "Add discount for ten or more items", under about 50 to 70 characters. If needed, leave a blank line and explain why the change was made. Commit one logical change at a time so each message can describe it honestly.
How do I undo a commit?
If the commit has been shared, use git revert <commit>, which adds a new commit that reverses it without rewriting history. For a local commit nobody else has, git reset can move the branch back, but read its options first, because --hard also discards uncommitted work.
What if I commit a password or API key by mistake?
Treat the secret as exposed: revoke or rotate it immediately. Deleting it in a new commit isn't enough, because it stays in the history and in any clones. Keep secrets in environment variables or a secrets manager, and add local config files to .gitignore before the first commit.
Java Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Which command shows the patch selected for the next commit?
Which directory is normally generated Maven output?
Java Quiz
2 questions to check what you learned.
What does git add do?
- Stages selected file content
- Compiles Java source
- Publishes every branch
What makes a commit easier to review?
- One coherent change with relevant validation
- Every unrelated experiment at once
- Only generated class files