javapublic 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
PrimeNumberCheckerclass contains a static methodisPrimeto check whether a given number is prime or not. - The
isPrimemethod takes an integernumberas input and returnstrueif the number is prime, andfalseotherwise. - 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
javaimport 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
Personclass that represents the structure of the JSON object. - The
JsonToXmlConverterclass demonstrates the conversion process. - First, we use Gson to parse the JSON string into a
JsonObject. - Next, we use Gson again to deserialize the
JsonObjectinto aPersonobject. - We create a
JAXBContextfor thePersonclass to prepare for the XML conversion. - Then, we create a
Marshallerand set theJAXB_FORMATTED_OUTPUTproperty to get a nicely formatted XML. - Finally, we use the
marshallerto marshal thePersonobject into an XML string and print the result.
3. Prime Number From 1 to 100 — How to display prime numbers using Java
javapublic 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
PrimeNumbersInRangeclass contains a static methodisPrimeto check whether a given number is prime or not, similar to the previous example. - In the
mainmethod, we define a range fromstarttoend, which in this case is 1 to 100. - We then iterate through each number in the range and use the
isPrimemethod 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)
javapublic 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
charto aString. TheCharToStringConverterclass demonstrates three methods to achieve this. - Method 1: Using
Character.toString(char)- This method converts the givencharto aStringusing the statictoStringmethod of theCharacterclass. - Method 2: Using
String.valueOf(char)- This method is a convenient way to convert acharto aStringusing the staticvalueOfmethod of theStringclass. - Method 3: Concatenating with an empty string - By concatenating the
charwith an empty string, Java automatically converts thecharto aString. - Each method produces the same output, converting the
charvariablechcontaining the character 'A' into aStringand printing it to the console.
5. Fibonacci Series in Java — Fibonacci Series Program in Java using Loops & Recursion
javapublic 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
FibonacciSeriesclass contains two methods to generate the Fibonacci series up to a given numbern. - 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 forn = 0andn = 1, and for any other value ofn, 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
javapublic 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
ArmstrongNumberCheckerclass contains a static methodisArmstrongto 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
isArmstrongmethod, we first calculate the number of digitsnin the given number usingString.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 theresultvariable. - After the loop, we compare the
resultwith theoriginalNumber, and if they are equal, the method returnstrue, indicating that the number is an Armstrong number.
7. Reverse a String in Java — How to Reverse a String in Java using Recursion
javapublic 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
StringReverserclass contains a static methodreverseStringto reverse a given string using recursion. - In the
reverseStringmethod, we use a simple recursive approach to reverse the string. - If the input string
stris empty, we directly return it as the reversed string (base case). - Otherwise, we call the
reverseStringmethod with the substringstr.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
javapublic 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
PalindromeCheckerclass contains a static methodisPalindrometo check whether a given number is a palindrome or not. - A palindrome is a number that reads the same forward and backward.
- In the
isPalindromemethod, we reverse the number and store it in thereversedNumbervariable. - We compare the
originalNumberwith thereversedNumber, and if they are equal, the method returnstrue, indicating that the number is a palindrome.
9. Pattern Programs in Java — How to Print Star, Pyramid, Number
javapublic 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
PatternPrinterclass 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
mainmethod, 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
javapublic 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
BubbleSortclass contains a static methodbubbleSortto 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
mainmethod, we initialize an integer arrayarrand callbubbleSortto sort the array in ascending order. - Before and after sorting, we print the elements of the array using the
printArraymethod.
11. Insertion Sort — Insertion Sort Algorithm in Java Program with Example
javapublic 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
InsertionSortclass contains a static methodinsertionSortto 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 indexiis 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 thekey(current element being inserted) one position ahead to make space for thekey. - The sorting process continues until all elements are inserted into their correct positions.
- In the
mainmethod, we initialize an integer arrayarrand callinsertionSortto sort the array in ascending order. - Before and after sorting, we print the elements of the array using the
printArraymethod.
12. Selection Sorting — Java Program for Selection Sorting with Example
javapublic 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
SelectionSortclass contains a static methodselectionSortto 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, theminIndexvariable 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
minIndexelement is swapped with the element at indexi, 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
mainmethod, we initialize an integer arrayarrand callselectionSortto sort the array in ascending order. - Before and after sorting, we print the elements of the array using the
printArraymethod.
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.
0 Comments