How to Use Git for Java Projects

Git workflow diagram showing branches, commits, and merge operations

Introduction

Git is a distributed version control system that tracks changes in your code over time. For Java developers, it provides a reliable way to manage evolving codebases, experiment with new features, and coordinate work across multiple branches and team members.

Version control is one of the most important skills for any developer to master. Without it, you risk losing work, creating confusion when working with others, and having no way to undo mistakes. Git solves these problems by maintaining a complete history of every change made to your codebase.

This tutorial will take you from Git beginner to competent user. You will learn the fundamental concepts, essential commands, and workflows that developers use every day. By the end, you will have the skills to manage your own projects and contribute to team repositories.

Who This Guide Is For

This tutorial is designed for developers who are new to version control or want to strengthen their Git skills. You will find this guide valuable if you:

Basic familiarity with the command line is helpful but not required. We explain each command thoroughly and provide context for when and why to use it.

Prerequisites

Before starting this tutorial, ensure you have:

If you need help installing Git, refer to our development environment setup guide which covers Git installation in detail.

Step-by-Step Instructions

Step 1: Understand Git Concepts

Before diving into commands, understanding a few key concepts will make everything else clearer.

A repository is a folder that Git is tracking. It contains your files plus a hidden .git directory where Git stores its data. You can have many repositories on your computer, one for each project.

A commit is a snapshot of your project at a specific point in time. Each commit has a unique identifier and contains information about what changed, when, and who made the change. Commits form a timeline of your project's history.

The staging area is a preparation zone where you select which changes to include in your next commit. This gives you control over exactly what gets saved, rather than committing everything at once.

A branch is an independent line of development. Branches let you work on features or fixes without affecting the main codebase until you are ready to integrate your changes.

Step 2: Create Your First Repository

Start by creating a new folder for your project and navigating into it. Then initialize Git to start tracking the folder:

mkdir my-project
cd my-project
git init

The git init command creates the .git directory that stores all version control information. Your folder is now a Git repository, though it does not have any commits yet.

Create a simple file to have something to track. Open your editor and create a file called readme.txt with some content. Save it in your project folder.

Step 3: Stage and Commit Changes

Before committing, you need to stage your changes. Check the status of your repository to see what Git knows about your files:

git status

Git will show readme.txt as an untracked file. To stage it for commit, use the add command:

git add readme.txt

Running git status again shows the file is now staged and ready to commit. Create your first commit with a descriptive message:

git commit -m "Add initial readme file"

Congratulations, you have made your first commit. This snapshot is now permanently recorded in your project's history. The -m flag lets you provide a commit message inline. Good commit messages describe what changed and why.

Step 4: Make More Changes and Track History

Edit your readme.txt file to add more content, then stage and commit the changes:

git add readme.txt
git commit -m "Expand readme with project description"

You can view your commit history with the log command:

git log

This shows all commits in reverse chronological order, including the unique identifier (a long string of characters), author, date, and message. For a more compact view, try:

git log --oneline

Each commit builds on the previous one, creating a timeline of your project's evolution.

Step 5: Work with Branches

Branches allow you to work on different features or experiments without affecting your main code. Create a new branch with:

git branch feature-addition

This creates a branch but does not switch to it. To switch branches, use:

git checkout feature-addition

Or combine both steps into one command:

git checkout -b feature-addition

Now any changes you make and commit will only exist on this branch. The main branch remains unchanged until you decide to merge your work back in.

Make some changes on your feature branch, stage them, and commit. Then switch back to your main branch:

git checkout main

Notice that your changes from the feature branch are not visible on the main branch. They are safely stored on the feature branch until you merge them.

Step 6: Merge Branches

When your feature is complete and tested, you can merge it into the main branch. First, make sure you are on the branch you want to merge into (usually main):

git checkout main
git merge feature-addition

Git will incorporate the changes from feature-addition into main. If there are no conflicts, the merge happens automatically. If the same lines were changed in both branches, Git will ask you to resolve the conflict manually.

After merging, you can delete the feature branch since its changes are now part of main:

git branch -d feature-addition

Step 7: Connect to a Remote Repository

So far, everything has been local to your computer. To share your code or back it up online, you need a remote repository. Popular hosting services provide these for free.

After creating a repository on a hosting service, connect your local repository to it:

git remote add origin https://your-repository-url.git

The name "origin" is conventional for your primary remote. Push your code to the remote:

git push -u origin main

The -u flag sets up tracking, so future pushes can simply use git push. Your commits are now safely stored online.

Common Mistakes and How to Avoid Them

Git can be forgiving, but some mistakes are easier to prevent than to fix.

Committing without reviewing changes: Always run git status and git diff before committing to see exactly what you are about to save. It is easy to accidentally include files you did not intend to commit.

Writing poor commit messages: Future you (and your teammates) will thank you for descriptive commit messages. Instead of "fixed bug," write "Fix null pointer exception in user login validation." Good messages explain what and why, not just what file changed.

Working directly on main: Develop the habit of creating branches for all changes, even small ones. This keeps your main branch clean and makes it easier to abandon changes if needed.

Not pulling before pushing: If you are working with others, always pull the latest changes before pushing your own. This prevents conflicts and ensures you are building on the current codebase.

Ignoring the .gitignore file: Create a .gitignore file to specify files Git should ignore, such as build outputs, dependencies, and personal configuration files. This keeps your repository clean and prevents accidental commits of sensitive information.

Practical Example

Let us walk through a realistic workflow. Imagine you are adding a new feature to a website project.

Start by ensuring your main branch is up to date:

git checkout main
git pull origin main

Create a branch for your feature:

git checkout -b add-contact-form

Make your changes to the code. As you work, periodically stage and commit your progress:

git add contact.html contact.css
git commit -m "Add contact form HTML structure and styling"

Continue making changes and committing. Each commit should represent a logical unit of work:

git add contact.js
git commit -m "Add form validation for contact form"

When the feature is complete, push your branch to the remote:

git push -u origin add-contact-form

After your code is reviewed and approved (if working with a team), merge it into main:

git checkout main
git merge add-contact-form
git push origin main

Clean up by deleting the feature branch locally and remotely:

git branch -d add-contact-form
git push origin --delete add-contact-form

Summary

Git provides powerful tools for managing your code history and collaborating with others. The fundamental workflow involves making changes, staging them, committing them with meaningful messages, and optionally pushing to a remote repository.

Key concepts to remember include repositories as tracked folders, commits as project snapshots, the staging area for preparing commits, and branches for parallel development. These building blocks combine to enable sophisticated development workflows.

Start with the basics and gradually incorporate more advanced features as you become comfortable. Git has many capabilities beyond what this tutorial covers, but mastering these fundamentals will serve you well in most situations. Practice regularly, and version control will become second nature.