Introduction
Java is a beginner-friendly, versatile programming language known for its simplicity, reliability, and wide use in web development, Android applications, and enterprise software. Its object-oriented nature makes it easy for new programmers to understand core coding concepts like classes, methods, and objects.
Learning Java through practical code samples is one of the most effective ways to master programming. Instead of memorizing syntax, you gain real problem-solving experience by writing, running, and modifying code yourself.
In this guide, you’ll find hands-on Java examples with detailed explanations and outputs, making it easy to follow along and understand how each piece of code works in practice.
Setting Up Java
Before you start coding in Java, you’ll need a few essential tools to create, compile, and run your programs.
1. What You Need
- JDK (Java Development Kit): Includes all tools needed to compile and run Java programs.
- IDE (Integrated Development Environment): Software like IntelliJ IDEA, Eclipse, or VS Code helps you write and manage code easily with features like syntax highlighting and debugging.
2. Steps to Run Your First Java Program
- Install the JDK from Oracle’s official website.
- Install an IDE such as IntelliJ IDEA or Eclipse.
- Create a new Java project and add a file named
Main.java. - Write your first program:
public class Main { public static void main(String[] args) { System.out.println("Hello, Java!"); } } - Run the program — you should see the output:
Hello, Java!
3. Online Alternatives for Beginners
If you don’t want to install anything yet, you can start coding instantly using free online Java compilers such as:
These platforms let you write, run, and share Java code right in your browser — perfect for quick learning and practice.
Basic Java Code Samples with Output

These simple Java programs will help you understand core programming concepts step by step. Each example includes code, an explanation, and expected output for better understanding.
3.1 Hello World Program
Purpose: Demonstrates the basic structure of a Java program.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
classdefines a Java class.main()is the entry point of every Java application.System.out.println()prints text to the console.
Output:
Hello, World!
3.2 Adding Two Numbers
Purpose: Shows how to use variables and arithmetic operators.
public class AddNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
int sum = a + b;
System.out.println("Sum: " + sum);
}
}
Explanation:
intstores integer values.- The
+operator performs addition.
Output:
Sum: 30
3.3
Purpose: Uses conditional statements to check if a number is even or odd.
public class EvenOdd {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0)
System.out.println(number + " is Even");
else
System.out.println(number + " is Odd");
}
}
Explanation:
%gives the remainder of a division.- If the remainder is 0, the number is even; otherwise, it’s odd.
Output:
7 is Odd
3.4 Largest Number Finder
Purpose: Compares two numbers to find the larger one.
public class LargestNumber {
public static void main(String[] args) {
int a = 25, b = 40;
if (a > b)
System.out.println(a + " is larger");
else
System.out.println(b + " is larger");
}
}
Explanation:
- The
>operator checks which value is greater.
Output:
40 is larger
3.5 Printing Numbers Using Loops

Purpose: Introduces the for loop for repetitive tasks.
public class NumberLoop {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Explanation:
- The loop starts at
1and runs untili <= 5. - Each iteration prints the current value of
i.
Output:
1
2
3
4
5
3.6 Factorial of a Number
Purpose: Uses a loop to calculate the factorial of a number.
public class Factorial {
public static void main(String[] args) {
int number = 5;
int fact = 1;
for (int i = 1; i <= number; i++) {
fact *= i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
}
Explanation:
- The
*=operator multiplies and stores the result. 5! = 1×2×3×4×5 = 120.
Output:
Factorial of 5 is: 120
3.7 Reverse a String
Purpose: Demonstrates string manipulation using loops.
public class ReverseString {
public static void main(String[] args) {
String str = "Java";
String rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev += str.charAt(i);
}
System.out.println("Reversed String: " + rev);
}
}
Explanation:
str.charAt(i)accesses each character.- The loop appends characters in reverse order.
Output:
Reversed String: avaJ
3.8 Sum of Array Elements
Purpose: Demonstrates arrays and enhanced for loops.
public class ArraySum {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum of array elements: " + sum);
}
}
Explanation:
int[] numbersdefines an array of integers.- The enhanced
forloop iterates through each element.
Output:
Sum of array elements: 150
Key Java Concepts Explained
Before diving deeper into real-world programs, it’s important to understand the core concepts that form the foundation of every Java program.
1. Variables and Data Types
Variables are containers for storing data, and data types define what kind of data a variable can hold.
Examples:
int age = 25; // Integer type
double price = 99.99; // Decimal type
char grade = 'A'; // Single character
boolean isJavaFun = true; // True or false value
Tip: Always choose the correct data type to save memory and ensure accuracy.
2. Operators
Operators perform actions on variables and values.
- Arithmetic Operators:
+,-,*,/,% - Relational Operators:
==,!=,>,<,>=,<= - Logical Operators:
&&(AND),||(OR),!(NOT)
Example:
int a = 10, b = 5;
System.out.println(a > b); // true
System.out.println((a > 5) && (b < 10)); // true
3. Loops
Loops allow you to execute code repeatedly without writing it multiple times.
for loop:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
while loop:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
do-while loop:
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
Tip: Use loops for tasks like counting, iterating arrays, or processing lists of data.
4. Conditional Statements
Conditionals control the flow of execution based on logical conditions.
if-else statement:
int number = 10;
if (number % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
switch statement:
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Other day");
}
5. Arrays
Arrays store multiple values of the same type in a single variable.
Example (Single-Dimensional):
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers[2]); // Output: 30
Example (Multi-Dimensional):
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // Output: 6
Tip: Arrays make it easier to handle lists or collections of data efficiently.
you may also like to read these posts:
Smart Budget Planning for Families: A Practical Guide to Financial Harmony
Discover the Beauty of Indonesian Traditional Fashion Styles
Learn Java Easily Online with Simple Coding Examples
Easy Core Java Tutorials for Beginners to Start Coding
Common Errors Beginners Make
When learning Java, it’s normal to encounter mistakes. Understanding and fixing these early helps you become a better programmer. Below are some common beginner errors and tips to debug them effectively.
1. Missing Semicolons (;)
Every Java statement must end with a semicolon. Forgetting one will cause a syntax error.
Example (Error):
System.out.println("Hello World") // Missing semicolon
Fix:
System.out.println("Hello World");
Tip: Check error messages in your IDE — they often highlight the exact line where the semicolon is missing.
2. Wrong Data Type Usage
Java is a strongly typed language, meaning variables must store values of the correct type.
Example (Error):
int age = "twenty"; // String assigned to an int variable
Fix:
int age = 20;
Tip: Always match variable types with the data they represent.
3. Forgetting to Close Braces {}
Every opening { must have a matching closing }. Missing braces cause compilation errors or misaligned logic.
Example (Error):
if (x > 0) {
System.out.println("Positive number");
Fix:
if (x > 0) {
System.out.println("Positive number");
}
Tip: Use proper indentation — it helps visually match opening and closing braces.
4. Misunderstanding Scope of Variables
Variables declared inside a method or loop are local and cannot be used outside their scope.
Example (Error):
if (true) {
int number = 10;
}
System.out.println(number); // Error: number cannot be resolved
Fix:
int number;
if (true) {
number = 10;
}
System.out.println(number);
Tip: Declare variables outside loops or blocks if you need to use them later in the program.
5. Tips on How to Debug Java Programs
- Read error messages carefully: They tell you what went wrong and where.
- Use print statements: Print variable values to trace program flow.
- Run programs frequently: Test after small changes to isolate errors.
- Use an IDE debugger: Tools like IntelliJ IDEA or Eclipse let you step through code line by line.
- Stay calm: Debugging is a skill — every error helps you learn something new.
Tips for Practicing Java Efficiently
Consistent and smart practice is the key to mastering Java. Instead of just reading code, write it, modify it, and experiment with it to strengthen your understanding.
1. Practice Every Code Example Manually
Don’t just copy and paste — type each program yourself. This helps you remember syntax, understand structure, and catch common mistakes early.
2. Change Inputs and Observe Different Outputs
After running an example, experiment with different input values. This helps you understand how your code behaves in various situations and improves logical thinking.
Example:
If a program checks even or odd numbers, try values like 0, -5, or 12 to test all conditions.
3. Use Comments to Explain Each Line of Your Code
Adding comments helps you understand your logic clearly and makes your code easier to revisit later.
Example:
int sum = a + b; // Adds two numbers and stores result in sum
4. Build Small Programs Using Combinations of Basic Examples
Once you’re comfortable with simple programs, combine multiple concepts to create small projects — like a calculator, grade checker, or login simulation.
This helps you see how different Java concepts work together.
5. Gradually Move to Advanced Topics
After mastering basics, start learning:
- Object-Oriented Programming (OOP) – classes, objects, and inheritance.
- Collections Framework – ArrayList, HashMap, and Sets.
- File Handling and Exception Handling for real-world applications.
Pro Tip: Practice daily — even short 20-minute sessions make a big difference over time.
Faqs:
Are these basic Java code samples suitable for beginners?
Yes, these basic Java code samples with output are designed for beginners to understand core programming concepts step by step.
Can I run these Java programs without installing Java?
Yes, you can use online IDEs like Replit, JDoodle, or HackerRank to run Java programs directly in your browser.
What concepts will I learn from these examples?
You will learn variables, loops, conditional statements, arrays, arithmetic operations, and basic string manipulation.
How can I practice these examples effectively?
Try modifying values, changing conditions, and creating your own variations to see how outputs change and to strengthen your understanding.
What should I do after mastering these basic Java code samples?
Once comfortable, you can move on to object-oriented programming, file handling, Java Collections, and small real-world Java projects.
Conclusion
Practicing basic Java code samples with output is the perfect way for beginners to build a strong foundation in Java programming. By understanding variables, loops, conditionals, arrays, and string operations through practical examples, you can develop problem-solving skills and confidence in coding. Consistent practice and experimentation with these simple programs will prepare you for more advanced Java concepts and real-world applications.
