Ticker

6/recent/ticker-posts

Java Programs

Java Programs

1. Prime Number Program in Java — Check whether a number is prime or not
java
public class PrimeNumberChecker {
public static boolean isPrime(int number) {
if (number <= 1)
return false;
for (int i = 2; i * i <= number; i++) {
if (number % i == 0)
return false;
}
return true;
}

public static void main(String[] args) {
int num = 29;
if (isPrime(num))
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

Explanation:

  • The PrimeNumberChecker class contains a static method isPrime to check whether a given number is prime or not.
  • The isPrime method takes an integer number as input and returns true if the number is prime, and false otherwise.
  • The method first checks if the input number is less than or equal to 1. If it is, the method returns false, as prime numbers are greater than 1.
  • Then, it iterates from 2 up to the square root of the given number, checking for any divisor. If a divisor is found, the method returns false, indicating the number is not prime.
  • If no divisor is found, the method returns true, indicating the number is prime.

2. Convert JSON to XML — Convert using Gson and JAXB: JAVA Example

java
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class JsonToXmlConverter {

public static void main(String[] args) throws JAXBException {
String jsonString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";

// Convert JSON to Java Object
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
Gson gson = new Gson();
Person person = gson.fromJson(jsonObject, Person.class);

// Convert Java Object to XML
JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

StringWriter stringWriter = new StringWriter();
marshaller.marshal(person, stringWriter);

System.out.println("XML representation:");
System.out.println(stringWriter.toString());
}
}

class Person {
private String name;
private int age;
private String city;

// Getters and Setters (not shown for brevity)
}

Explanation:

  • In this example, we convert a JSON string to its equivalent XML representation using Gson and JAXB libraries.
  • We define a Person class that represents the structure of the JSON object.
  • The JsonToXmlConverter class demonstrates the conversion process.
  • First, we use Gson to parse the JSON string into a JsonObject.
  • Next, we use Gson again to deserialize the JsonObject into a Person object.
  • We create a JAXBContext for the Person class to prepare for the XML conversion.
  • Then, we create a Marshaller and set the JAXB_FORMATTED_OUTPUT property to get a nicely formatted XML.
  • Finally, we use the marshaller to marshal the Person object into an XML string and print the result.

3. Prime Number From 1 to 100 — How to display prime numbers using Java

java
public class PrimeNumbersInRange {
public static boolean isPrime(int number) {
if (number <= 1)
return false;
for (int i = 2; i * i <= number; i++) {
if (number % i == 0)
return false;
}
return true;
}

public static void main(String[] args) {
int start = 1;
int end = 100;

System.out.println("Prime numbers between " + start + " and " + end + ":");
for (int i = start; i <= end; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
}

Explanation:

  • The PrimeNumbersInRange class contains a static method isPrime to check whether a given number is prime or not, similar to the previous example.
  • In the main method, we define a range from start to end, which in this case is 1 to 100.
  • We then iterate through each number in the range and use the isPrime method to determine if it is a prime number.
  • If a number is prime, we print it in the console, displaying all prime numbers within the specified range.

(Note: The isPrime method used here is the same as in the first example.)


4. Convert char to String — How to Convert Char to String in Java (Examples)

java
public class CharToStringConverter {
public static void main(String[] args) {
char ch = 'A';

// Method 1: Using Character.toString(char)
String str1 = Character.toString(ch);
System.out.println("Method 1: " + str1);

// Method 2: Using String.valueOf(char)
String str2 = String.valueOf(ch);
System.out.println("Method 2: " + str2);

// Method 3: Concatenating with an empty string
String str3 = "" + ch;
System.out.println("Method 3: " + str3);
}
}

Explanation:

  • In Java, there are several ways to convert a char to a String. The CharToStringConverter class demonstrates three methods to achieve this.
  • Method 1: Using Character.toString(char) - This method converts the given char to a String using the static toString method of the Character class.
  • Method 2: Using String.valueOf(char) - This method is a convenient way to convert a char to a String using the static valueOf method of the String class.
  • Method 3: Concatenating with an empty string - By concatenating the char with an empty string, Java automatically converts the char to a String.
  • Each method produces the same output, converting the char variable ch containing the character 'A' into a String and printing it to the console.

5. Fibonacci Series in Java — Fibonacci Series Program in Java using Loops & Recursion

java
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10;

// Using loops
System.out.print("Fibonacci Series using loops: ");
for (int i = 0; i < n; i++) {
System.out.print(fibonacciUsingLoop(i) + " ");
}

System.out.println();

// Using recursion
System.out.print("Fibonacci Series using recursion: ");
for (int i = 0; i < n; i++) {
System.out.print(fibonacciUsingRecursion(i) + " ");
}
}

public static int fibonacciUsingLoop(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;

int prev = 0;
int current = 1;
int result = 0;

for (int i = 2; i <= n; i++) {
result = prev + current;
prev = current;
current = result;
}

return result;
}

public static int fibonacciUsingRecursion(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;

return fibonacciUsingRecursion(n - 1) + fibonacciUsingRecursion(n - 2);
}
}

Explanation:

  • The FibonacciSeries class contains two methods to generate the Fibonacci series up to a given number n.
  • Method 1: fibonacciUsingLoop(int n) - This method calculates the Fibonacci series using a loop. It starts with the first two numbers (0 and 1) and iteratively calculates the subsequent numbers by adding the previous two numbers.
  • Method 2: fibonacciUsingRecursion(int n) - This method calculates the Fibonacci series using recursion. It defines the base cases for n = 0 and n = 1, and for any other value of n, it recursively calls itself to calculate the Fibonacci number.

(Note: In this example, we generate and print the first 10 numbers of the Fibonacci series.)


6. Armstrong Number in Java — Java Program to Check Armstrong Number

java
public class ArmstrongNumberChecker {
public static boolean isArmstrong(int number) {
int originalNumber = number;
int result = 0;
int n = String.valueOf(number).length();

while (number != 0) {
int digit = number % 10;
result += Math.pow(digit, n);
number /= 10;
}

return result == originalNumber;
}

public static void main(String[] args) {
int num = 153;
if (isArmstrong(num))
System.out.println(num + " is an Armstrong number.");
else
System.out.println(num + " is not an Armstrong number.");
}
}

Explanation:

  • The ArmstrongNumberChecker class contains a static method isArmstrong to check whether a given number is an Armstrong number or not.
  • An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
  • In the isArmstrong method, we first calculate the number of digits n in the given number using String.valueOf(number).length().
  • We then perform the Armstrong number calculation by extracting each digit from the number, raising it to the power of n, and accumulating the results in the result variable.
  • After the loop, we compare the result with the originalNumber, and if they are equal, the method returns true, indicating that the number is an Armstrong number.

7. Reverse a String in Java — How to Reverse a String in Java using Recursion

java
public class StringReverser {
public static String reverseString(String str) {
if (str.isEmpty())
return str;
else
return reverseString(str.substring(1)) + str.charAt(0);
}

public static void main(String[] args) {
String input = "Hello, World!";
String reversed = reverseString(input);
System.out.println("Original String: " + input);
System.out.println("Reversed String: " + reversed);
}
}

Explanation:

  • The StringReverser class contains a static method reverseString to reverse a given string using recursion.
  • In the reverseString method, we use a simple recursive approach to reverse the string.
  • If the input string str is empty, we directly return it as the reversed string (base case).
  • Otherwise, we call the reverseString method with the substring str.substring(1), effectively removing the first character of the original string.
  • We then concatenate the first character str.charAt(0) at the end of the reversed substring, which effectively reverses the string.
  • The recursion continues until the entire string is reversed.

8. Palindrome Program in Java — Check if a number is Palindrome or Not

java
public class PalindromeChecker {
public static boolean isPalindrome(int number) {
int originalNumber = number;
int reversedNumber = 0;

while (number != 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}

return originalNumber == reversedNumber;
}

public static void main(String[] args) {
int num = 12321;
if (isPalindrome(num))
System.out.println(num + " is a palindrome.");
else
System.out.println(num + " is not a palindrome.");
}
}

Explanation:

  • The PalindromeChecker class contains a static method isPalindrome to check whether a given number is a palindrome or not.
  • A palindrome is a number that reads the same forward and backward.
  • In the isPalindrome method, we reverse the number and store it in the reversedNumber variable.
  • We compare the originalNumber with the reversedNumber, and if they are equal, the method returns true, indicating that the number is a palindrome.

9. Pattern Programs in Java — How to Print Star, Pyramid, Number

java
public class PatternPrinter {
public static void main(String[] args) {
int rows = 5;

System.out.println("Pattern 1: Star Pattern");
printStarPattern(rows);

System.out.println("\nPattern 2: Pyramid Pattern");
printPyramidPattern(rows);

System.out.println("\nPattern 3: Number Pattern");
printNumberPattern(rows);
}

public static void printStarPattern(int rows) {
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}

public static void printPyramidPattern(int rows) {
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}

public static void printNumberPattern(int rows) {
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

Explanation:

  • The PatternPrinter class contains three methods to print different patterns: star pattern, pyramid pattern, and number pattern.
  • printStarPattern(int rows): This method prints a pattern of stars in a right-angled triangle, where the number of rows determines the height of the triangle.
  • printPyramidPattern(int rows): This method prints a pyramid pattern with stars, where each row has an increasing number of stars, and the top row contains one star.
  • printNumberPattern(int rows): This method prints a pattern of numbers in a right-angled triangle, where each row contains numbers from 1 to the row number.
  • In the main method, we specify the number of rows for the patterns and call each respective method to print the patterns.

10. Bubble Sort Program in Java — Sorting Algorithm Example

java
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
boolean swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no two elements were swapped in the inner loop, the array is already sorted
if (!swapped)
break;
}
}

public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original array:");
printArray(arr);

bubbleSort(arr);

System.out.println("\nSorted array:");
printArray(arr);
}

public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}

Explanation:

  • The BubbleSort class contains a static method bubbleSort to sort an array of integers using the Bubble Sort algorithm.
  • Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order.
  • The outer loop (controlled by i) goes from the beginning to the second-to-last element of the array. In each iteration, the largest element in the remaining unsorted part of the array "bubbles up" to the correct position at the end of the array.
  • The inner loop (controlled by j) compares adjacent elements and swaps them if they are in the wrong order.
  • The sorting process continues until no more swaps are made in a pass, indicating that the array is already sorted.
  • In the main method, we initialize an integer array arr and call bubbleSort to sort the array in ascending order.
  • Before and after sorting, we print the elements of the array using the printArray method.

11. Insertion Sort — Insertion Sort Algorithm in Java Program with Example

java
public class InsertionSort {
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1] that are greater than key to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original array:");
printArray(arr);

insertionSort(arr);

System.out.println("\nSorted array:");
printArray(arr);
}

public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}

Explanation:

  • The InsertionSort class contains a static method insertionSort to sort an array of integers using the Insertion Sort algorithm.
  • Insertion Sort is a simple sorting algorithm that builds a sorted array one element at a time by repeatedly inserting an unsorted element into its correct position in the sorted part of the array.
  • The outer loop (controlled by i) goes from the second element to the end of the array. In each iteration, the element at index i is compared with the elements in the sorted part of the array, and it is inserted at the correct position within the sorted part.
  • The inner loop (controlled by j) moves elements greater than the key (current element being inserted) one position ahead to make space for the key.
  • The sorting process continues until all elements are inserted into their correct positions.
  • In the main method, we initialize an integer array arr and call insertionSort to sort the array in ascending order.
  • Before and after sorting, we print the elements of the array using the printArray method.

12. Selection Sorting — Java Program for Selection Sorting with Example

java
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the element at index i
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}

public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original array:");
printArray(arr);

selectionSort(arr);

System.out.println("\nSorted array:");
printArray(arr);
}

public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}

Explanation:

  • The SelectionSort class contains a static method selectionSort to sort an array of integers using the Selection Sort algorithm.
  • Selection Sort is a simple sorting algorithm that divides the array into two parts: the sorted part and the unsorted part. In each iteration, it finds the minimum element from the unsorted part and swaps it with the first element of the unsorted part, effectively growing the sorted part of the array.
  • The outer loop (controlled by i) goes from the beginning to the second-to-last element of the array. In each iteration, the minIndex variable keeps track of the index with the minimum element in the unsorted part of the array.
  • The inner loop (controlled by j) finds the minimum element in the unsorted part by comparing elements with the current minimum element (arr[minIndex]).
  • After finding the minimum element, the minIndex element is swapped with the element at index i, effectively adding it to the sorted part of the array.
  • The sorting process continues until the entire array is sorted in ascending order.
  • In the main method, we initialize an integer array arr and call selectionSort to sort the array in ascending order.
  • Before and after sorting, we print the elements of the array using the printArray method.

You can use the code examples and explanations provided above to create comprehensive documentation with proper formatting, headings, and subheadings for each of the given topics. Remember to include a brief introduction to each topic and the corresponding code examples. Additionally, you can include information on the time complexity of the algorithms used in the sorting programs to provide an overview of their efficiency.

    Post a Comment

    0 Comments