The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • Others
          • Indexing
      • Vendor-Specific Concepts
        • Oracle Specific
          • Rownum vs Rowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism and Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Distributed Tracing
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Low-Level Design (LLD)
      • Programming Paradigms
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Enhancements
        • Fluent API Design
          • Examples
    • High-Level Design (HLD)
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Architecture
        • Event Driven Architecture
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 1 - Maths theory & Pattern
          • Set 2 - Arrays
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • General Interview Preparation Tips - TBU
      • Flowchart - How to Solve Coding Problem?
  • Personal Projects
    • Hackathon
Powered by GitBook
On this page
  • About
  • How Merge Works in Git ?
  • Types of Merges
  • 1. Fast-Forward Merge
  • 2. No Fast-Forward Merge (--no-ff)
  • 3. Three-Way Merge (Standard Merge with Divergence)
  • 4. Octopus Merge
  • 5. Merge with Conflicts
  • Merge Strategy Options
  • Comparison
  • When to Use Merge ?
  • Merge vs Rebase
  • Practical Use Cases
  • 1. Standard Feature Branch Merge into Main Branch
  • 2. Bugfix Branch Merged Back Into Production
  • 3. Combining Two Active Feature Branches
  • 4. Bringing Develop Changes into Feature Branch
  • 5. Merging for Collaboration Between Teammates

Was this helpful?

  1. Git
  2. Workflows
  3. Merge Strategies

Merge

About

Merging in Git is the process of combining changes from two branches into one. It's used when we want to integrate work from a feature branch back into the main development branch (e.g., main, develop, or release/1.x) or vice versa.

Merging preserves the history of both branches and creates a new commit (called a merge commit) that ties them together.

How Merge Works in Git ?

When we run a git merge, Git looks for the common ancestor of the two branches and compares the changes made on each side from that point.

Example scenario:

  • main and feature-x both originated from commit A.

  • main has commit B.

  • feature-x has commits C and D.

When we merge feature-x into main, Git:

  • Identifies commit A as the common ancestor.

  • Applies the changes from commits C and D onto the current main.

  • Creates a new merge commit E with two parents: B and D.

The resulting history looks like this:

A---B---------E (main)
     \       /
      C---D (feature-x)

Types of Merges

1. Fast-Forward Merge

When it happens ?

A fast-forward merge occurs when the current branch has no new commits since it diverged from the branch being merged. Git doesn’t need to create a merge commit — it simply moves the pointer forward.

Before:

 A---B---C---D (feature)
         ↑
       (main)
  • main is currently pointing to C

  • feature has advanced to D

  • main has no new commits after C, so Git can fast-forward it to D

After:

A---B---C---D (main, feature)
  • Git just advances the main pointer to D, the tip of the feature branch.

  • This results in a linear history.

  • No merge commit is created.

Command

git checkout main
git merge feature

When to use ?

  • Feature branch is fully ahead of main with no divergence.

  • We want clean, simple history.

2. No Fast-Forward Merge (--no-ff)

When it happens ?

We use this when we want to force Git to create a merge commit, even if a fast-forward is possible. This helps preserve the context of the feature branch.

Before:

 A---B---C---D (feature)
         ↑
       (main)
  • main is at commit C

  • feature is ahead by one commit: D

After:

A---B---C-------E (main)
         \     /
          D---/  (feature)
  • E is a merge commit with parents: C and D

  • main now includes the full history of the feature

  • feature still exists (optional to delete)

Explanation

  • Forces a new commit E to indicate a merge took place.

  • The feature branch’s existence is preserved in history.

  • Useful for tracking what was merged and when.

Command

git checkout main
git merge --no-ff feature

When to use ?

  • We want to preserve the feature branch's identity.

  • Our team policy enforces explicit merge commits.

  • For audit or traceability reasons.

3. Three-Way Merge (Standard Merge with Divergence)

When it happens ?

Both the base branch and feature branch have diverged — i.e., each has commits the other doesn’t have.

Before:

      E---F (feature)
     /
A---B---C (main)
  • B is the common ancestor

  • main has commits: B → C

  • feature has commits: B → E → F

After:

      E---F
     /     \
A---B---C---G (main)
            ↑
          (merge commit)
  • G is the merge commit with two parents:

    • One from main (C)

    • One from feature (F)

  • main now includes changes from both branches

  • History is non-linear, but traceable

Command

git checkout main
git merge feature

When to use ?

  • The branches have diverged.

  • We want a complete history of how changes were integrated.

  • Most common real-world merge scenario.

4. Octopus Merge

When it happens ?

Used when merging more than two branches at once.

Before:

      C (feature1)
     /
A---B
     \
      D (feature2)
       \
        E (feature3)
  • All three feature branches (feature1, feature2, feature3) diverged from a common base (B)

  • They have no conflicting changes

After:

       C  D  E
        \ | /
A---B-----F (main)
          ↑
     (merge commit)
  • F is the octopus merge commit

  • Has multiple parents: C, D, E

  • main now contains all changes from feature1, feature2, and feature3

Command

git merge feature1 feature2

When to use ?

  • Automated merges with no conflicts.

  • Integrating multiple feature branches at once (e.g., for a release).

5. Merge with Conflicts

When it happens ?

A merge conflict occurs when two branches modify the same line in a file or delete/rename the same file differently.

Git cannot automatically decide whose change to keep, so it stops the merge and asks for manual intervention.

Before Merge:

Let’s say we have a file greeting.txt.

Content of greeting.txt on main:
Hello from Main!

Content of greeting.txt on feature:
Hello from Feature!

Branch Structure:

      C (feature - changes greeting.txt)
     /
A---B---D (main - also changes greeting.txt)
  • B is the common ancestor

  • Both main and feature changed the same line in greeting.txt in different ways

Attempting Merge:

git checkout main
git merge feature

Git will now stop and show a merge conflict:

✖ Conflict in greeting.txt:

<<<<<<< HEAD
Hello from Main!
=======
Hello from Feature!
>>>>>>> feature
  • HEAD is our current branch (main)

  • feature is the incoming branch

  • We must choose which change to keep (or both)

Resolving the Conflict:

We manually edit the file, for example:

Hello from Main and Feature!

Then:

git add greeting.txt
git commit

Git will now complete the merge by creating a merge commit.

After Merge:

      C
     /
A---B---D---E (main)
         \  /
          (merge commit with conflict resolved)
  • E is the merge commit

  • It has two parents: D (main) and C (feature)

  • greeting.txt now contains the manually resolved content

  • The merge commit (E in our example) is a new commit created on the current branch we are merging into (here, main).

  • Even though we manually resolve conflicts, the merge commit still becomes the new tip of main.

  • This merge commit has two parents:

    • The tip of our current branch before merge (D on main)

    • The tip of the branch we merged in (C on feature)

Merge Strategy Options

Git also offers internal merge strategies used behind the scenes:

Strategy
Description

recursive (default)

Standard three-way merge; handles most cases

resolve

Simple strategy, limited capabilities

ours

Keeps the current branch’s changes only

theirs

Keeps the incoming branch’s changes (used in rebasing with strategy options)

octopus

Used when merging more than two branches

Example:

git merge --strategy=recursive feature

Comparison

Type
Merge Commit Created
Linear History
Conflict Handling
Typical Use Case

Fast-Forward

No

Yes

No (no divergence)

Simple merges, clean linear history

No Fast-Forward

Yes

No

Yes

Preserve feature branch history

Three-Way Merge

Yes

No

Yes

Diverged branches, active collaboration

Octopus Merge

Yes (single commit)

No

No (fails on conflict)

Merge multiple branches at once

Merge with Conflicts

Yes

No

Yes (manual resolution)

When overlapping changes cause conflicts

When to Use Merge ?

Use merge when:

  • We want to preserve the full history of both branches.

  • Our team prefers non-destructive history.

  • We are working on long-running branches (e.g., release/1.x, develop, etc.).

  • We want to use GitLab Merge Requests or GitHub Pull Requests and show clear integration points.

Merge vs Rebase

Aspect
Merge
Rebase

History

Preserved, non-linear

Linearized, rewritten

Merge commit

Yes

No (unless explicitly created)

Conflict handling

All at once

One commit at a time

Use case

Collaborative workflows, history trace

Clean history, private feature branches

Practical Use Cases

1. Standard Feature Branch Merge into Main Branch

Problem: We completed a feature in a separate branch (feature/login). Now we want to bring that code into the main integration branch (develop or main), while preserving commit history.

Why Use Merge: Merging retains the complete branch history and clearly shows that a feature was developed independently and then integrated.

Command:

git checkout develop
git merge feature/login

Effect:

  • Creates a new merge commit.

  • Keeps all commits from feature/login.

  • Shows a clear branch-and-merge structure.

2. Bugfix Branch Merged Back Into Production

Problem: We created a hotfix branch (hotfix/issue-404) from main to quickly fix a production bug. Now the fix is done and tested.

Why Use Merge: We want the fix to be merged back while preserving the commit structure and making it traceable.

Command:

git checkout main
git merge hotfix/issue-404

Effect:

  • Keeps the hotfix history visible.

  • Avoids altering existing commits (unlike rebase).

3. Combining Two Active Feature Branches

Problem: Two related features are being developed in separate branches (feature/auth and feature/dashboard), and now we need to test them together locally before integrating into main.

Why Use Merge: We want to combine branches without changing their history. Merging is safe and non-destructive.

Command:

git checkout feature/auth
git merge feature/dashboard

Effect: We can test how both features behave together. If something breaks, history is untouched and reversible.

4. Bringing Develop Changes into Feature Branch

Problem: We are working on a long-lived branch (feature/analytics), and the develop branch has changed significantly (other features, refactoring, etc.). We need to sync.

Why Use Merge: We want to bring changes from develop into our branch to test compatibility and resolve conflicts without rewriting our feature’s history.

Command:

git checkout feature/analytics
git merge develop

Effect:

  • Resolves conflicts now instead of during the final merge.

  • Preserves our work’s history.

  • Keeps commits in their original sequence.

5. Merging for Collaboration Between Teammates

Problem: Two developers work on the same branch locally and need to sync up regularly without rebasing over each other’s history.

Why Use Merge: Merging is safe in shared branches. It doesn’t force history rewrites, which would create confusion or conflicts in shared repos.

Command:

git pull --no-rebase

(Performs a fetch + merge. Use --no-rebase to explicitly avoid rebasing.)

Effect:

  • Maintains all commit history.

  • Preserves collaborative workflows.

PreviousMerge StrategiesNextRebase

Last updated 7 hours ago

Was this helpful?