Java • Getting Started and Tooling

Git Commits — Commit code changes with meaningful messages (conceptual workflow)

Learn how developers save snapshots of their code and write clear messages that explain every change.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

Imagine working on a group essay where everyone edits the same Google Doc at once. Someone deletes a paragraph you liked, another person overwrites your changes, and nobody can remember what the document looked like yesterday. This frustrating scenario is exactly the kind of problem that programmers faced for decades before modern version control systems came along. In the world of software development, tracking changes to code is critical — and the commit is the fundamental unit that makes this tracking possible.

Early programmers saved copies of files manually, naming them things like project_v1.java, project_v2_FINAL.java, and project_v2_FINAL_REAL.java. As projects grew larger and teams bigger, this approach fell apart completely. The solution was to build dedicated tools that could record the history of every change, who made it, and why. This evolution led to Git, which revolutionized how we save and describe our work.

1972 • SCCS — Source Code Control System

Bell Labs created one of the first version control tools, allowing programmers to track changes to individual files one at a time.

1986 • CVS — Concurrent Versions System

CVS introduced the idea of multiple developers working on the same project simultaneously, using a central server to store all file history.

2000 • Subversion (SVN)

SVN improved on CVS by tracking entire directories instead of individual files and supporting atomic commits — changes that either fully succeed or fully fail.

2005 • Git Created by Linus Torvalds

Linus Torvalds, creator of Linux, built Git as a distributed version control system where every developer has a full copy of the project history on their own machine.

2008 • GitHub Launches

GitHub provided a web platform for hosting Git repositories, making collaboration and open source development accessible to millions of developers worldwide.

Today, Git is the dominant version control tool used by professional developers, open source communities, and students learning to code. At the heart of Git lies a simple but powerful concept: the commit. Understanding what a commit is, how to create one, and how to write a meaningful commit message will make you a better programmer and a better collaborator. So what exactly happens when you 'commit' your code?

SECTION 2

Core Principles of Git Commits

A Git commit is a snapshot of your entire project at a specific moment in time. When you commit, Git records the state of every tracked file, attaches a message you write, and stamps it with a unique identifier. Think of each commit as a save point in a video game — you can always go back to it if something goes wrong later. The following core principles govern how commits work and why they matter.

1

Snapshot, Not a Diff

Each commit stores a complete picture of your project files at that moment. Git is smart enough to avoid duplicating unchanged files, but conceptually every commit is a full snapshot you could restore independently.
2

The Staging Area

Before you commit, you choose exactly which changed files to include using git add. This staging step lets you group related changes together into one logical commit instead of saving everything at once.
3

Meaningful Messages

Every commit requires a message describing what changed and why. A good message helps your future self (and teammates) understand the purpose of each change without reading every line of code.
4

Unique Hash Identifiers

Git assigns each commit a unique 40-character hexadecimal ID (called a SHA-1 hash) like a1b2c3d.... This ensures every commit in the world is uniquely identifiable and tamper-proof.
5

Immutable History

Once a commit is created, it cannot be secretly altered. Git's design ensures that any change to a commit's content would produce a completely different hash, making the project's history trustworthy and auditable.
✦

KEY TAKEAWAY

Think of Git commits like entries in a detailed lab notebook. Each entry records exactly what experiment you ran (the code changes), when you ran it (the timestamp), and your notes about what happened (the commit message). Just as a scientist wouldn't write 'did stuff' in their lab notebook, a programmer shouldn't write vague commit messages. The notebook only helps you if each entry is clear and specific.

SECTION 3

The Git Commit Workflow — Visual Explanation

The process of creating a Git commit involves three key areas: the working directory (where you edit files), the staging area (where you prepare changes), and the repository (where committed snapshots are permanently stored). The diagram below shows how your changes flow through these three zones as you create a commit.

WORKING DIRECTORY(Your project files)Main.java ✏️Helper.java ✏️style.css ✏️notes.txt (untracked)STAGING AREA(Ready to commit)Main.java ✔Helper.java ✔Only staged filesgo into the commitREPOSITORY(Permanent history)Commit a1b2c3d"Add login validation"2 files | Jan 15, 2025Commit e4f5g6hPrevious commit...Commit x7y8z9wgit addgit commitThe Three Zones of Git: Edit → Stage → CommitFiles flow left to right as you prepare and save your changes
The diagram shows the three zones of Git. You edit files in the working directory, select specific files for the next commit using git add to move them into the staging area, and then run git commit to permanently record them in the repository. Notice that untracked files like notes.txt stay in the working directory and are ignored by Git.

This three-zone workflow is what gives Git its power and flexibility. Unlike just hitting "save" in a word processor, you get to carefully choose which changes belong together in a single commit. For example, if you fixed a bug in Main.java and also started a new feature in style.css, you can stage and commit the bug fix first, then stage and commit the new feature separately. This keeps your project history clean and easy to follow.

SECTION 4

How Commits Work Under the Hood

When you run git commit -m "Your message here", several things happen behind the scenes. Git packages all the staged changes into a commit object — a data structure that contains four essential pieces of information. Understanding these pieces helps you appreciate why Git is so reliable and why your commit messages matter so much.

Anatomy of a Commit Object

  • Tree — A reference to the snapshot of all tracked files at the moment of the commit. This is the actual content of your project.
  • Parent — A pointer to the previous commit, forming a chain of history. The very first commit in a project has no parent.
  • Author & Timestamp — Your name, email, and the exact date and time the commit was created, so the team knows who made each change.
  • Message — The human-readable description you write to explain the purpose of the change.

The Commit Command Sequence

In a typical Java project, the workflow looks like this. First, you write or modify your Java source files. Then, you use git status to see which files have changed. Next, you run git add to stage the files you want. Finally, you execute git commit -m "message" to record those staged changes permanently.

CommandWhat It DoesExample
git statusShows which files are modified, staged, or untrackedgit status
git add <file>Moves a specific file to the staging areagit add Main.java
git add .Stages all changed files in the current directorygit add .
git commit -mCreates a commit with an inline messagegit commit -m "Fix null pointer in login"
git logDisplays the commit history with hashes, authors, and messagesgit log --oneline

Essential Git commands for the commit workflow

💡

Pro Tip

Use git diff before staging to review exactly what changed in your files. This helps you write a more accurate commit message because you can see every addition, deletion, and modification before committing.

SECTION 5

Writing Meaningful Commit Messages

Writing good commit messages is one of the most underrated skills in programming. A well-crafted message transforms your project history from a confusing list of random changes into a clear story of your project's development. Professional development teams often have strict guidelines about commit messages because the quality of messages directly affects how efficiently the team can work together.

Good vs. Bad Commit Messages❌ BAD MESSAGESa1b2c3d"fixed stuff"d4e5f6g"update"h7i8j9k"asdfghjkl"l0m1n2o"changes"Vague • No context • UnhelpfulYou won't remember what these mean😰 "Which commit broke the login?"✅ GOOD MESSAGESa1b2c3d"Fix null pointer in login validation"d4e5f6g"Add email format check to signup form"h7i8j9k"Remove unused import in Calculator"l0m1n2o"Refactor gradeAvg() for readability"Specific • Action-oriented • ClearFuture you will be grateful😊 "Commit a1b2c3d fixed the login!"
The left column shows vague, unhelpful messages that give no context about what actually changed. The right column shows specific, action-oriented messages that start with a verb and clearly describe the purpose of each change. When you need to find a specific change six months later, good messages are the difference between a 30-second search and a 30-minute headache.

Rules for Great Commit Messages

  • ✓ Start with an imperative verb — Write "Add feature" not "Added feature" or "Adding feature." Think of it as completing the sentence: "If applied, this commit will _____."
  • ✓ Keep the subject line under 50 characters — Short messages display well in Git logs and on GitHub. If you need more detail, add a blank line then a longer description body.
  • ✓ Explain what and why, not how — The code itself shows how the change was made. Your message should explain what the change accomplishes and why it was necessary.
  • ✓ One logical change per commit — Don't mix a bug fix, a new feature, and a formatting change in a single commit. Make separate commits for each so the history stays clean.
  • ✓ Capitalize the first word — Treat it like a sentence. Write "Fix" not "fix." This keeps your log looking consistent and professional.

SECTION 6

Worked Example — Committing a Java Code Change

Let's walk through a realistic scenario. Suppose you're building a simple Java calculator program and you've just added a new method that calculates the average of an array of grades. Here's exactly how you would stage and commit that change with a meaningful message.

Committing a New Method to a Java Project

  1. 1

    Step 1 — Make Your Code Change

    You open Calculator.java and add a new method called calculateAverage(double[] grades) that loops through an array, sums the values, and returns the mean. You save the file in your editor.
  2. 2

    Step 2 — Check the Status

    In your terminal, navigate to the project directory and run git status. Git responds by showing that Calculator.java is listed under "Changes not staged for commit" in red text. This means Git knows the file changed, but it hasn't been prepared for a commit yet.
    Output: modified: Calculator.java (shown in red)
  3. 3

    Step 3 — Stage the File

    Run git add Calculator.java to move this file into the staging area. If you run git status again, you'll see the file is now listed under "Changes to be committed" in green text. The file is ready to be permanently recorded.
    Output: modified: Calculator.java (now shown in green)
  4. 4

    Step 4 — Write and Execute the Commit

    Run git commit -m "Add calculateAverage method for grade computation". Notice how the message starts with an imperative verb ("Add"), stays under 50 characters, and clearly describes what was added and its purpose. Git creates the commit object, assigns it a unique hash, and records it in the repository history.
    Output: [main f3a7b2c] Add calculateAverage method for grade computation — 1 file changed, 12 insertions(+)
  5. 5

    Step 5 — Verify in the Log

    Run git log --oneline to see your new commit at the top of the history. You'll see the abbreviated hash followed by your message. Every commit below it represents a previous save point in your project.
    f3a7b2c Add calculateAverage method for grade computation — your commit is now the latest entry in the project history
⚠

Common Mistake

Forgetting to stage files before committing is the most common Git mistake for beginners. If you run git commit without first running git add, Git will tell you there is "nothing to commit." Always check git status to confirm your files are staged (green) before committing.

SECTION 7

Commit Message Do's and Don'ts

Knowing the rules for good commit messages is one thing; seeing them applied across different scenarios is another. The table below compares common bad practices with their improved alternatives, explaining why each improvement matters for real-world collaboration.

Bad PracticeBetter AlternativeWhy It Matters
"fix""Fix array index error in sortGrades()"Specifies what was fixed and where, so a teammate can find the relevant code quickly
"updated Main.java""Add user input validation to Main"Git already tracks which files changed — your message should explain the purpose, not restate the file name
"WIP""Implement partial search functionality"Even incomplete work should be described; 'WIP' tells nobody what is actually in progress
Committing everything at onceSeparate commits for separate concernsSmaller, focused commits are easier to review, test, and undo if something breaks
"final version""Complete unit tests for Calculator class"Nothing is ever truly 'final' in software — describe the actual content of the commit

Common commit message mistakes and their improvements

✦

KEY TAKEAWAY

Think of commit messages like subject lines in emails. If you received an email with the subject 'stuff' or 'update,' you'd have no idea whether to open it or ignore it. But a subject line like 'Meeting moved to 3 PM Friday' tells you exactly what to expect. Your future self reads commit messages the same way — make each one count.

SECTION 8

Commits in Team Workflows & Advanced Concepts

Once you've mastered the basic commit workflow, there's a bigger world of Git concepts to explore. In professional environments, commits are just one piece of a larger collaboration puzzle that includes branches, pull requests, and code reviews. Understanding how your commits fit into these workflows will prepare you for real-world software development.

ConceptWhat You Know NowWhat Comes Next
Saving ChangesCreating commits with meaningful messages on a single branchCreating separate branches for features and merging them together
Viewing HistoryUsing git log to see past commitsUsing git diff to compare commits and git blame to trace line-by-line authorship
Fixing MistakesWriting accurate messages to avoid confusionUsing git revert to undo specific commits and git amend to fix the last message
CollaborationWorking solo with local commitsPushing commits to GitHub, opening pull requests, and reviewing teammates' code

Your current knowledge vs. what's coming next

The most important point to remember is that every advanced Git operation builds on the commit. Whether you're rebasing, cherry-picking, or resolving merge conflicts, the fundamental unit you're working with is still the commit — a snapshot with a message. Mastering clean, meaningful commits now will make every future Git skill dramatically easier to learn.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

A student claims that a Git commit only saves the specific lines of code that changed, not the whole project. Is this accurate? Explain the difference between how Git conceptually stores a commit and what it physically records.
Show answer
The student's claim is partially correct in terms of physical storage but incorrect conceptually. Git treats each commit as a complete snapshot of the entire project — meaning conceptually, every commit contains the full state of all tracked files at that moment. Under the hood, Git is efficient: it doesn't duplicate unchanged files but instead stores references to previously recorded versions. The key distinction is that you can check out any single commit and get the full project back, not just a set of changes. This is why Git can quickly switch between commits without needing to 'replay' every change from the beginning.

Question 2: BASIC CALCULATION

You have modified three files: App.java, Database.java, and README.md. You only want to commit the two Java files together. Write the exact sequence of Git commands you would use, including an appropriate commit message.
Show answer
First, stage only the two Java files using git add App.java Database.java. Then commit them with a meaningful message: git commit -m "Refactor database connection logic in App and Database classes". The README.md file remains in the working directory as an unstaged change. You could verify this by running git status before and after each step. This approach lets you keep the documentation change for a separate, purpose-specific commit.

Question 3: INTERMEDIATE

You run git log --oneline and see the following history: c3d4e5f stuff b2c3d4e more changes a1b2c3d initial commit Your teammate asks you to explain what changed in commit c3d4e5f and you cannot tell from the message. Explain what went wrong with this commit history and rewrite all three messages to follow best practices, assuming the first commit created the project, the second added a search feature, and the third fixed a bug in the search.
Show answer
The problem is that the messages "stuff" and "more changes" are completely vague — they violate the principle of describing what changed and why. No one can understand the purpose of those commits without reading every line of code. Better messages would be: a1b2c3d Initialize project with main class and folder structure, b2c3d4e Add keyword search feature to product catalog, and c3d4e5f Fix case-sensitivity bug in search query matching. Each rewritten message starts with an imperative verb, stays concise, and tells the reader exactly what the commit accomplishes. With these messages, your teammate could immediately identify which commit might have introduced a search-related issue.

Question 4: APPLIED

You're working on a group Java project for your computer science class. You've made the following changes in a single coding session: (1) fixed a NullPointerException in the login method, (2) added a new 'forgot password' feature, and (3) reformatted the indentation in three files. Explain how you should organize these into commits and write the commit messages.
Show answer
These three changes serve different purposes and should be separated into three distinct commits for clarity. First, stage and commit the bug fix: git commit -m "Fix NullPointerException in login when username is empty". Second, stage and commit the new feature: git commit -m "Add forgot-password email reset functionality". Third, stage and commit the formatting changes: git commit -m "Standardize indentation to 4 spaces across all files". By separating these, if the 'forgot password' feature introduces a new bug, you can revert just that commit without losing the bug fix or the formatting improvements. This is the "one logical change per commit" principle in action, and it's especially important in team settings where others need to review your changes.

Question 5: CRITICAL THINKING

Consider two developers working on the same Java project. Developer A makes 50 tiny commits per day with messages like "Fix typo" and "Add semicolon." Developer B makes 2 large commits per day with messages like "Complete entire user authentication module." Analyze the trade-offs of each approach and propose a commit strategy that balances both extremes.
Show answer
Developer A's approach creates a cluttered history that's hard to navigate — scrolling through dozens of trivial commits makes it difficult to find meaningful changes. However, the advantage is that each change is granular and easy to revert individually. Developer B's approach creates clean-looking logs but each commit bundles so many changes together that pinpointing a specific bug becomes nearly impossible. If something breaks, reverting a massive commit undoes hours of unrelated work. The ideal balance is to commit each logical unit of work separately — one commit for adding a method, one for fixing a bug, one for updating documentation. A good rule of thumb is that each commit should be small enough that its message can clearly describe all changes in under 50 characters, but large enough that it represents a complete, meaningful step in the project's development. For Developer A, this means grouping related typo fixes into a single 'Fix formatting issues in UserService class' commit. For Developer B, this means breaking the authentication module into commits like 'Add password hashing utility,' 'Create login endpoint,' and 'Add session token generation.'

SUMMARY

Lesson Summary

Summary

A Git commit is a permanent snapshot of your project that records what changed, who made the change, and when it happened. The commit workflow follows three zones: you edit files in the working directory, select files for the next commit using git add to move them to the staging area, and then run git commit -m to permanently save the snapshot to the repository. Each commit is assigned a unique SHA-1 hash that makes it identifiable and tamper-proof.

The most critical habit to develop is writing meaningful commit messages that start with an imperative verb, stay under 50 characters, and describe what changed and why. Follow the one logical change per commit principle to keep your history clean and easy to navigate. Remember to always check git status before committing and use git log to verify your commit history. Mastering these fundamentals prepares you for advanced Git workflows including branching, merging, and collaborative development on platforms like GitHub.

Varsity Tutors • Java • Git Commits — Commit code changes with meaningful messages (conceptual workflow)