Skip to content

A Guide to Java Programming Examples

Updated on:
Updated by: Dina Essawy

With its intricate concepts and examples, diving headfirst into the vast world of Java programming can be a bit like trying to solve the most complex tea-time crossword puzzle. Indeed, even those seasoned in coding are occasionally found scratching their heads. However, refuse to let this put you off.

A staggering 95% of enterprise desktops rely on Java, making it one of the most important languages in our business landscape. This blog will serve as your guiding light through key Java programming examples, such as the Fibonacci series, prime numbers and arrays, and others—all designed to fine-tune your skills within this prevalent language.

A guide to java programming examples
Java examples programming

Let us explore some popular Java programming examples that you can use to develop a wide variety of applications, including web applications, mobile applications, enterprise applications, and scientific computing. These programs include the Fibonacci series, prime number program, palindrome program, factorial program, and Armstrong numbers.

Fibonacci Series

In this section, we will discuss the Fibonacci series in Java Programming. It’s a fun part of popular Java examples. The Fibonacci series is unique. It all starts with 0 and 1. Then comes a sequence of numbers, each number always being the sum of the previous two numbers. So, the series goes as follows: 0, 1, 1, 2, 3, 5, 8, and so on.

The coding for this series uses a method we call Fibonacci coding. This method turns an integer into a binary number using the Fibonacci representation. You can display this series using your own Java program. There are many ways to generate this series in Java programming; you can use top-down approaches, while others prefer bottom-up methods.

Example Solution

Code
int n1 = 0;
int n2 = 1;
int n3;
int count = 15;
int i;

System.out.println(n1 + " " + n2);
for (i = 2; i < count; ++i) 
{
     n3 = n1 + n2;
     System.out.print(" " + n3);
     n1 = n2;
     n2 = n3;
}

Output
1 2 3 5 8 13 21 34 55 89 144 233 377

Prime Number Program

One of the popular Java examples is the Prime Number Program. This program is one way to show off your skills. It uses a logic that checks if numbers are only divisible by 1 and themselves. These unique numbers are what we call prime numbers. The opposite of prime numbers is composite numbers.

You can set up this program using for loops and while loops. Your goal is to determine whether a number given to you is a prime number. An interesting fact: apart from 2, all prime numbers are odd.

The Prime Number Program helps you understand computation and iteration in Java. This program becomes fun with the use of integer division, boolean condition, and iterative calculation. Get ready to delve into the algorithm of the Prime Number Program.

Example Solution

Code
int number = 37;
boolean isPrime = false;
for (int i = 2; i <= number/2; ++i) {
      if (number % i == 0) {
            isPrime = true;
            break;
      }
}

if (!isPrime)
      System.out.println(number + " is a prime number!");
else
      System.out.println(number + " is not a prime number!");

Output
37 is a prime number!

Palindrome Program

A palindrome number is the same even if you flip its digits. Let’s show you how to create a Palindrome Program in Java. There are many ways to do this:

  1. You can use a for loop. This lets you review each digit of the number to see if it is the same when reversed.
  2. Library methods make this task easier, too. These ready-to-use tools come with Java and can quickly check if a number is a palindrome.
  3. Use a stack and queue to check if a string is a palindrome. First, put all the letters of the string into a stack and a queue. Then, compare each letter from the start and end until you reach the middle of the string.
  4. Use array methods to work with strings as well. This way, you can go through each letter of your word just like you would with digits.
  5. Armstrong numbers are also part of Java programming, but that’s another topic.

Example Solution

Code
public static boolean isPalindrome(String inputString){
         if(inputString.length() == 0 || inputString.length() == 1){
                      return true;
          }
          if(inputString.charAt(0) == inputString.charAt(inputString.length() - 1)){
                      return isPalindrome(inputString.substring(1, inputString.length() - 1));
          }
return false;
}
System.out.println(isPalindrome(madam));
System.out.println(isPalindrome(String.valueOf(3461345)));

Output
true
false

Factorial Program

Now, let’s talk about Factorial Programs, one of the Java examples. This is a common task in Java. It’s a method to multiply an integer by every nonnegative integer less than it.

Factorial uses the symbol ‘n!’. So ‘5!’ means 5 x 4 x 3 x 2 x 1. One of the easy ways to do this in Java is by using a loop. A for loop can multiply numbers from n down to one.

You can also use recursion in Java for factorial tasks. Recursion is when a method calls itself. It’s like this: If n is zero, then return one. Else, multiply n with the factorial of (n-1). Besides factorial, you can do more with Java.

Example Solution

Code
int numberCalculate= 1;
int factorial = 7;
for(int i = 1; i <= factorial; i++) {
       numberCalculate = numberCalculate * i;
}
System.out.println(numberCalculate);

Output
5040

Armstrong Number

Let’s explore what an Armstrong number in Java is. It is a positive digit that sums up to the same number when each of its digits is raised to the power equal to the count of digits. These numbers are also known as pluperfect or Plus Perfect numbers.

  • Count the number of digits in your given number.
  • Find its mth power for every digit in the number (where m is the total count of digits).
  • Add all these powers together.
  • Does this sum equal your given number? If so, it’s an Armstrong number!

Example Solution

Code
int number = 407;
String[] digits = String.valueOf(number).split("");
int sum = 0;
for(int i = 0; i < digits.length; i++) {
          int element = Integer.parseInt(digits[i]);
          sum += element * element * element;
}
if(number == sum)
         System.out.println(number + " is an Armstrong number!");
else()
         System.out.println(number + " is not an Armstrong number!");

Output
407 is an Armstrong number!

Java Array Programs

Arrays are a fundamental data structure in Java programming, allowing you to store a collection of elements of the same data type. They are versatile and widely used in various programming tasks. Here are some examples of Java array programs to illustrate their usage:

Copying Elements of an Array

Talking about Java programming, one of the everyday tasks we often handle is copying elements of an array. Here are some methods that we can use:

  • Use the Arrays class’ copyOfRange() method to copy a selected range of elements from the source array. This method is handy when we only want to copy specific array parts.
  • Loop through each element in the original array and copy them individually. It’s a simple yet effective way to replicate an array.
  • Be aware of potential problems with array copying. If not done right, it can lead to tricky bugs in your programs.
  • Use java.util.Arrays class’s copy () method for either padding or truncating arrays. This method allows us to control the length of our new array.
  • The best way to understand these methods is by using them in real examples.

Example Solution

Code
String[] oldArray = {"We", "will", "copy", "the", "elements", "in", "this", "array", "now"};
String[] newArray = String[oldArray.length];
int indexer = 0;
for (String var : oldArray) 
{ 
        newArray[indexer] = var;       //Gives the current element into the new Array on the correct position
        indexer++;
}

or

int[] oldArray= { 2, 3, 5, 7, 9 };
int[] newArray = Arrays.copyOfRange(oldArray, 1, 6);
for (String var : newArray) 
{ 
        System.out.print(var + " ");

}

Output
3 5 7 9 0 

Finding the Frequency of Each Element

Java array programs help find the count of each thing in an array. This task examines how often each part appears in a sorted list of good, whole numbers.

  • Choose an array to work on—it could be any type, from Armstrong to generic arrays.
  • Start counting; the aim is to see how many times each part appears in the list.
  • Use Java classes if needed; they can take an array and give back another with counts of each thing.
  • Don’t worry if this sounds tough! Many tools exist for extra learning.

Example Solution

Code
int array = {1, 4 6, 7, 8, 9, 7, 4};
int frequencies = new int[array.length];
int elementDone = -1;
for(int i = 0; i < array.length; i++) {
        int count = 1;
        for(int j = i + 1; j < array.length; j++) {
               if(array[i] == array[j] {
                     count++;
                     frequencies[j] = elementDone;   //Don't count the same element twice
                }
         }
         if(frequencies[i] != elementDone)
                  frequencies[i] = count;
}
System.out.println("Element:    |     Frequency:");
for(int k = 0; k < frequencies.length; k++) {
           if(frequencies[k] != visited) 
                   System.out.println("           " + array[k] + "     |     " + frequencies[k]);
}

Output
Element:    |     Frequency: 
           1     |     1
           4     |     2
           6     |     1
           7     |     2
           8     |     1
           9     |     1

Left Rotating Elements of an Array

To the left rotate an array, we shift each element towards the left several times. This is the same as rotating the array to the right by the length of the array minus N. Here’s how you can do it in Java:

  • Start with a variety of numbers.
  • Choose a specific position from which you want to rotate the elements (this will be your reference point).
  • Take the first element from this reference point and move it to its new position after rotation.
  • Repeat step 3 for all remaining elements, shifting them in one position to the left.
  • The last component of the original array will become the first element after rotation.

Example Solution

Code
int[] array = {2, 4, 5, 6, 7};
for(int i = 0; i < n; i++) {
      int first = array[0];  
      for(j = 0; j < array.length - 1; j++) {
             array[j] = array[j + 1];
      }
}
array[j] = first;
for(int var : array) {
      System.out.println(var + " ");
}

Output
7 6 5 4 2

Printing Duplicate Elements

Let’s learn about printing duplicate elements in Java arrays. There are different ways to achieve this. Take a look at some examples:

  1. Using two loops: You can use two loops to identify and print duplicate elements in an array. The first loop iterates over each element in the array, and the second loop checks if any other elements are equal to the current element. If a duplicate is found, it is printed.
  2. Removing duplicates using a set data structure: Another approach is to use a set data structure to remove duplicate elements from the array. By adding the elements to a set that does not allow duplicates, you can easily identify and print the unique elements.
  3. Finding duplicate values in an array of string values: If your array contains string values, you can use a hashmap or brute force approach to find duplicate elements. This involves iterating over each element and checking if it appears more than once in the array.

Example Solution

Code
int[] arr = {1, 2, 3, 4, 2, 5, 6, 7, 3}; 
System.out.println("Duplicate elements in the array are:"); 
for (int i = 0; i < arr.length - 1; i++) { 
         for (int j = i + 1; j < arr.length; j++) { 
                 if (arr[i] == arr[j]) { 
                      System.out.println(arr[j]); 
                 } 
          }
}

Output
Duplicate elements in the array are:
2
3

Sorting Elements in Ascending Order

Here is how to sort elements in ascending order using Java.

  • First, import the java.util.Arrays package at the beginning of your program.
  • Next, declare an array with the elements you want to sort.
  • Use the Arrays.sort() method and pass in your array as a parameter.
  • After calling the sort() method, your array will be sorted in ascending order.

Example Solution

Code

int[] unsortedNumbers = {10, 4, 2, 6, 45, 2, 7, 8)
int[] sortedNumbers = Arrays.sort(unsortedNumbers);
for(int var : sortedNumbers) {
        System.out.println(var + " ");
}

Output

2 2 4 6 7 8 10 45

Finding the Largest and Smallest Elements

One of the key examples is finding the most significant and smallest elements in a Java program. Developers and career seekers must know how to analyse arrays and identify these key values. Here are the steps you can follow:

  • Determine the size of the array.
  • Declare variables to store the most significant and most minor numbers, initialised with the first element of the array.
  • Use a loop to iterate through each element of the array.
  • Inside the loop, compare each element with the current values of the largest and smallest variables.
  • If an element is larger than the current most significant value, update the largest variable.
  • If an element is smaller than the current smallest value, update the smallest variable.
  • After looping through all elements, you will have identified the largest and smallest numbers in the array.

Example Solution

Code
int[] arr = {12, 34, 56, 78, 90, 45, 23, 67, 89, 1}; 
int min = arr[0]; 
int max = arr[0];
for (int i = 1; i < arr.length; i++) { 
     if (arr[i] < min) { 
         min = arr[i];  
     }     
     if (arr[i] > max) { 
         max = arr[i]; 
     } 
}  
System.out.println("Minimum value: " + min); 
System.out.println("Maximum value: " + max);

Output
Minimum value: 1
Maximum value: 90

Java OOPs Programs

Java is an object-oriented programming (OOP) language, which is designed to create programs using objects. Objects are self-contained entities that combine data and behaviour. OOP concepts such as encapsulation, inheritance, and polymorphism are fundamental to Java programming.

Creating and Comparing Objects

Creating and comparing objects in Java programming involves working with classes, instances, methods, attributes, and constructors. Here are some key points to remember:

  1. Objects are the basic unit of object-oriented programming in Java.
  2. To create an object, we need to declare a class and then use the ‘new’ keyword followed by the class name.
  3. Each object created from a class is called an instance. Multiple instances can be created from the same class.
  4. Objects have methods that define their behaviour. These methods can be called on specific instances of the class.
  5. Attributes are variables associated with objects that store data specific to each instance.
  6. Constructors are unique methods used to initialise objects when they are created.
  7. Inheritance allows us to create new classes based on existing ones, inheriting their attributes and behaviours.
  8. Polymorphism enables objects of different classes to be treated as objects of a common superclass.
  9. We can use the ‘equals()’ method or compare specific attributes using logical operators when comparing objects.
  10. Instances represent individual objects.

Inheritance and Polymorphism

Inheritance and polymorphism are important concepts in Java programming. They allow us to create specialised actions based on the type of objects we are working with. Here are some key points to understand:

  1. Inheritance enables us to create new classes based on existing ones. We can modify or extend these classes to add new functionalities.
  2. Polymorphism occurs when classes in Java inherit. It allows us to implement methods differently in inherited classes.
  3. Inheritance applies to classes, while polymorphism applies to methods.
  4. By using inheritance and polymorphism, we can achieve code reusability and maintainability.
  5. Abstraction, encapsulation, polymorphism, and inheritance are the four main principles of Java’s object-oriented programming.

Abstraction and Encapsulation

Abstraction and encapsulation are essential concepts in object-oriented programming. They help us organise code and make it easier to understand and maintain.

  1. Abstraction hides complexity and shows only the relevant information to users.
  2. Encapsulation is used to contain information and restrict access to code.
  3. These two principles are fundamental in object-oriented programming.
  4. Abstraction hides unwanted details, while encapsulation binds code and data together.
  5. In Java, we implement abstraction using abstract classes and methods.
  6. In Java, we implement encapsulation using private, public, and protected access modifiers.

Using Arrays and Collections

Arrays and collections are among the key concepts in Java programming. They allow us to store data in a structured way and perform various operations on that data. Here are some ways we can use arrays and collections in Java:

  • Declaring arrays: We can declare an array by specifying the type of elements it will hold and its name. For example, we can declare an array to hold integers like this: “int[] numbers;”
  • Initialising arrays: After declaring an array, we must initialise it with values. We can do this by assigning values to individual elements or using a loop. For example, we can initialise an array with three elements like this: “numbers = new int[]{1, 2, 3};”
  • Accessing arrays: Once an array is declared and initialised, we can access its elements using their index positions. The index starts from 0 for the first element. For example, we can access the second element of our array like this: “int second element = numbers[1];”
  • Storing collections: The Java Collections Framework provides interfaces like List, Queue, and Set for storing collections of objects. These interfaces allow us to add, remove, and retrieve elements from the collection.
  • Manipulating collections: We can manipulate collections by adding or removing elements based on certain conditions or performing operations.
  • Accessing collections: Once a collection is created and populated with objects, we can iterate over it using loops or stream APIs to access each object’s properties or perform specific actions.

Multithreading

Multithreading allows for the concurrent execution of multiple parts of a program. Different threads can run at the same time, performing tasks simultaneously.

Handling Exceptions and Errors

Handling exceptions and errors is one of the essential Java programming examples. Here are some key points to remember:

  • Exceptions are error events that can disrupt the normal flow of a program.
  • Java offers a robust and object-oriented approach to handling exceptions.
  • When an exception occurs in a method, it creates an exception object.
  • Exception handling allows you to catch and handle exceptions, preventing abnormal termination of the program.
  • It helps deal with exceptions that cannot be handled locally.
  • Exception handling provides a way to handle errors without displaying an error status in the program.

Java Number Programs

Java Number Programs include various coding samples, such as reversing a number, converting it to a word, and checking for automorphic, sunny, and tech numbers.

Reversing a Number

There are different methods you can use to reverse a number in Java.

1. Using a “while loop”

  • Take the input number.
  • Initialise a variable to store the reversed number.
  • Use the modulus operator (%) to get the remainder of the input number divided by 10.
  • Multiply the reversed number by 10 and add the remainder obtained in the previous step.
  • Update the input number by dividing it by 10, discarding the last digit.
  • Repeat these steps until the input number becomes 0.
Example Solution
Code
int input = 1234;
int reversed = 0;
while(input != 0) {
      int digit = input % 10;
      reversed = reversed * 10 + digit;
      input /= 10;
}
System.out.println(reversed);

Output
4321

2. Using a “for loop”

  • Take the input number.
  • Convert it into a string and store it in a variable.
  • Use a for loop to iterate through each string character from right to left.
  • Append each character to a new string variable to get the reversed number.
Example Solution
Code
int input = 6789;
String inputString = String.valueOf(input);
String reversed = "";
for(int i = (inputString.length - 1); i < 0; i--) {
       reversed += inputString.charAt(i);
}
System.out.println(reversed);

Output
9876

3. Using Recursion

  • Create a recursive function that takes an argument as the input number.
  • Inside the function, check if the input number is less than 10; if it is true, return it as it is (base case).
  • If not, perform a modulo operation on the input number with 10 and multiply it by 10, raised to the power of the length of the input number minus one (using the Math.pow() method).
  • Call the same function again with modified arguments: divide the input number by 10 and subtract one from the length of the input number (recursive call).
  • Add both results obtained from the base case and recursive call.
Example Solution
Code
public static void Reverse(int input) {
        if(input < 10) {
              System.out.println(input);
              return;
        }
        else {
              System.out.println(input % 10);
              Reverse(input / 10);
        }
}

Function calling:
Reverse(3579);

Output

9753

Converting Number to Word

  1. Start by importing the necessary packages in your Java program.
  2. Define an array of string variables that represent the number of words from zero to nineteen.
  3. Create another array of string variables representing the tens place words from twenty to ninety.
  4. Prompt the user to enter a number they want to convert into words.
  5. Read the inputted number from the user and store it in a variable.
  6. Use if-else statements or switch case statements to handle different cases:
  7. If the number is less than 20, retrieve the corresponding word from the first array.
  8. If the number is between 20 and 99, retrieve the corresponding word for tens place and concatenate it with the word for ones place (if not zero).
  9. Print out the converted word representation of the inputted number.

Example Solution

Code

String[] oneToNineteen = {"one", "two", "three", "four", "five, "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
String[] tens = {"twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"};

System.out.println("Please type a number between 1 and 99!");
int input = Integer.valueOf("45");

if(input < 20)
       System.out.println(oneToNineteen[input - 1]);
else if(input <= 99) {
       int tensDigit = Integer.valueOf(String.valueOf(input).charAt(0));
       int unitDigit = Integer.valueOf(String.valueOf(input).charAt(1));
       System.out.println(tens[tensDigit - 2] + " " + oneToNineteen[unitDigit - 1];
}

Output

fourty five

Checking for Automorphic, Sunny, and Tech Numbers

Automorphic numbers are numbers whose square ends with the same digits as the number itself. In Java programming, you can check if a number is automorphic by squaring it and comparing the last digits with the original number. If they match, then the number is automorphic.

Example Solutions

Automorphic numbers:
Code
int num = 5;
int square = num * num; 
String numStr = Integer.toString(num); 
String squareStr = Integer.toString(square); 
if (squareStr.endsWith(numStr)) { 
     System.out.println(num + " is an automorphic number."); 
} 
else { 
     System.out.println(num + " is not an automorphic number."); 
}

Output
5 is an automorphic number.
Sunny numbers:
Code
int n = 25;
boolean isSunny = false; 
for (int m = 1; m * m <= n; m++) { 
     if (n == m * m + 1) { 
         isSunny = true; break; 
     } 
} 
if (isSunny) { 
     System.out.println(n + " is a sunny number."); 
} 
else { 
     System.out.println(n + " is not a sunny number."); 
}

Output
25 is not a sunny number.
Tech numbers
Code

int number = 2025; 
int originalNumber = number; 
int digitSum = 0; 
while (number > 0) { 
    int digit = number % 10; 
    digitSum += digit; 
    number /= 10; 
} 
if (originalNumber % digitSum == 0) { 
    System.out.println(originalNumber + " is a tech number."); 
} 
else {
    System.out.println(originalNumber + " is not a tech number."); 
}

Output
2025 is a tech number.

Generating Random Numbers

  1. The Java programming language provides built-in methods and classes for generating random numbers.
  2. The `java.util.Random` class creates random numbers in Java.
  3. The `nextInt()` method of the `Random` class generates random integers.
  4. You can use the `nextLong()` method to generate random long values.
  5. You can use the `nextDouble()` method to generate random decimal values, such as doubles.
  6. By default, the `Random` class generates pseudo-random numbers based on an initial seed value.
  7. If you want to generate true random numbers, you can use external libraries or online services that provide access to true randomness.

Random random = new Random();
Systme.out.print(random.nextInt(100)); //upper limit

Printing Patterns Using Numbers

Printing patterns using numbers is a fun and challenging task in Java programming. You can create various designs and shapes by arranging numbers in a specific way. Here are some examples of number patterns that you can print using Java:

Pyramid Patterns

  • Print a pyramid pattern of numbers.
  • Create a half-pyramid pattern using numbers.

Number Series Patterns

  • Generate the Fibonacci series using numbers.
  • Print the prime numbers within a given range.
  • Check for palindrome numbers.

Character Logic Patterns

  • Create patterns like alphabets, stars, or any other characters using numbers.

Loop Patterns

  • Use loops to print different patterns like square or rectangle shapes.

Conditional Patterns

  • Implement logic to print certain patterns based on specific conditions.

Java programming examples are great for practising and learning Java program basics. You can strengthen your coding skills by exploring popular Java examples like the Fibonacci series, prime numbers, and palindromes. Diving into array programs and OOP concepts will help you become more proficient in Java. So, start exploring these examples today and enhance your programming knowledge!

Leave a comment

Your email address will not be published. Required fields are marked *

Join Our Mailing List

Grow your business by getting expert web, marketing and sales tips straight to
your inbox. Subscribe to our newsletter.