Java How-To Examples – Practical Snippets with Explanations (2025 Edition)
Introduction – Learn Java by Doing
In Java, practicing small problem-solving examples helps build a strong foundation. This guide provides simple, practical code examples that cover basic operations, string manipulations, array processing, loops, conditionals, and working with data structures.
In this guide, you’ll learn:
- How to solve common coding tasks using Java
- Understand how each snippet works step-by-step
- Strengthen your fundamentals with hands-on code
Topics Covered with Explanations
1. Add Two Numbers
Explanation: Adding two integers using the + operator.
int a = 10, b = 20;
int sum = a + b;
System.out.println("Sum = " + sum);
Code Explanation:
aandbare declared and initialized.- Their sum is stored in
sum. - The result is printed using
System.out.println().
2. Count Words in a String
Explanation: Count the number of words in a string using .split() method.
String text = "Java is powerful";
int wordCount = text.split("\\s+").length;
System.out.println("Words: " + wordCount);
Code Explanation:
split("\\s+")splits the string on whitespace..lengthgives the total number of words.
3. Reverse a String
Explanation: Reversing characters using StringBuilder.
String str = "Java";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed);
Code Explanation:
StringBuilderis used for mutable strings.reverse()reverses the characters.toString()converts it back to a string.
4. Sum of Array Elements
Explanation: Iterate through an array and add all elements.
int[] numbers = {10, 20, 30};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum = " + sum);
Code Explanation:
- A for-each loop adds each element to
sum. - The total is printed after the loop.
5. Convert String to Array
Explanation: Convert a comma-separated string to an array.
String str = "Java,Python,C++";
String[] langs = str.split(",");
System.out.println(Arrays.toString(langs));
Code Explanation:
.split(",")splits the string into an array.Arrays.toString()displays the array content.
6. Sort an Array
Explanation: Sorting an integer array in ascending order.
int[] arr = {5, 2, 8, 1};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
Code Explanation:
Arrays.sort()performs in-place sorting.- The sorted array is printed.
7. Find Array Average
Explanation: Calculate the average of array elements.
int[] values = {10, 20, 30};
int sum = 0;
for (int v : values) sum += v;
double avg = (double) sum / values.length;
System.out.println("Average = " + avg);
Code Explanation:
- Total sum is divided by the number of elements using
.length. - Casting ensures correct decimal result.
8. Find Smallest Element
Explanation: Find the minimum value in an array.
int[] nums = {4, 7, 1, 9};
int min = nums[0];
for (int n : nums) {
if (n < min) min = n;
}
System.out.println("Min = " + min);
Code Explanation:
- Assume the first value as smallest.
- Update
minif a smaller value is found during loop.
9. Loop Through ArrayList
Explanation: Looping over an ArrayList using for-each loop.
ArrayList<String> list = new ArrayList<>(List.of("Java", "Python", "C"));
for (String lang : list) {
System.out.println(lang);
}
Code Explanation:
List.of()initializes the list.- The loop prints each element.
10. Loop Through HashMap
Explanation: Access keys and values in a HashMap.
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Code Explanation:
entrySet()returns key-value pairs.- Each entry is printed.
11. Loop Through Enum
Explanation: Use .values() to loop through enum constants.
enum Days { MON, TUE, WED }
for (Days d : Days.values()) {
System.out.println(d);
}
Code Explanation:
.values()returns all constants.- Loop prints each day.
12. Area of Rectangle
Explanation: Calculate area using formula length * width.
int length = 5, width = 3;
int area = length * width;
System.out.println("Area = " + area);
Code Explanation:
- Variables hold dimensions.
- Result is computed and printed.
13. Even or Odd Number
Explanation: Use modulus operator to check parity.
int num = 6;
System.out.println(num % 2 == 0 ? "Even" : "Odd");
Code Explanation:
% 2 == 0checks if number is divisible by 2.
14. Positive or Negative Number
Explanation: Check sign of number using conditional blocks.
int number = -5;
if (number > 0)
System.out.println("Positive");
else if (number < 0)
System.out.println("Negative");
else
System.out.println("Zero");
Code Explanation:
- Conditions identify sign status of the number.
15. Square Root of a Number
Explanation: Use Math.sqrt() to calculate square root.
double n = 16;
double sqrt = Math.sqrt(n);
System.out.println("Square root = " + sqrt);
Code Explanation:
Math.sqrt()returns square root as adouble.
🎲 16. Generate Random Number
Explanation: Use Math.random() to get a value between 0 and 100.
int rand = (int)(Math.random() * 100);
System.out.println("Random: " + rand);
Code Explanation:
Math.random()gives value [0.0, 1.0)- Multiply and cast to get an integer range.
Summary – Recap & Next Steps
These how-to examples are your quick reference guide for writing effective Java code.
Key Takeaways:
- Learn core Java operations through real-world snippets
- Practice string, array, and math problems
- Loop through collections and enums
- Understand conditionals and conversions
Next Steps:
- Try modifying these examples to accept user input
- Combine multiple examples into a mini-project
- Explore more how-to tasks like file reading, regex, and recursion
Frequently Asked Questions (FAQs)
Can these examples be used in coding interviews?
Yes, they demonstrate common logic and help you explain your thinking clearly.
How can I take input instead of hardcoding values?
Use Scanner for user input. Example: Scanner sc = new Scanner(System.in);
Are these examples valid for Java 17 and newer?
Yes. All code is compatible with Java 8 and above.
Can I use these examples for Android development?
Yes. Logic remains the same, but output goes to UI components instead of console.
Where can I practice these online?
Try platforms like Replit, JDoodle, or use an IDE like IntelliJ/Eclipse.
Share Now :
