Version Control (Git)

Essential Git commands and concepts for Java developers.

Version Control with Git

Git is the standard for version control. It allows you to track changes, collaborate with others, and revert mistakes.

Basic Commands

git init

Initializes a new Git repository.

git clone <url>

Copies an existing repository from a remote server (like GitHub).

git add <file>

Stages changes to be committed. Use git add . to stage all changes.

git commit -m "message"

Saves the staged changes with a descriptive message.

git push

Uploads your local commits to the remote repository.

git pull

git pull

Downloads changes from the remote repository to your local machine.

Branching and Merging

git branch <name>

Creates a new branch.

git checkout <name>

Switches to the specified branch.

git merge <name>

Merges the specified branch into the current branch.

git checkout -b <name>

Creates AND switches to a new branch in one command.

.gitignore for Java

You should not commit compiled code (.class files) or build artifacts. Create a .gitignore file:

# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

Tip 💡

Commit often and write clear, descriptive commit messages. It helps you (and others) understand the history of your project.