Simple Java programs for beginners are short, self-contained code examples that teach one concept at a time: printing output, doing arithmetic, using loops, or sorting arrays. Each program compiles and runs in under a minute. The 15 examples below cover basic syntax, logic, arrays and strings — everything needed for university practicals and entry-level placement tests.
- Key Takeaway 1: Java is statically typed, so every variable needs a declared type before you use it.
- Key Takeaway 2: The
mainmethod is the entry point of every Java application; without it, nothing runs. - Key Takeaway 3: According to the TIOBE Index (2024), Java consistently holds a top-3 position in global language popularity, making it one of the most in-demand skills for Indian IT hiring.
- Key Takeaway 4: Practising 15-20 focused programs beats reading a 500-page textbook cover to cover when you are starting out.
- Key Takeaway 5: Strong Java fundamentals feed directly into ethical hacking, secure coding and AI development work.
Java has ranked in the top three languages on the Stack Overflow Developer Survey for years running — with the 2024 edition showing Java used professionally by 30.3% of respondents globally — which makes it a smart first language to practise seriously. Start with these 15 simple Java programs for beginners and you will cover everything from basic syntax to entry-level algorithms.
How to Practise Simple Java Programs for Beginners
Before you write a single line, get your environment right. Download the Oracle JDK (Java 21 LTS is the current stable release as of 2024), install VS Code or IntelliJ IDEA Community, and confirm your setup by running javac -version in the terminal. If you have already learned how to write, compile and run a C program, the compile-then-run workflow in Java will feel familiar.
One mistake beginners make constantly: they copy code without typing it. Your fingers need to remember the syntax, not just your eyes. Type every program below from scratch, even if it takes longer.
The Compile-Run Cycle in Java
- Write your code in a file named exactly after the public class, e.g. Hello.java.
- Open a terminal in the same folder and run javac Hello.java to compile.
- If there are no errors, run java Hello to execute.
- Read the output, then deliberately break something and recompile so you understand what each error means.
Deliberately triggering errors is one of the best learning techniques there is. You will quickly discover the difference between a compile-time error and a runtime exception. Our guide on Java exceptions and common runtime errors explains exactly what to do when things go wrong.
What Every Beginner Java Program Needs
| Component | What It Does | Example |
|---|---|---|
| Class declaration | Wraps all code; filename must match | public class Hello |
| main method | Entry point the JVM calls first | public static void main(String[] args) |
| Statement | An instruction ending with a semicolon | System.out.println(“Hello”); |
| Import statement | Brings in external classes like Scanner | import java.util.Scanner; |
| Variable declaration | Reserves memory with a name and type | int age = 20; |
Simple Java Programs with Output: Examples 1-8
These eight programs are the bread and butter of any Java basics course. Indian universities, from NITs and IITs to VTU and Anna University-affiliated engineering colleges, include every one of these in their first-semester practicals. Work through them in order because each one builds on the last.
Program 1: Hello World
Every Java journey starts here. The program prints one line to the console and teaches you the minimum structure a Java file needs.
Code:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Output: Hello, World!
Notice that System.out.println prints the text and then moves to a new line. System.out.print does the same without the line break. That small difference trips up a lot of beginners in their first week.
Program 2: Sum of Two Numbers
Code:
public class Sum {
public static void main(String[] args) {
int a = 15, b = 25;
int sum = a + b;
System.out.println("Sum = " + sum);
}
}
Output: Sum = 40
The + operator does two jobs in Java: it adds numbers and it concatenates strings. When you write “Sum = ” + sum, Java converts the integer to a string automatically. That is called implicit type conversion.
Program 3: Swap Two Variables
Code (using a temporary variable):
public class Swap {
public static void main(String[] args) {
int x = 10, y = 20, temp;
temp = x;
x = y;
y = temp;
System.out.println("x = " + x + ", y = " + y);
}
}
Output: x = 20, y = 10
Interviewers at TCS, Infosys and Wipro still ask this in written tests. Know both the temp-variable method and the arithmetic method (x = x + y; y = x – y; x = x – y) so you can answer either way.
Program 4: Even or Odd
Code:
public class EvenOdd {
public static void main(String[] args) {
int n = 7;
if (n % 2 == 0) {
System.out.println(n + " is Even");
} else {
System.out.println(n + " is Odd");
}
}
}
Output: 7 is Odd
The modulo operator % returns the remainder after division. If the remainder when dividing by 2 is zero, the number is even. Simple, but this is the foundation of every divisibility check you will write later.
Program 5: Factorial Using a Loop
Code:
public class Factorial {
public static void main(String[] args) {
int n = 5, fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
System.out.println("Factorial of " + n + " = " + fact);
}
}
Output: Factorial of 5 = 120
This introduces the for loop and the compound assignment operator *=. Once you are comfortable here, try rewriting it with a while loop and then with recursion. Three implementations of the same problem teach you more than three different problems would.
Program 6: Fibonacci Series
Code:
public class Fibonacci {
public static void main(String[] args) {
int n = 10, a = 0, b = 1;
System.out.print(a + " " + b);
for (int i = 2; i < n; i++) {
int c = a + b;
System.out.print(" " + c);
a = b;
b = c;
}
}
}
Output: 0 1 1 2 3 5 8 13 21 34
The Fibonacci series is a classic exam question and a gateway to understanding dynamic programming later. Track how a and b shift at each step; draw it on paper if needed.
Program 7: Reverse a Number
Code:
public class ReverseNumber {
public static void main(String[] args) {
int num = 12345, rev = 0;
while (num != 0) {
int digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
System.out.println("Reversed: " + rev);
}
}
Output: Reversed: 54321
This program combines modulo and integer division. It is a favourite in GATE preparation and campus placement written tests across India, particularly at companies like Cognizant and HCL Technologies.
Program 8: Check Prime Number
Code:
public class PrimeCheck {
public static void main(String[] args) {
int n = 29;
boolean isPrime = true;
if (n < 2) isPrime = false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) { isPrime = false; break; }
}
System.out.println(n + (isPrime ? " is Prime" : " is Not Prime"));
}
}
Output: 29 is Prime
Checking up to Math.sqrt(n) instead of n-1 cuts the number of iterations dramatically. That is your first taste of algorithmic efficiency, and it matters more as inputs get larger.
Java Array Programs for Beginners: Examples 9-15
These seven programs step up the difficulty. They cover arrays, sorting, searching and string manipulation. If you are preparing for campus placements or university exams, these are the programs asked most often. According to GeeksforGeeks' interview preparation data, array manipulation and sorting questions appear in over 60% of entry-level Java coding rounds at Indian IT companies. The JetBrains State of Developer Ecosystem 2024 report also found that Java remains the primary language taught in 58% of university computer science programmes surveyed globally.
Program 9: Sum of Array Elements
Code:
public class ArraySum {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : arr) {
sum += num;
}
System.out.println("Sum = " + sum);
}
}
Output: Sum = 150
The enhanced for-each loop makes array traversal cleaner. Get comfortable with both the index-based loop and the for-each; some problems need the index, others do not.
Program 10: Find the Largest Element in an Array
Code:
public class LargestElement {
public static void main(String[] args) {
int[] arr = {3, 78, 12, 45, 99, 7};
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
System.out.println("Largest = " + max);
}
}
Output: Largest = 99
Always initialise max to the first element, not to zero. If the array contains only negative numbers, initialising to zero gives a wrong answer. That is a real bug that appears in production code written by developers who skipped this lesson.
Program 11: Bubble Sort
Code:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int num : arr) System.out.print(num + " ");
}
}
Output: 11 12 22 25 34 64 90
Bubble sort has O(n squared) time complexity, which makes it inefficient on large datasets. You learn it not because you will use it in production, but because it teaches comparison-based sorting logic that applies to every other sorting algorithm you will study.
Program 12: Linear Search
Code:
public class LinearSearch {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 1, 9, 2};
int target = 9, index = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) { index = i; break; }
}
System.out.println(index != -1 ? "Found at index " + index : "Not found");
}
}
Output: Found at index 4
Linear search checks every element one by one from left to right. It works on both sorted and unsorted arrays, which makes it the simplest search algorithm to implement. The trade-off is speed: on a list of one million items, it may check all one million before finding the target.
Program 13: Binary Search
Code:
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {2, 5, 8, 12, 16, 23, 38, 56};
int target = 23, low = 0, high = arr.length - 1, result = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) { result = mid; break; }
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
System.out.println(result != -1 ? "Found at index " + result : "Not found");
}
}
Output: Found at index 5
Binary search requires a sorted array and runs in O(log n) time. That is the practical reason sorting matters: it unlocks faster searching. These two programs together explain a concept that takes most students a full lecture to grasp.
Program 14: Palindrome Check
Code:
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
String rev = new StringBuilder(str).reverse().toString();
System.out.println(str.equals(rev) ? str + " is a Palindrome" : str + " is not a Palindrome");
}
}
Output: madam is a Palindrome
This program introduces the StringBuilder class and the .equals() method for string comparison. Never use == to compare strings in Java; it checks object references, not content, and that bug is one of the most common mistakes in beginner code.
Program 15: Count Vowels in a String
Code:
public class CountVowels {
public static void main(String[] args) {
String str = "Java Programming";
int count = 0;
for (char c : str.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) != -1) count++;
}
System.out.println("Vowels: " + count);
}
}
Output: Vowels: 6
This program combines character arrays, string methods and a search inside a string. It is also a clean introduction to working with text, which is relevant to everything from form validation to building chatbots.
Where to Practise Simple Java Programs Next
Writing programs from a guide is only step one. You need to solve problems you have not seen before, under time pressure, to build real skill. The most used platforms among Indian CS students are GeeksforGeeks, LeetCode and HackerRank. GeeksforGeeks specifically has a dedicated Java practice section with problems tagged by difficulty and topic, which makes it easy to pick up from wherever you are.
Sites like Javatpoint also have structured Java program lists that are useful for exam revision, though they lean more toward reading than hands-on coding. For actual problem-solving practice, LeetCode's Easy section is the better choice once you have finished these 15 programs.
Difficulty Progression Table
| Stage | Programs to Focus On | Recommended Platform | Time Investment |
|---|---|---|---|
| Week 1 | Hello World, Sum, Swap, Even/Odd | Local IDE + Javatpoint reference | 1 hour/day |
| Week 2 | Factorial, Fibonacci, Reverse, Prime | GeeksforGeeks practice | 1-2 hours/day |
| Week 3 | Arrays, Sorting, Searching | HackerRank Java domain | 1-2 hours/day |
| Week 4 | Strings, Palindrome, Pattern programs | LeetCode Easy (Java filter) | 2 hours/day |
If you are studying for a BTech or BCA degree, check our breakdown of BSc Computer Science subjects and scope to see exactly where Java fits into your full curriculum. And if you are thinking about what comes after graduation, the jobs and salary after MCA guide covers which technical skills employers actually pay for.
Tools That Speed Up Your Learning
Beyond the code itself, the tools you use shape how fast you improve. Our software development tools guide covers IDEs, debuggers and version control systems worth setting up early. IntelliJ IDEA's built-in debugger, for instance, lets you step through a loop line by line, which makes understanding programs like Bubble Sort dramatically faster than reading the code alone.
Java's strong typing and verbose error messages are actually an asset when you are learning. The compiler tells you exactly what is wrong and where. Use that feedback rather than fighting it.
Once your Java fundamentals are solid, the next logical step for many Indian IT professionals is specialising in a high-demand area. Ethical hacking, secure coding and AI development all require strong programming foundations, and our Stack Overflow developer survey insights article explains which specialisations are growing fastest right now.
Frequently Asked Questions
What are simple Java programs for beginners?
Simple Java programs for beginners are short code examples that each teach one concept: printing text, doing arithmetic, using loops, working with arrays or manipulating strings. Examples include Hello World, factorial, Fibonacci, swap, prime check and basic sorting. They are designed to be typed, run and modified rather than just read.
Where can I practise Java programs?
The best platforms for Java practice are GeeksforGeeks, HackerRank's Java domain, LeetCode (filter by Java) and Javatpoint for reference programs. Indian students also use their university lab portals and competitive coding platforms like CodeChef. Start with GeeksforGeeks' school-level problems and move to LeetCode Easy once you are comfortable with basic syntax.
What Java programs are asked in exams?
University exams in India typically ask for factorial, Fibonacci, prime number check, palindrome, bubble sort, linear search and pattern printing programs. Campus placement written tests from companies like TCS and Infosys add array manipulation, string reversal and binary search. Practising all 15 programs in this article covers the vast majority of what appears in both contexts.
How do I improve Java coding?
Type every program yourself instead of copying it. Then modify it: change the input, add a new condition, or rewrite it using a different loop type. Solve at least one new problem daily on a platform like HackerRank or LeetCode. Reading about Java improves your knowledge; writing and debugging code improves your skill, and those are different things.
What algorithms should beginners code in Java?
Start with Bubble Sort, Linear Search and Binary Search because they teach comparison logic and the value of sorted data. Then move to Insertion Sort, Selection Sort and basic recursion (factorial, Fibonacci). These algorithms appear in GATE preparation, placement tests and university practicals across India, and they form the base of every data structures course you will take next.
You have now got 15 working Java programs, a four-week practice plan and a clear picture of what exam questions look like. Here are three things to do this week:
- Set up your JDK and IDE today, then type and run Programs 1-4 from scratch without copy-pasting.
- Create a free account on GeeksforGeeks or HackerRank and solve five Java problems at the beginner level by the end of the week.
- Once you are comfortable with these basics, explore how Java programming connects to cybersecurity and ethical hacking through 3.0 University's CEH v13 AI online course, or browse the full 3.0 University certification catalogue to find where your skills can take you next.
Last updated: June 2025. Reviewed by the 3University editorial team.