50 Java Programs for Beginners with Output & Explanation (2026 Guide)
Java remains one of the most widely used programming languages in the software industry. Whether you want to become a backend developer, software engineer, Android developer, or prepare for coding interviews, Java is an excellent language to learn.
One of the most effective ways to master Java is by practicing programs regularly. Writing code helps you understand syntax, logic building, problem-solving, and core programming concepts.
In this comprehensive guide, you'll learn 50 essential Java programs every beginner should practice. Each program includes source code, output, and detailed explanations.
Let's start with the fundamentals.
Program 1: Hello World Program
The Hello World program is traditionally the first program every programmer writes.
Java Code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}Output
Hello WorldExplanation
public class HelloWorldcreates a class.main()is the entry point of a Java application.System.out.println()prints text to the console.
Program 2: Print Your Name
This program prints a user's name.
Java Code
public class PrintName {
public static void main(String[] args) {
System.out.println("John Doe");
}
}Output
John DoeExplanation
The program directly displays the specified text using the println() method.
Program 3: Add Two Numbers
Addition is one of the most basic arithmetic operations.
Java Code
public class AddNumbers {
public static void main(String[] args) {
int num1 = 20;
int num2 = 30;
int sum = num1 + num2;
System.out.println("Sum = " + sum);
}
}Output
Sum = 50Explanation
The values are stored in variables and added together using the + operator.
Program 4: Find the Average of Three Numbers
Java Code
public class AverageNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 30;
double average = (a + b + c) / 3.0;
System.out.println("Average = " + average);
}
}Output
Average = 20.0Explanation
The sum of all numbers is divided by the total count.
Program 5: Swap Two Numbers Using Third Variable
Java Code
public class SwapNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
int temp = a;
a = b;
b = temp;
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}Output
a = 20
b = 10Explanation
A temporary variable stores one value while swapping.
Program 6: Swap Two Numbers Without Third Variable
Java Code
public class SwapWithoutTemp {
public static void main(String[] args) {
int a = 10;
int b = 20;
a = a + b;
b = a - b;
a = a - b;
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}Output
a = 20
b = 10Explanation
Mathematical operations are used to exchange values without extra memory.
Program 7: Check Even or Odd Number
Java Code
public class EvenOdd {
public static void main(String[] args) {
int num = 12;
if(num % 2 == 0)
System.out.println("Even Number");
else
System.out.println("Odd Number");
}
}Output
Even NumberExplanation
If a number is divisible by 2, it is even; otherwise, it is odd.
Program 8: Find Largest of Two Numbers
Java Code
public class LargestNumber {
public static void main(String[] args) {
int a = 15;
int b = 25;
if(a > b)
System.out.println(a + " is largest");
else
System.out.println(b + " is largest");
}
}Output
25 is largestExplanation
The if-else statement compares two numbers and prints the larger one.
Program 9: Find Largest of Three Numbers
Java Code
public class LargestThree {
public static void main(String[] args) {
int a = 15;
int b = 40;
int c = 25;
if(a >= b && a >= c)
System.out.println(a + " is largest");
else if(b >= a && b >= c)
System.out.println(b + " is largest");
else
System.out.println(c + " is largest");
}
}Output
40 is largestExplanation
Logical operators help determine which value is greatest.
Program 10: Check Positive, Negative, or Zero
Java Code
public class NumberType {
public static void main(String[] args) {
int num = -10;
if(num > 0)
System.out.println("Positive");
else if(num < 0)
System.out.println("Negative");
else
System.out.println("Zero");
}
}Output
NegativeExplanation
The program checks the sign of the given number.
Program 11: Check Leap Year
Java Code
public class LeapYear {
public static void main(String[] args) {
int year = 2028;
if((year % 4 == 0 && year % 100 != 0)
|| (year % 400 == 0))
System.out.println("Leap Year");
else
System.out.println("Not a Leap Year");
}
}Output
Leap YearExplanation
Leap year rules:
- Divisible by 4
- Not divisible by 100
- Unless divisible by 400
Program 12: Calculate Simple Interest
Formula:
Simple Interest = (P × R × T) / 100
Java Code
public class SimpleInterest {
public static void main(String[] args) {
double principal = 5000;
double rate = 5;
double time = 2;
double si = (principal * rate * time) / 100;
System.out.println("Simple Interest = " + si);
}
}Output
Simple Interest = 500.0Explanation
The formula calculates interest earned over time.
Program 13: Find Area of Circle
Formula:
Area = Ï€r²
Java Code
public class CircleArea {
public static void main(String[] args) {
double radius = 5;
double area = Math.PI * radius * radius;
System.out.println("Area = " + area);
}
}Output
Area = 78.53981633974483Explanation
Java's Math.PI provides an accurate value of π.
Program 14: Convert Celsius to Fahrenheit
Formula:
F = (C × 9/5) + 32
Java Code
public class CelsiusToFahrenheit {
public static void main(String[] args) {
double celsius = 25;
double fahrenheit =
(celsius * 9 / 5) + 32;
System.out.println(
"Fahrenheit = " + fahrenheit);
}
}Output
Fahrenheit = 77.0Explanation
The formula converts temperature from Celsius to Fahrenheit.
Program 15: Generate Multiplication Table
Java Code
public class MultiplicationTable {
public static void main(String[] args) {
int num = 5;
for(int i = 1; i <= 10; i++) {
System.out.println(
num + " x " + i + " = " + (num * i)
);
}
}
}Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50Explanation
A for loop iterates from 1 to 10 and multiplies the number by each value.
Program 16: Factorial of a Number
A factorial is the product of all positive integers less than or equal to a number.
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
Java Code
public class Factorial {
public static void main(String[] args) {
int num = 5;
long factorial = 1;
for(int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("Factorial = " + factorial);
}
}Output
Factorial = 120Explanation
The loop multiplies all numbers from 1 to 5.
Program 17: Fibonacci Series
The Fibonacci sequence is:
0, 1, 1, 2, 3, 5, 8, 13...
Java Code
public class Fibonacci {
public static void main(String[] args) {
int a = 0;
int b = 1;
System.out.print(a + " " + b + " ");
for(int i = 2; i < 10; i++) {
int c = a + b;
System.out.print(c + " ");
a = b;
b = c;
}
}
}Output
0 1 1 2 3 5 8 13 21 34Explanation
Each number is the sum of the previous two numbers.
Program 18: Check Prime Number
A prime number has exactly two factors:
- 1
- Itself
Java Code
public class PrimeCheck {
public static void main(String[] args) {
int num = 17;
boolean isPrime = true;
for(int i = 2; i <= num / 2; i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}
if(isPrime)
System.out.println("Prime Number");
else
System.out.println("Not Prime Number");
}
}Output
Prime NumberExplanation
The loop checks whether any number divides 17 evenly.
Program 19: Generate Prime Numbers from 1 to 100
Java Code
public class PrimeNumbers {
public static void main(String[] args) {
for(int num = 2; num <= 100; num++) {
boolean isPrime = true;
for(int i = 2; i <= num / 2; i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}
if(isPrime)
System.out.print(num + " ");
}
}
}Output
2 3 5 7 11 13 17 19 23 29 ...Explanation
Every number is checked individually for primality.
Program 20: Reverse a Number
Example:
12345 → 54321
Java Code
public class ReverseNumber {
public static void main(String[] args) {
int num = 12345;
int reverse = 0;
while(num != 0) {
int digit = num % 10;
reverse = reverse * 10 + digit;
num /= 10;
}
System.out.println(reverse);
}
}Output
54321Explanation
The last digit is extracted and added to the reversed number.
Program 21: Check Palindrome Number
A palindrome remains the same when reversed.
Examples:
- 121
- 1331
- 1221
Java Code
public class PalindromeNumber {
public static void main(String[] args) {
int original = 121;
int num = original;
int reverse = 0;
while(num != 0) {
reverse = reverse * 10 + num % 10;
num /= 10;
}
if(original == reverse)
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}Output
PalindromeExplanation
The reversed number is compared with the original.
Program 22: Count Digits in a Number
Java Code
public class CountDigits {
public static void main(String[] args) {
int num = 123456;
int count = 0;
while(num != 0) {
num /= 10;
count++;
}
System.out.println(count);
}
}Output
6Explanation
Each loop removes one digit.
Program 23: Sum of Digits
Example:
1234
1 + 2 + 3 + 4 = 10
Java Code
public class SumDigits {
public static void main(String[] args) {
int num = 1234;
int sum = 0;
while(num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println(sum);
}
}Output
10Explanation
Each digit is extracted and added.
Program 24: Product of Digits
Java Code
public class ProductDigits {
public static void main(String[] args) {
int num = 123;
int product = 1;
while(num != 0) {
product *= num % 10;
num /= 10;
}
System.out.println(product);
}
}Output
6Explanation
1 × 2 × 3 = 6
Program 25: Armstrong Number
An Armstrong number equals the sum of its digits raised to the power of the number of digits.
Example:
153
1³ + 5³ + 3³ = 153
Java Code
public class Armstrong {
public static void main(String[] args) {
int number = 153;
int temp = number;
int sum = 0;
while(temp != 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if(sum == number)
System.out.println("Armstrong Number");
else
System.out.println("Not Armstrong Number");
}
}Output
Armstrong NumberExplanation
Each digit is cubed and added together.
Program 26: Armstrong Numbers from 1 to 1000
Java Code
public class ArmstrongSeries {
public static void main(String[] args) {
for(int num = 1; num <= 1000; num++) {
int temp = num;
int sum = 0;
while(temp != 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if(sum == num)
System.out.print(num + " ");
}
}
}Output
1 153 370 371 407Program 27: Check Perfect Number
A perfect number equals the sum of its proper divisors.
Example:
6
1 + 2 + 3 = 6
Java Code
public class PerfectNumber {
public static void main(String[] args) {
int num = 6;
int sum = 0;
for(int i = 1; i < num; i++) {
if(num % i == 0)
sum += i;
}
if(sum == num)
System.out.println("Perfect Number");
else
System.out.println("Not Perfect Number");
}
}Output
Perfect NumberProgram 28: Check Strong Number
Example:
145
1! + 4! + 5! = 145
Java Code
public class StrongNumber {
public static void main(String[] args) {
int num = 145;
int original = num;
int sum = 0;
while(num != 0) {
int digit = num % 10;
int fact = 1;
for(int i = 1; i <= digit; i++) {
fact *= i;
}
sum += fact;
num /= 10;
}
if(sum == original)
System.out.println("Strong Number");
else
System.out.println("Not Strong Number");
}
}Output
Strong NumberProgram 29: Find Power of a Number
Example:
2⁵ = 32
Java Code
public class PowerNumber {
public static void main(String[] args) {
int base = 2;
int exponent = 5;
int result = 1;
for(int i = 1; i <= exponent; i++) {
result *= base;
}
System.out.println(result);
}
}Output
32Explanation
The base is multiplied repeatedly.
Program 30: Check Automorphic Number
An automorphic number's square ends with the same digits as the number itself.
Example:
25
25² = 625
Java Code
public class Automorphic {
public static void main(String[] args) {
int num = 25;
int square = num * num;
if(square % 100 == num)
System.out.println("Automorphic Number");
else
System.out.println("Not Automorphic Number");
}
}Output
Automorphic NumberExplanation
The last digits of the square are compared with the original number.
Program 31: Find Largest Element in an Array
Java Code
public class LargestElement {
public static void main(String[] args) {
int[] arr = {10, 25, 7, 89, 45};
int largest = arr[0];
for(int i = 1; i < arr.length; i++) {
if(arr[i] > largest) {
largest = arr[i];
}
}
System.out.println("Largest Element = " + largest);
}
}Output
Largest Element = 89Explanation
The program compares each array element and keeps track of the largest value.
Program 32: Find Smallest Element in an Array
Java Code
public class SmallestElement {
public static void main(String[] args) {
int[] arr = {10, 25, 7, 89, 45};
int smallest = arr[0];
for(int i = 1; i < arr.length; i++) {
if(arr[i] < smallest) {
smallest = arr[i];
}
}
System.out.println("Smallest Element = " + smallest);
}
}Output
Smallest Element = 7Program 33: Calculate Sum of Array Elements
Java 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 = 150Program 34: Calculate Average of Array Elements
Java Code
public class ArrayAverage {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int sum = 0;
for(int num : arr) {
sum += num;
}
double average = (double) sum / arr.length;
System.out.println("Average = " + average);
}
}Output
Average = 30.0Program 35: Reverse an Array
Java Code
public class ReverseArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for(int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}Output
5 4 3 2 1Program 36: Sort an Array in Ascending Order
Java Code
import java.util.Arrays;
public class SortArray {
public static void main(String[] args) {
int[] arr = {50, 20, 10, 40, 30};
Arrays.sort(arr);
for(int num : arr) {
System.out.print(num + " ");
}
}
}Output
10 20 30 40 50Program 37: Linear Search
Java Code
public class LinearSearch {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int key = 30;
boolean found = false;
for(int num : arr) {
if(num == key) {
found = true;
break;
}
}
if(found)
System.out.println("Element Found");
else
System.out.println("Element Not Found");
}
}Output
Element FoundProgram 38: Binary Search
Java Code
import java.util.Arrays;
public class BinarySearchExample {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int index = Arrays.binarySearch(arr, 40);
System.out.println("Index = " + index);
}
}Output
Index = 3Program 39: Find Second Largest Element
Java Code
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {10, 20, 90, 50, 70};
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for(int num : arr) {
if(num > first) {
second = first;
first = num;
} else if(num > second && num != first) {
second = num;
}
}
System.out.println("Second Largest = " + second);
}
}Output
Second Largest = 70Program 40: Remove Duplicate Elements from Array
Java Code
import java.util.HashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4, 5};
HashSet<Integer> set = new HashSet<>();
for(int num : arr) {
set.add(num);
}
System.out.println(set);
}
}Output
[1, 2, 3, 4, 5]Program 41: Reverse a String
Java Code
public class ReverseString {
public static void main(String[] args) {
String str = "Java";
String reversed = "";
for(int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println(reversed);
}
}Output
avaJProgram 42: Check Palindrome String
Java Code
public class PalindromeString {
public static void main(String[] args) {
String str = "madam";
String reverse = "";
for(int i = str.length() - 1; i >= 0; i--) {
reverse += str.charAt(i);
}
if(str.equals(reverse))
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}Output
PalindromeProgram 43: Count Vowels in a String
Java Code
public class CountVowels {
public static void main(String[] args) {
String str = "Java Programming";
int count = 0;
str = str.toLowerCase();
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u') {
count++;
}
}
System.out.println("Vowels = " + count);
}
}Output
Vowels = 5Program 44: Count Words in a Sentence
Java Code
public class WordCount {
public static void main(String[] args) {
String sentence =
"Java is a powerful programming language";
String[] words = sentence.split("\\s+");
System.out.println("Words = " + words.length);
}
}Output
Words = 6Program 45: Check Anagram Strings
Two strings are anagrams if they contain the same characters in a different order.
Examples:
- listen → silent
- heart → earth
Java Code
import java.util.Arrays;
public class Anagram {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
if(Arrays.equals(arr1, arr2))
System.out.println("Anagram");
else
System.out.println("Not Anagram");
}
}Output
AnagramInterview Tips for Arrays and Strings
The following programs are asked frequently in Java interviews:
Array Questions
- Largest Element
- Second Largest Element
- Array Sorting
- Binary Search
- Remove Duplicates
- Array Reversal
String Questions
- Reverse String
- Palindrome String
- Anagram Check
- Character Count
- Word Count
- Vowel Counter
Practice these programs until you can write them without looking at the solution.
Program 46: Character Frequency Counter
This program counts how many times each character appears in a string.
Java Code
import java.util.HashMap;
public class CharacterFrequency {
public static void main(String[] args) {
String str = "programming";
HashMap<Character, Integer> map = new HashMap<>();
for(char ch : str.toCharArray()) {
map.put(ch,
map.getOrDefault(ch, 0) + 1);
}
System.out.println(map);
}
}Output
{p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}Explanation
A HashMap stores each character and its frequency.
Program 47: Convert String to Uppercase
Java Code
public class UpperCaseExample {
public static void main(String[] args) {
String str = "java programming";
System.out.println(
str.toUpperCase());
}
}Output
JAVA PROGRAMMINGExplanation
The toUpperCase() method converts all characters to uppercase.
Program 48: Convert String to Lowercase
Java Code
public class LowerCaseExample {
public static void main(String[] args) {
String str = "JAVA PROGRAMMING";
System.out.println(
str.toLowerCase());
}
}Output
java programmingExplanation
The toLowerCase() method converts all characters to lowercase.
Program 49: Sort Characters in a String
Java Code
import java.util.Arrays;
public class SortString {
public static void main(String[] args) {
String str = "java";
char[] chars = str.toCharArray();
Arrays.sort(chars);
System.out.println(
new String(chars));
}
}Output
aajvExplanation
The string is converted into a character array and sorted.
Program 50: Find Duplicate Characters in a String
Java Code
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
char[] chars = str.toCharArray();
System.out.print(
"Duplicate Characters: ");
for(int i = 0; i < chars.length; i++) {
int count = 1;
for(int j = i + 1;
j < chars.length; j++) {
if(chars[i] == chars[j]
&& chars[i] != ' ') {
count++;
chars[j] = '0';
}
}
if(count > 1
&& chars[i] != '0') {
System.out.print(
chars[i] + " ");
}
}
}
}Output
Duplicate Characters: r g mExplanation
Nested loops compare characters and identify duplicates.
Modern Java Features Every Developer Should Learn
Learning Java programs is important, but modern Java development requires understanding newer language features.
Java Records
Records reduce boilerplate code.
Example
record Student(
String name,
int age
) {}Benefits
- Less code
- Immutable objects
- Better readability
Pattern Matching
Pattern Matching simplifies type checking.
Example
Object obj = "Java";
if(obj instanceof String str) {
System.out.println(str);
}Benefits
- Cleaner code
- Fewer explicit casts
- Better readability
Virtual Threads
Virtual Threads help build scalable applications.
Example
Thread.startVirtualThread(() -> {
System.out.println(
"Virtual Thread Running");
});Benefits
- Lightweight concurrency
- Better performance
- Easier multithreading
Switch Expressions
Modern Java supports concise switch statements.
Example
int day = 2;
String result = switch(day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
default -> "Unknown";
};
System.out.println(result);Text Blocks
Multi-line strings are easier with Text Blocks.
Example
String text = """
Welcome to Java
Programming Tutorial
2026 Edition
""";Java Interview Preparation Roadmap
Many beginners learn syntax but struggle during interviews.
Follow this roadmap:
Stage 1: Java Basics
- Variables
- Data Types
- Operators
- Input and Output
- Loops
- Conditional Statements
Stage 2: Object-Oriented Programming
- Classes
- Objects
- Inheritance
- Encapsulation
- Polymorphism
- Abstraction
Stage 3: Collections Framework
Learn:
- ArrayList
- LinkedList
- HashMap
- HashSet
- TreeMap
- PriorityQueue
Stage 4: Exception Handling
Topics:
- try-catch
- throw
- throws
- custom exceptions
Stage 5: Multithreading
Topics:
- Threads
- Runnable Interface
- Synchronization
- Executor Framework
- Virtual Threads
Stage 6: Java Streams
Topics:
- filter()
- map()
- reduce()
- collect()
Stage 7: Data Structures & Algorithms
Master:
- Arrays
- Strings
- Linked Lists
- Stacks
- Queues
- Trees
- Graphs
- Dynamic Programming
Stage 8: Spring Boot
Learn:
- REST APIs
- Dependency Injection
- JPA/Hibernate
- Security
- Microservices
Frequently Asked Questions
Is Java Still Worth Learning in 2026?
Yes.
Java remains one of the most in-demand programming languages for:
- Enterprise Software
- Backend Development
- Banking Systems
- Cloud Applications
- Android Development
Which Java Version Should Beginners Learn?
Start with Java 21 or newer.
Benefits:
- Long-Term Support (LTS)
- Modern Features
- Industry Adoption
How Many Java Programs Should Beginners Practice?
At least:
- 50 basic programs
- 50 string programs
- 50 array programs
This builds strong problem-solving skills.
Is Java Good for Coding Interviews?
Absolutely.
Many companies allow Java during coding rounds because of:
- Strong standard library
- Readability
- Performance
- Object-oriented design
Can I Learn Java Without DSA?
You can learn Java syntax without DSA.
However, for interviews and software engineering jobs, DSA knowledge is essential.
Common Mistakes Beginners Make
Avoid these mistakes:
1. Memorizing Code
Understand logic instead of memorizing programs.
2. Ignoring OOP Concepts
Object-Oriented Programming is the foundation of Java.
3. Skipping Collections
Collections are heavily used in real-world applications.
4. Avoiding Projects
Build practical applications after learning basics.
5. Ignoring Modern Java Features
Learn Records, Streams, Virtual Threads, and Pattern Matching.
Best Java Projects for Beginners
After completing these programs, build:
Beginner Projects
- Calculator
- Number Guessing Game
- Student Management System
- Library Management System
Intermediate Projects
- Banking Application
- Expense Tracker
- Chat Application
- Inventory Management System
Advanced Projects
- E-commerce Backend
- URL Shortener
- Task Management API
- Spring Boot Microservices
Final Thoughts
Java remains one of the most valuable programming languages to learn in 2026. By practicing these 50 programs, understanding Object-Oriented Programming, learning Collections, and exploring modern Java features, you'll develop a strong foundation for coding interviews and professional software development.
Don't just read the programs—type them, run them, modify them, and experiment with different inputs. Consistent practice is what transforms a beginner into a skilled Java developer.
Start with the basics, build projects, learn Data Structures and Algorithms, and gradually move toward frameworks like Spring Boot. With patience and regular practice, Java can open doors to exciting opportunities in software engineering, backend development, and enterprise applications.
Happy Coding!