Bubble Sort Example in Java
On this page (9sections)
Introduction
Bubble Sort is a classic Java console program that demonstrates the concept with complete source code and sample output. Sorting algorithms arrange data in order — bubble, selection, merge, quick and heap sort.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. It can be practical if the input is usually in sort order but may occasionally have some out-of-order elements nearly in position.
Bubble Sort Example Program
import java.util.Scanner;
class BubbleSort {
public static void main(String []args) {
int num,swap;
Scanner in = new Scanner(System.in);
System.out.println("How many numbers are to be sorted:");
num = in.nextInt();
int array[] = new int[num];
System.out.println("Enter " + num + " integers");
for (int i = 0; i < num; i++){
array[i] = in.nextInt();
for (int i = 0; i < ( num - 1 ); i++) {
for (int j = 0; j < num - i - 1; j++) {
if (array[j] > array[j+1]){
swap = array[j];
array[j] = array[j+1];
array[j+1] = swap;
}
}
}
}
System.out.println("After sorting: ");
for (int i = 0; i < num; i++){
System.out.println(array[i]);
}
}
}
Sample Output
How many numbers are to be sorted:
7
Enter 7 integers
34
67
32
78
945
1111
2
After sorting:
2
32
34
67
78
945
1111
When to use
Use this bubble sort example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
Scannerreads typed input from the keyboard (System.in). -
A
println/printcall writes text to the console — part of the sample output below. -
num = in.nextInt();updates a variable used in the calculation or output. -
int array[] = new int[num];updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
The
ifstatement runs the nested code only when the condition is true.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.