Table of Contents
- Why Learn These Programs?
- Program #1: Print Your Name and Age
- Program #2: Simple Calculator (Add, Subtract, Multiply, Divide)
- Program #3: Check if a Number is Even or Odd
- Program #4: Find the Largest of Three Numbers
- Program #5: Print Multiplication Table
- Program #6: Check if a Number is Prime
- Program #7: Reverse a Number
- Program #8: Find Factorial of a Number
- Program #9: Print Patterns (Stars and Numbers)
- Program #10: Simple Array Operations
- Practice Tips for School Students
- Common Mistakes to Avoid
- Quick Reference: Java Basics
- Next Steps: Where to Go From Here
- Fun Project Ideas
- Frequently Asked Questions
- Conclusion
Learning Java doesn't have to be scary or boring. If you're a school student just starting with programming, you're in the right place. This article covers 10 essential Java programs that will teach you the fundamentals while being fun and practical.
These aren't random exercises—they're carefully chosen programs that build on each other, teaching you important concepts like loops, conditions, arrays, and methods. By the end, you'll have a solid foundation in Java programming.
Each program includes complete working code, simple explanations, and practice challenges. Let's start coding!
Perfect for Beginners
These programs are designed for school students (Classes 8-12) who are new to Java. No prior programming experience needed—we'll explain everything step by step!
Why Learn These Programs?
Before we dive into the code, here's why these specific programs matter:
- Build Strong Foundations: Each program teaches fundamental programming concepts
- School Exam Preparation: These programs commonly appear in school exams and practicals
- Logical Thinking: You'll develop problem-solving skills that help in all subjects
- Confidence Building: Start simple and gradually tackle more challenging programs
- Real-World Skills: Learn concepts used in actual software development
Ready? Let's write some code!
Program #1: Print Your Name and Age
Let's start with the absolute basics—printing output to the screen. This is your first step into Java programming!
What You'll Learn
- How to write a basic Java program
- Using System.out.println() to display output
- Understanding variables and data types
- Basic program structure
Solution
public class PrintNameAge {
public static void main(String[] args) {
// Declare variables
String name = "Rahul";
int age = 15;
// Print the information
System.out.println("Hello! My name is " + name);
System.out.println("I am " + age + " years old.");
// You can also use printf for formatted output
System.out.printf("In 5 years, I will be %d years old.%n", age + 5);
}
}
Explanation
- String name: Creates a variable to store text (your name)
- int age: Creates a variable to store a whole number (your age)
- System.out.println(): Prints text to the screen and moves to next line
- + operator: Joins (concatenates) text and variables together
Try This!
Change the name and age to your own. Add more lines to print your school name, favorite subject, or hobby!
Program #2: Simple Calculator (Add, Subtract, Multiply, Divide)
Let's build a calculator that can perform basic math operations. This teaches you about arithmetic operators and user input.
What You'll Learn
- Arithmetic operators (+, -, *, /)
- Taking input from users using Scanner
- Performing calculations
- Displaying results
Solution
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
// Create Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Get two numbers from user
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
// Perform all operations
double sum = num1 + num2;
double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2;
// Display results
System.out.println("\n--- Results ---");
System.out.println(num1 + " + " + num2 + " = " + sum);
System.out.println(num1 + " - " + num2 + " = " + difference);
System.out.println(num1 + " * " + num2 + " = " + product);
System.out.println(num1 + " / " + num2 + " = " + quotient);
scanner.close();
}
}
Explanation
- Scanner: A tool to read input from the keyboard
- nextDouble(): Reads a decimal number from user
- double: Data type for numbers with decimals
- Operators: + adds, - subtracts, * multiplies, / divides
Challenge
Add a modulus operation (%) to find the remainder. Also, add error handling for division by zero!
Program #3: Check if a Number is Even or Odd
This program introduces you to conditional statements—making decisions in your code based on conditions.
What You'll Learn
- If-else statements for decision making
- Modulus operator (%) to find remainders
- Boolean conditions (true/false)
- Program flow control
Solution
import java.util.Scanner;
public class EvenOddChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Check if number is even or odd
if (number % 2 == 0) {
System.out.println(number + " is an EVEN number.");
} else {
System.out.println(number + " is an ODD number.");
}
// Bonus: Check if positive, negative, or zero
if (number > 0) {
System.out.println("It is also a POSITIVE number.");
} else if (number < 0) {
System.out.println("It is also a NEGATIVE number.");
} else {
System.out.println("The number is ZERO.");
}
scanner.close();
}
}
Explanation
- % operator: Gives the remainder after division (5 % 2 = 1)
- if-else: Executes different code based on conditions
- == operator: Checks if two values are equal
- Logic: If number divided by 2 has remainder 0, it's even
Program #4: Find the Largest of Three Numbers
Learn to compare multiple values and find the maximum—a common programming task.
What You'll Learn
- Nested if-else statements
- Comparison operators (>, <, >=, <=)
- Logical operators (&&, ||)
- Finding maximum values
Solution
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get three numbers from user
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();
// Method 1: Using if-else
int largest;
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
System.out.println("\nThe largest number is: " + largest);
// Method 2: Using Math.max()
int max = Math.max(num1, Math.max(num2, num3));
System.out.println("Using Math.max(): " + max);
// Bonus: Find smallest too
int smallest = Math.min(num1, Math.min(num2, num3));
System.out.println("The smallest number is: " + smallest);
scanner.close();
}
}
Explanation
- && operator: Means 'AND' - both conditions must be true
- >= operator: Greater than or equal to
- Math.max(): Built-in function to find maximum of two numbers
- Nested Math.max(): Compare first two, then compare result with third
Try This!
Modify the program to find the largest of 5 numbers. Can you do it without using Math.max()?
Program #5: Print Multiplication Table
Your first loop! Learn to repeat actions automatically—one of the most powerful concepts in programming.
What You'll Learn
- For loops for repetition
- Loop variables and counters
- Formatted output
- Automating repetitive tasks
Solution
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("\nMultiplication Table of " + number + ":");
System.out.println("----------------------------");
// Using for loop to print table
for (int i = 1; i <= 10; i++) {
int result = number * i;
System.out.println(number + " x " + i + " = " + result);
}
// Bonus: Print table in reverse
System.out.println("\nReverse Table:");
for (int i = 10; i >= 1; i--) {
System.out.println(number + " x " + i + " = " + (number * i));
}
scanner.close();
}
}
Explanation
- for loop: Repeats code a specific number of times
- i = 1: Starting value (initialization)
- i <= 10: Condition to continue (while this is true, loop continues)
- i++: Increment (add 1 to i after each loop)
- Loop body: Code inside { } runs each time
Program #6: Check if a Number is Prime
Prime numbers are special—they're only divisible by 1 and themselves. This program teaches you to check mathematical properties.
What You'll Learn
- While loops
- Boolean variables (true/false)
- Break statement to exit loops
- Mathematical logic
Solution
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Numbers less than 2 are not prime
if (number < 2) {
System.out.println(number + " is NOT a prime number.");
return;
}
// Assume number is prime
boolean isPrime = true;
// Check if number is divisible by any number from 2 to number-1
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
isPrime = false;
break; // No need to check further
}
}
// Display result
if (isPrime) {
System.out.println(number + " is a PRIME number!");
} else {
System.out.println(number + " is NOT a prime number.");
}
// Bonus: Print all prime numbers up to the entered number
System.out.println("\nPrime numbers up to " + number + ":");
for (int num = 2; num <= number; num++) {
boolean prime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
prime = false;
break;
}
}
if (prime) {
System.out.print(num + " ");
}
}
scanner.close();
}
}
Explanation
- boolean isPrime: Variable that stores true or false
- break: Exits the loop immediately
- Logic: If number is divisible by any number (remainder = 0), it's not prime
- Optimization: Only check up to number/2 (no number larger than half can divide evenly)
Program #7: Reverse a Number
Learn to manipulate individual digits of a number—a fundamental skill for many programming problems.
What You'll Learn
- While loops with conditions
- Extracting digits using modulus
- Building numbers digit by digit
- Mathematical operations
Solution
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int original = number; // Save original number
int reversed = 0;
// Reverse the number
while (number != 0) {
int digit = number % 10; // Get last digit
reversed = reversed * 10 + digit; // Add digit to reversed number
number = number / 10; // Remove last digit
}
System.out.println("Original number: " + original);
System.out.println("Reversed number: " + reversed);
// Bonus: Check if number is palindrome
if (original == reversed) {
System.out.println(original + " is a PALINDROME!");
} else {
System.out.println(original + " is NOT a palindrome.");
}
scanner.close();
}
}
Explanation
- number % 10: Gets the last digit (1234 % 10 = 4)
- number / 10: Removes the last digit (1234 / 10 = 123)
- reversed * 10 + digit: Builds reversed number (0 → 4 → 43 → 432 → 4321)
- Palindrome: Number that reads same forwards and backwards (121, 1331)
Challenge
Try reversing a string instead of a number. Hint: Use a for loop to go through the string backwards!
Program #8: Find Factorial of a Number
Factorial is a mathematical operation where you multiply a number by all positive integers less than it. Great for learning recursion!
What You'll Learn
- Recursion (function calling itself)
- Iterative vs recursive approaches
- Base cases in recursion
- Mathematical calculations
Solution
import java.util.Scanner;
public class Factorial {
// Method 1: Using loop (Iterative)
public static long factorialIterative(int n) {
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i; // Same as: result = result * i
}
return result;
}
// Method 2: Using recursion
public static long factorialRecursive(int n) {
// Base case: factorial of 0 or 1 is 1
if (n == 0 || n == 1) {
return 1;
}
// Recursive case: n! = n × (n-1)!
return n * factorialRecursive(n - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long resultIterative = factorialIterative(number);
System.out.println("Factorial (Iterative): " + number + "! = " + resultIterative);
long resultRecursive = factorialRecursive(number);
System.out.println("Factorial (Recursive): " + number + "! = " + resultRecursive);
// Show the calculation
System.out.print("\nCalculation: " + number + "! = ");
for (int i = number; i >= 1; i--) {
System.out.print(i);
if (i > 1) System.out.print(" × ");
}
System.out.println(" = " + resultIterative);
}
scanner.close();
}
}
Explanation
- Factorial: 5! = 5 × 4 × 3 × 2 × 1 = 120
- Iterative: Uses a loop to multiply numbers
- Recursive: Function calls itself with smaller values
- Base case: Stopping condition for recursion (0! = 1, 1! = 1)
- long: Used instead of int because factorials get very large
Program #9: Print Patterns (Stars and Numbers)
Pattern printing is fun and teaches you nested loops—loops inside loops!
What You'll Learn
- Nested loops (loop inside another loop)
- Understanding rows and columns
- Pattern logic and visualization
- Creative programming
Solution
import java.util.Scanner;
public class PatternPrinting {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();
// Pattern 1: Right-angled triangle
System.out.println("\nPattern 1: Right Triangle");
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Pattern 2: Inverted triangle
System.out.println("\nPattern 2: Inverted Triangle");
for (int i = rows; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
// Pattern 3: Pyramid
System.out.println("\nPattern 3: Pyramid");
for (int i = 1; i <= rows; i++) {
// Print spaces
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
// Print stars
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("* ");
}
System.out.println();
}
// Pattern 4: Number triangle
System.out.println("\nPattern 4: Number Triangle");
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
// Pattern 5: Floyd's Triangle
System.out.println("\nPattern 5: Floyd's Triangle");
int number = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(number + " ");
number++;
}
System.out.println();
}
scanner.close();
}
}
Explanation
- Outer loop: Controls rows (how many lines)
- Inner loop: Controls columns (what to print in each line)
- Nested loops: Inner loop runs completely for each iteration of outer loop
- Spaces: Used to create alignment in pyramid patterns
- Floyd's Triangle: Continuous numbers arranged in triangular form
Challenge
Try creating a diamond pattern or a hollow square! These require combining multiple pattern techniques.
Program #10: Simple Array Operations
Arrays let you store multiple values in one variable. This is your introduction to data structures!
What You'll Learn
- Creating and initializing arrays
- Accessing array elements
- Looping through arrays
- Common array operations (sum, average, max, min)
Solution
import java.util.Scanner;
public class ArrayOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many numbers do you want to enter? ");
int size = scanner.nextInt();
// Create array
int[] numbers = new int[size];
// Input array elements
System.out.println("Enter " + size + " numbers:");
for (int i = 0; i < size; i++) {
System.out.print("Number " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}
// Display array
System.out.print("\nYour numbers: ");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
// Calculate sum
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("\nSum: " + sum);
// Calculate average
double average = (double) sum / size;
System.out.println("Average: " + average);
// Find maximum
int max = numbers[0];
for (int num : numbers) {
if (num > max) {
max = num;
}
}
System.out.println("Maximum: " + max);
// Find minimum
int min = numbers[0];
for (int num : numbers) {
if (num < min) {
min = num;
}
}
System.out.println("Minimum: " + min);
// Search for a number
System.out.print("\nEnter a number to search: ");
int search = scanner.nextInt();
boolean found = false;
int position = -1;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == search) {
found = true;
position = i;
break;
}
}
if (found) {
System.out.println(search + " found at position " + (position + 1));
} else {
System.out.println(search + " not found in the array.");
}
scanner.close();
}
}
Explanation
- int[] numbers: Declares an array of integers
- new int[size]: Creates array with specified size
- numbers[i]: Accesses element at index i (arrays start at 0)
- Enhanced for loop: for (int num : numbers) - easier way to loop through arrays
- numbers.length: Property that gives the size of array
Congratulations!
You've completed all 10 programs! You now know variables, loops, conditions, methods, recursion, and arrays—the building blocks of Java programming!
Practice Tips for School Students
Now that you've seen all 10 programs, here's how to practice effectively:
1. Type, Don't Copy-Paste
Always type the code yourself. Your fingers need to learn the syntax, and typing helps you remember better than copying.
2. Experiment and Break Things
Change values, modify conditions, add new features. See what happens when you break the code—that's how you learn!
3. Explain to Someone Else
Try teaching these programs to a friend or family member. If you can explain it, you truly understand it.
4. Practice Daily
Even 20-30 minutes daily is better than 3 hours once a week. Consistency builds skills faster.
5. Create Your Own Variations
- Modify the calculator to include more operations
- Create different pattern designs
- Build a simple grade calculator using arrays
- Make a number guessing game
- Create a simple quiz program
Study Schedule
Week 1: Programs 1-3 | Week 2: Programs 4-6 | Week 3: Programs 7-8 | Week 4: Programs 9-10 | Week 5: Create your own programs!
Common Mistakes to Avoid
- Forgetting semicolons (;): Every statement in Java needs to end with a semicolon
- Case sensitivity: 'Number' and 'number' are different in Java
- Array index errors: Remember arrays start at 0, not 1
- Not closing Scanner: Always use scanner.close() at the end
- Integer division: 5/2 gives 2, not 2.5 (use double for decimals)
- Infinite loops: Make sure your loop condition eventually becomes false
Quick Reference: Java Basics
Here's a handy reference for the concepts you've learned:
Data Types
- int: Whole numbers (5, -10, 1000)
- double: Decimal numbers (3.14, -0.5, 99.99)
- String: Text ("Hello", "Java")
- boolean: True or false
- char: Single character ('A', '5', '