Introduction
Learning Java is easier when you practice coding and use simple examples. Java programs help beginners understand concepts such as variables, operators, if statements, loops, strings, and arrays. Beginning with Java programs builds a strong foundation and improves logical thinking. This guide covers 15 beginner Java programs with code examples, outputs, and clear explanations to aid hands‑on learning. Each Java example also shows patterns that users can use for more advanced tasks. Explore our Java Course Syllabus to begin your programming journey.
Why Should Beginners Practise Java Programs?
Practising Java programs links theory with coding. Instead of just memorising syntax, beginners can learn how Java statements combine to create results.
Regular coding practice helps to:
- Understand Java variables, data types, operators, and control statements.
- Identify and correct common programming errors.
- Develop logical thinking through small coding challenges.
- Build a foundation for Java object‑oriented programming and interview preparation.
Understand Java concepts step by step with beginner-friendly Java Tutorials.
Basic Java Programs for Beginners
These beginner examples introduce basic Java syntax, arithmetic operations, and variable manipulation.
1. Hello World Program
The Hello World program is a starting point for Java beginners. It demonstrates the structure of a Java class and the main() method, where program execution begins.
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello, World!”);
}
}
Output:
Hello, World!
The System.out.println() statement displays text in the console. The class name should match the filename when the class is declared as public.
2. Add Two Numbers
This program shows how to keep numbers in variables and add them with the + sign.
public class AddNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
int sum = a + b;
System.out.println(“Sum: ” + sum);
}
}
Output:
Sum: 30
The values a and b hold the numbers. Their sum is assigned to sum and printed. Changing a and b lets you try the idea with other numbers.
3. Check Whether a Number Is Even or Odd
A number is even if it is divisible by two without a remainder. The modulus operator (%) shows the leftover after division.
public class EvenOdd {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println(“Even”);
} else {
System.out.println(“Odd”);
}
}
}
Output:
Odd
The condition checks whether the remainder is zero. If it is, the number is even; otherwise, it is odd.
Apply programming concepts through practical Java Project Ideas.
4. Find the Largest of Two Numbers
Conditional statements can compare two values and identify the larger one.
public class LargestNumber {
public static void main(String[] args) {
int a = 25;
int b = 40;
if (a > b) {
System.out.println(a + ” is larger”);
} else if (b > a) {
System.out.println(b + ” is larger”);
} else {
System.out.println(“Both numbers are equal”);
}
}
}
Output:
40 is larger
The if and else if parts compare the numbers. The final else covers the case when both values are the same.
5. Swap Two Numbers
Swapping means giving each variable the other’s value. A temporary variable can make this simple.
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 = 10
The original value of a is kept in temp. Then a takes the value of b, and b takes the value stored in temp.
Easy Java Programs Using Conditional Statements and Loops
1. Check Whether a Number Is Positive, Negative, or Zero
This program uses statements to classify a number based on its value.
public class NumberCheck {
public static void main(String[] args) {
int number = -5;
if (number > 0) {
System.out.println(“Positive”);
} else if (number < 0) {
System.out.println(“Negative”);
} else {
System.out.println(“Zero”);
}
}
}
Output:
Negative
The first condition checks for a positive value, and the second checks for a negative value. If neither condition is true, the number is zero.
Prepare for job interviews with essential Java Interview Questions and Answers.
2. Find the Factorial of a Number
The factorial of a non-negative integer is the product of all positive integers up to that number. For example, (5! = 5 \times 4 \times 3 \times 2 \times 1 = 120). The factorial of zero is one.
public class Factorial {
public static void main(String[] args) {
int number = 5;
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println(“Factorial: ” + factorial);
}
}
Output:
Factorial: 120
The loop multiplies factorial by each integer from one to five. This example uses a fixed non‑negative value. Larger factorials can exceed the range of Java’s type.
3. Generate a Multiplication Table
A for loop can generate a multiplication table by repeating a calculation with different values.
public class MultiplicationTable {
public static void main(String[] args) {
int number = 5;
for (int i = 1; i <= 10; i++) {
System.out.println(number + ” x ” + i
+ ” = ” + (number * i));
}
}
}
Output:
5 x 1 = 5
5 x 2 = 10
…
5 x 10 = 50
The loop runs ten times. During each iteration, the number is multiplied by the current value of i.
4. Check Whether a Number Is Prime
A prime number is an integer greater than one that has two positive divisors: one and itself.
public class PrimeCheck {
public static void main(String[] args) {
int number = 17;
boolean isPrime = number > 1;
for (int i = 2; i <= number / i && isPrime; i++) {
if (number % i == 0) {
isPrime = false;
}
}
System.out.println(isPrime ? “Prime” : “Not prime”);
}
}
Output:
Prime
The loop checks divisors starting from two. It only needs to test divisors up to the square root of the number, which the condition i <= number / i checks without multiplying i by itself.
Learn about Java Developer Salary trends for freshers and experienced professionals.
5. Print the Fibonacci Series
The Fibonacci series begins with zero and one. Each subsequent number is the sum of the two preceding numbers.
public class Fibonacci {
public static void main(String[] args) {
int first = 0;
int second = 1;
for (int i = 1; i <= 10; i++) {
System.out.print(first + ” “);
int next = first + second;
first = second;
second = next;
}
}
}
Output:
0 1 1 2 3 5 8 13 21 34
The program prints ten terms. After each iteration, the variables are updated to prepare the pair of numbers.
Java Programs for Strings and Arrays
Strings store text while arrays hold values of the same type. These examples introduce operations used in everyday Java programming.
1. Reverse a String
Reversing a string means showing its characters in reverse order. Java’s StringBuilder provides a method for this operation.
public class ReverseString {
public static void main(String[] args) {
String text = “Java”;
String reversed = new StringBuilder(text)
.reverse().toString();
System.out.println(reversed);
}
}
Output:
avaJ
The reverse() method reverses the character sequence, and toString() converts the result into a string.
2. Check Whether a String Is a Palindrome
A palindrome reads the same forward and backward. Examples are madam and level.
public class Palindrome {
public static void main(String[] args) {
String text = “madam”;
String reversed = new StringBuilder(text)
.reverse().toString();
if (text.equals(reversed)) {
System.out.println(“Palindrome”);
} else {
System.out.println(“Not a palindrome”);
}
}
}
Output:
Palindrome
The program compares the string with its reversed version using equals(). This example is case-sensitive. Does not strip spaces or punctuation before comparing.
3. Find the Largest Element in an Array
An array can hold values under one variable name. Finding the largest element means comparing those values.
public class LargestArrayElement {
public static void main(String[] args) {
int[] numbers = {12, 45, 7, 89, 23};
int largest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
System.out.println(“Largest: ” + largest);
}
}
Output:
Largest: 89
The program begins with the element as the largest value. It checks each remaining element. Updates the largest value whenever it finds a bigger one.
Build job-ready programming skills through our practical Java Course in Chennai.
4. Calculate the Sum of Array Elements
Adding all array elements is an exercise to learn loops and array indexing.
public class ArraySum {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
int sum = 0;
for (int number: numbers) {
sum += number;
}
System.out.println(“Sum: ” + sum);
}
}
Output:
Sum: 100
The enhanced for loop visits each element and adds it to sum. This loop is handy when every element must be processed without using an index.
5. Count Vowels in a String
Vowels are the letters a, e, i, o, and u. This program counts their occurrences in a string without treating uppercase and lowercase letters differently.
public class CountVowels {
public static void main(String[] args) {
String text = “Java Programming”;
int count = 0;
for (int i = 0; i < text.length(); i++) {
char ch = Character.toLowerCase(text.charAt(i));
if (ch == ‘a’ || ch == ‘e’ || ch == ‘i’
|| ch == ‘o’ || ch == ‘u’) {
count++;
}
}
System.out.println(“Vowels: ” + count);
}
}
Output:
Vowels: 5
The loop checks each character, turns it to lowercase, and tests whether it is a vowel. The counter rises whenever a match is found.
Conclusion
Practising Java programs helps beginners build a basic foundation in programming. Working through examples and slowly moving to harder tasks makes learning easier. Regular coding, testing different inputs, and correcting errors build confidence and prepare learners for advanced Java concepts and practical development projects. – Get expert career guidance from a trusted Training and Placement Institute in Chennai.
