Java Coding Questions
How do you reverse a string in Java?
Here are a few common approaches:
Using a StringBuilder or StringBuffer:
You can use the
StringBuilderorStringBufferclass to efficiently reverse a string because these classes are mutable. Here's how you can do it:String originalString = "Hello, World!"; StringBuilder reversedString = new StringBuilder(originalString); reversedString.reverse(); String result = reversedString.toString(); System.out.println(result); // Outputs: "!dlroW ,olleH"Note that using
StringBuilderis preferred overStringBufferin most cases because it's not synchronized, making it more efficient for single-threaded applications.Using a loop to reverse the string:
You can reverse a string by iterating through it character by character and building a new string in reverse order. Here's an example using a loop:
String originalString = "Hello, World!"; String reversedString = ""; for (int i = originalString.length() - 1; i >= 0; i--) { reversedString += originalString.charAt(i); } System.out.println(reversedString); // Outputs: "!dlroW ,olleH"However, this method can be less efficient for large strings because strings in Java are immutable, and each concatenation creates a new string, potentially resulting in a lot of unnecessary object creations.
Using a
chararray:You can convert the string to a
chararray, reverse the array, and then create a new string from the reversed array. Here's an example:String originalString = "Hello, World!"; char[] charArray = originalString.toCharArray(); int length = charArray.length; for (int i = 0; i < length / 2; i++) { char temp = charArray[i]; charArray[i] = charArray[length - 1 - i]; charArray[length - 1 - i] = temp; } String reversedString = new String(charArray); System.out.println(reversedString); // Outputs: "!dlroW ,olleH"This method can be more memory-efficient than the second approach because it doesn't involve creating new strings in each iteration.
How do you remove duplicates from an array in Java?
In Java, you can remove duplicates from an array using several different methods. One common approach is to use a Set or List to store the unique elements of the array. Here's an example using a Set:
import java.util.HashSet;
import java.util.Arrays;
public class RemoveDuplicatesFromArray {
public static void main(String[] args) {
String[] arrayWithDuplicates = {"apple", "banana", "apple", "orange", "banana", "grape"};
// Create a HashSet to store unique elements
HashSet<String> uniqueElements = new HashSet<>();
for (String element : arrayWithDuplicates) {
uniqueElements.add(element);
}
// Convert the HashSet back to an array
String[] arrayWithoutDuplicates = uniqueElements.toArray(new String[0]);
System.out.println(Arrays.toString(arrayWithoutDuplicates));
}
}
In this code:
We define an array called
arrayWithDuplicatescontaining duplicate elements.We create a
HashSetcalleduniqueElementsto store the unique elements. AHashSetautomatically ensures uniqueness.We iterate through the
arrayWithDuplicates, and for each element, we add it to theuniqueElementsset.We convert the
uniqueElementsset back to an array using thetoArraymethod. The resulting array,arrayWithoutDuplicates, contains the unique elements.Finally, we print the
arrayWithoutDuplicatesto verify that duplicates have been removed.
Using a Set is an efficient way to remove duplicates because it automatically enforces uniqueness. If you need to maintain the order of elements, you can use a LinkedHashSet instead of a HashSet. If you prefer working with a List, you can use an ArrayList and iterate through the original array to add elements to the ArrayList if they haven't been added already.
Here's an example using a List:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RemoveDuplicatesFromArray {
public static void main(String[] args) {
String[] arrayWithDuplicates = {"apple", "banana", "apple", "orange", "banana", "grape"};
// Create an ArrayList to store unique elements
List<String> uniqueElements = new ArrayList<>();
for (String element : arrayWithDuplicates) {
if (!uniqueElements.contains(element)) {
uniqueElements.add(element);
}
}
// Convert the ArrayList back to an array
String[] arrayWithoutDuplicates = uniqueElements.toArray(new String[0]);
System.out.println(Arrays.toString(arrayWithoutDuplicates));
}
}How do you find the second highest number in an array in Java?
To find the second highest number in an array in Java, you can iterate through the array while keeping track of the largest and second-largest values. Here's a simple example:
public class SecondLargestNumber {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 9, 1, 11, 7};
int firstLargest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int number : numbers) {
if (number > firstLargest) {
secondLargest = firstLargest;
firstLargest = number;
} else if (number > secondLargest && number < firstLargest) {
secondLargest = number;
}
}
if (secondLargest == Integer.MIN_VALUE) {
System.out.println("There is no second largest number.");
} else {
System.out.println("The second largest number is: " + secondLargest);
}
}
}You can also find the second highest number in an array in Java using streams by first converting the array to a stream, sorting it in descending order, skipping the first element (which is the largest), and then retrieving the second element in the stream. Here's how you can do it:
import java.util.Arrays;
public class SecondLargestNumberUsingStream {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 9, 1, 11, 7};
int secondLargest = Arrays.stream(numbers)
.boxed() // Convert to Integer objects
.sorted((a, b) -> b - a) // Sort in descending order
.skip(1) // Skip the largest element
.findFirst()
.orElseThrow(() -> new IllegalStateException("There is no second largest number."));
System.out.println("The second largest number is: " + secondLargest);
}
}
In this code:
We use
Arrays.stream(numbers)to convert the arraynumbersto a stream of integers.We use
.boxed()to convert theIntStreamto aStream<Integerso that we can use thesortedmethod to sort the elements in descending order.We use
.sorted((a, b) -> b - a)to sort the stream in descending order.We use
.skip(1)to skip the first element in the sorted stream (which is the largest element).We use
.findFirst()to retrieve the first (and only) element in the remaining stream, which is the second largest number.If there is no second largest number (e.g., when the array is empty or contains only one unique number), we throw an
IllegalStateException.
How do you implement a linked list in Java?
In Java, you can implement a singly linked list, a basic data structure, using custom classes to represent the nodes and the linked list itself. Here's a simple example of how to implement a singly linked list:
- Create a
Nodeclass to represent individual elements in the linked list.
public class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
- Create a
LinkedListclass to manage the linked list and provide methods for insertion, deletion, and traversal.
public class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
// Method to insert a new node at the end of the linked list.
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// Method to delete a node with a specific value.
public void delete(int data) {
if (head == null) {
return;
}
if (head.data == data) {
head = head.next;
return;
}
Node current = head;
while (current.next != null) {
if (current.next.data == data) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
// Method to display the linked list.
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
public static void main(String[] args) {
LinkedList myList = new LinkedList();
myList.append(1);
myList.append(2);
myList.append(3);
System.out.print("Linked List: ");
myList.display();
myList.delete(2);
System.out.print("Linked List after deleting 2: ");
myList.display();
}
}
In this example:
- The
Nodeclass represents individual elements in the linked list. Each node contains data and a reference to the next node in the list. - The
LinkedListclass manages the linked list. It provides methods for appending (adding to the end) and deleting nodes, as well as displaying the contents of the list. - In the
mainmethod, we create aLinkedListinstance, append some elements, display the linked list, and then delete a specific element.
This is a simple implementation of a singly linked list in Java. You can expand upon this foundation to add more functionality, such as inserting at specific positions or searching for elements.
How do you find the middle element of a singly linked list in one pass?
To find the middle element of a singly linked list in one pass, you can use the two-pointer or "tortoise and hare" approach. This approach uses two pointers, one moving at twice the speed of the other. When the faster pointer reaches the end of the list, the slower pointer will be at the middle of the list. Here's a Java implementation:
public class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public class FindMiddleOfSinglyLinkedList {
public ListNode findMiddle(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next; // Move the slow pointer by one step
fast = fast.next.next; // Move the fast pointer by two steps
}
return slow;
}
public static void main(String[] args) {
FindMiddleOfSinglyLinkedList finder = new FindMiddleOfSinglyLinkedList();
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
ListNode middle = finder.findMiddle(head);
if (middle != null) {
System.out.println("The middle element is: " + middle.val);
} else {
System.out.println("The list is empty.");
}
}
}
In this code:
The
ListNodeclass represents individual elements in the linked list.The
FindMiddleOfSinglyLinkedListclass contains the methodfindMiddle, which finds the middle element of the singly linked list.Two pointers,
slowandfast, are initialized at the head of the list.The
whileloop continues until thefastpointer reaches the end of the list or goes past it. In each iteration, theslowpointer moves one step, and thefastpointer moves two steps.When the
fastpointer reaches the end, theslowpointer will be at the middle element of the linked list.Finally, the code prints the value of the middle element, or a message indicating that the list is empty.
This approach allows you to find the middle element of a singly linked list in one pass, making it efficient for large lists.
How do you implement a binary search in Java?
Binary search is an efficient algorithm for searching for a specific element in a sorted array. Here's how you can implement binary search in Java:
public class BinarySearch {
// Function to perform binary search
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Element found
} else if (arr[mid] < target) {
left = mid + 1; // Search the right half
} else {
right = mid - 1; // Search the left half
}
}
return -1; // Element not found
}
public static void main(String[] args) {
int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int target = 7;
int result = binarySearch(sortedArray, target);
if (result != -1) {
System.out.println("Element found at index " + result);
} else {
System.out.println("Element not found in the array.");
}
}
}
In this code:
The
binarySearchfunction performs the binary search. It takes a sorted arrayarrand a target elementtargetas parameters.We initialize two pointers,
leftandright, which represent the indices of the current search range. Initially, the entire array is the search range.Inside the
whileloop, we calculate themidindex, which is the middle of the current search range.We compare the element at the
midindex with the target element. If they are equal, we return the index at which the element was found.If the element at the
midindex is less than the target, we updatelefttomid + 1to search the right half of the current range.If the element at the
midindex is greater than the target, we updaterighttomid - 1to search the left half of the current range.The
whileloop continues until the search range is empty (left>right) or until the element is found.If the element is not found, we return -1 to indicate that it doesn't exist in the array.
In the
mainmethod, we create a sorted array and specify the target element for the binary search.We call the
binarySearchfunction to search for the target element and print the result.
How do you check if a given string is a palindrome in Java?
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. To check if a given string is a palindrome in Java, you can follow these steps:
- Remove any non-alphanumeric characters and convert the string to lowercase for a case-insensitive check.
- Use two pointers, one starting from the beginning of the string and the other from the end, and compare the characters at these positions.
Here's a Java code example to check if a given string is a palindrome:
public class PalindromeCheck {
public static boolean isPalindrome(String str) {
if (str == null || str.isEmpty()) {
return true; // An empty string or null is considered a palindrome.
}
str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); // Remove non-alphanumeric characters and convert to lowercase.
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false; // If characters don't match, it's not a palindrome.
}
left++;
right--;
}
return true; // If the loop completes without returning false, it's a palindrome.
}
public static void main(String[] args) {
String input1 = "A man, a plan, a canal, Panama";
String input2 = "racecar";
String input3 = "hello";
System.out.println("Is '" + input1 + "' a palindrome? " + isPalindrome(input1));
System.out.println("Is '" + input2 + "' a palindrome? " + isPalindrome(input2));
System.out.println("Is '" + input3 + "' a palindrome? " + isPalindrome(input3));
}
}
In this code:
The
isPalindromemethod first handles the edge cases of an empty string ornull, both of which are considered palindromes.It removes non-alphanumeric characters from the input string and converts the string to lowercase using
replaceAll.Two pointers,
leftandright, are used to compare characters at the beginning and end of the string. The loop continues until they meet in the middle.If at any point the characters at the
leftandrightpositions do not match, the method returnsfalse. If the loop completes without returningfalse, the string is considered a palindrome, and the method returnstrue.In the
mainmethod, you can see how theisPalindromefunction is used to check three example strings.
How do you implement a breadth-first search (BFS) algorithm in Java?
Breadth-First Search (BFS) is an algorithm used to traverse or search through a graph or tree data structure. It explores all the nodes at the current level before moving to the next level. Here's how you can implement a BFS algorithm in Java:
First, you'll need a representation of a graph or tree. For this example, let's assume you have a basic graph represented as an adjacency list.
import java.util.*;
public class BFSExample {
public static class Graph {
private int V; // Number of vertices
private LinkedList<Integer>[] adj; // Adjacency list
public Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; i++) {
adj[i] = new LinkedList<>();
}
}
public void addEdge(int v, int w) {
adj[v].add(w);
}
public void BFS(int startVertex) {
boolean[] visited = new boolean[V];
LinkedList<Integer> queue = new LinkedList<>();
visited[startVertex] = true;
queue.add(startVertex);
while (!queue.isEmpty()) {
startVertex = queue.poll();
System.out.print(startVertex + " ");
for (Integer n : adj[startVertex]) {
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
}
public static void main(String[] args) {
Graph g = new Graph(6);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
g.addEdge(3, 5);
System.out.println("Breadth-First Traversal (starting from vertex 0): ");
g.BFS(0);
}
}
In this code:
The
Graphclass represents an undirected graph using an adjacency list.addEdgeis a method for adding edges to the graph.BFSis the BFS algorithm implementation. It starts from a givenstartVertexand explores all reachable vertices from that vertex, printing them as it visits them.A boolean array,
visited, is used to keep track of visited vertices. ALinkedListnamedqueueis used to manage the order of vertices to visit.In the
mainmethod, we create an instance of theGraphclass, add edges to create a sample graph, and then call theBFSmethod to perform a breadth-first traversal, starting from vertex 0.
How do you implement a depth-first search (DFS) algorithm in Java?
Depth-First Search (DFS) is an algorithm used to traverse or search through a graph or tree data structure. It explores as far as possible along a branch before backtracking. Here's how you can implement a DFS algorithm in Java:
First, you'll need a representation of a graph or tree. For this example, let's assume you have a basic graph represented as an adjacency list.
import java.util.*;
public class DFSExample {
public static class Graph {
private int V; // Number of vertices
private LinkedList<Integer>[] adj; // Adjacency list
public Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; i++) {
adj[i] = new LinkedList<>();
}
}
public void addEdge(int v, int w) {
adj[v].add(w);
}
public void DFS(int startVertex) {
boolean[] visited = new boolean[V];
DFSUtil(startVertex, visited);
}
private void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
System.out.print(v + " ");
for (Integer n : adj[v]) {
if (!visited[n]) {
DFSUtil(n, visited);
}
}
}
}
public static void main(String[] args) {
Graph g = new Graph(6);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
g.addEdge(3, 5);
System.out.println("Depth-First Traversal (starting from vertex 0): ");
g.DFS(0);
}
}
In this code:
The
Graphclass represents an undirected graph using an adjacency list.addEdgeis a method for adding edges to the graph.DFSis the DFS algorithm implementation. It starts from a givenstartVertexand explores all reachable vertices from that vertex, printing them as it visits them.A boolean array,
visited, is used to keep track of visited vertices.The actual DFS traversal is performed by the
DFSUtilmethod, which is a recursive function that explores adjacent vertices.In the
mainmethod, we create an instance of theGraphclass, add edges to create a sample graph, and then call theDFSmethod to perform a depth-first traversal, starting from vertex 0.
How do you find the maximum subarray sum in an array in Java?
You can find the maximum subarray sum in an array using the Kadane's algorithm, which is a well-known algorithm for this problem. Kadane's algorithm is an efficient way to find the maximum subarray sum in a one-dimensional array. Here's how you can implement it in Java:
public class MaxSubarraySum {
public static int findMaxSubarraySum(int[] nums) {
int maxEndingHere = nums[0];
int maxSoFar = nums[0];
for (int i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
public static void main(String[] args) {
int[] nums = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
int maxSubarraySum = findMaxSubarraySum(nums);
System.out.println("Maximum Subarray Sum: " + maxSubarraySum);
}
}
In this code:
The
findMaxSubarraySummethod takes an integer arraynumsas input and returns the maximum subarray sum.We initialize two variables,
maxEndingHereandmaxSoFar, both initially set to the first element of the array.We iterate through the array starting from the second element. For each element, we update
maxEndingHereto be the maximum of the current element and the sum of the current element andmaxEndingHere. This keeps track of the maximum subarray ending at the current position.We also update
maxSoFarto be the maximum of its current value andmaxEndingHere. This ensures that it always stores the maximum subarray sum seen so far.After the loop,
maxSoFarwill contain the maximum subarray sum, and we return it.In the
mainmethod, we create an example arraynums, callfindMaxSubarraySumto find the maximum subarray sum, and then print the result.
How do you implement a stack in Java?
In Java, you can implement a stack data structure using the built-in java.util.Stack class or by creating your custom stack using an array or a linked list. Here, I'll show you how to create a custom stack using an array:
javaCopy codepublic class CustomStack {
private int maxSize;
private int top;
private int[] stackArray;
public CustomStack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int item) {
if (top < maxSize - 1) {
stackArray[++top] = item;
} else {
System.out.println("Stack is full. Cannot push " + item);
}
}
public int pop() {
if (!isEmpty()) {
return stackArray[top--];
} else {
System.out.println("Stack is empty. Cannot pop.");
return -1; // Return a sentinel value to indicate an empty stack
}
}
public int peek() {
if (!isEmpty()) {
return stackArray[top];
} else {
System.out.println("Stack is empty. Cannot peek.");
return -1; // Return a sentinel value to indicate an empty stack
}
}
public boolean isEmpty() {
return top == -1;
}
public int size() {
return top + 1;
}
public static void main(String[] args) {
CustomStack stack = new CustomStack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Stack size: " + stack.size());
System.out.println("Top element: " + stack.peek());
while (!stack.isEmpty()) {
System.out.println("Popped: " + stack.pop());
}
}
}
In this code:
The
CustomStackclass represents a stack using an array.The
pushmethod adds an item to the top of the stack, and thepopmethod removes and returns the item from the top of the stack.The
peekmethod allows you to view the top item without removing it.The
isEmptymethod checks if the stack is empty, and thesizemethod returns the number of elements in the stack.In the
mainmethod, an instance of theCustomStackclass is created, and some items are pushed onto the stack. Then, the stack's size, top element, and the items are popped one by one.
How do you find the sum of the digits of a given integer in Java?
To find the sum of the digits of a given integer in Java, you can use a loop to extract each digit and accumulate their sum. Here's a simple Java program to accomplish this:
public class SumOfDigits {
public static int sumOfDigits(int number) {
int sum = 0;
while (number != 0) {
int digit = number % 10; // Get the last digit
sum += digit; // Add the digit to the sum
number /= 10; // Remove the last digit
}
return sum;
}
public static void main(String[] args) {
int number = 12345;
int result = sumOfDigits(number);
System.out.println("The sum of the digits of " + number + " is: " + result);
}
}
In this code:
The
sumOfDigitsmethod takes an integernumberas input and calculates the sum of its digits. It initializes a variablesumto 0 to store the sum.Inside a
whileloop, it repeatedly extracts the last digit of the number using the modulo operator (%) and adds it to thesum. It then removes the last digit by dividing the number by 10.The loop continues until the number becomes 0, at which point all the digits have been processed.
In the
mainmethod, we callsumOfDigitswith an example integernumber, and then print the result.
How do you find the factorial of a given number in Java?
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}How do you implement a merge sort algorithm in Java?
public static void mergeSort(int[] arr) {
if (arr.length < 2) {
return;
}
int mid = arr.length / 2;
int[] left = Arrays.copyOfRange(arr, 0, mid);
int[] right = Arrays.copyOfRange(arr, mid, arr.length);
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
private static void merge(int[] arr, int[] left, int[] right) {
int i = 0;
int j = 0;
int k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
while (i < left.length) {
arr[k++] = left[i++];
}
while (j < right.length) {
arr[k++] = right[j++];
}
}How do you find the most common element in an array in Java?
To find the most common (or frequently occurring) element in an array in Java, you can use a combination of data structures like HashMap and a loop to iterate through the array and count the occurrences of each element. Here's an example using a HashMap:
import java.util.*;
public class MostCommonElement {
public static int findMostCommonElement(int[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("The array is empty.");
}
// Create a HashMap to store the count of each element in the array
Map<Integer, Integer> elementCount = new HashMap<>();
int mostCommonElement = arr[0]; // Initialize the most common element to the first element
int maxCount = 1; // Initialize the maximum count to 1
for (int element : arr) {
if (elementCount.containsKey(element)) {
int newCount = elementCount.get(element) + 1;
elementCount.put(element, newCount);
if (newCount > maxCount) {
maxCount = newCount;
mostCommonElement = element;
}
} else {
elementCount.put(element, 1);
}
}
return mostCommonElement;
}
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
int mostCommon = findMostCommonElement(arr);
System.out.println("The most common element is: " + mostCommon);
}
}
In this code:
The
findMostCommonElementmethod takes an arrayarras input and returns the most common element.We use a
HashMapcalledelementCountto store the count of each element in the array.We iterate through the array, and for each element, we check if it's already in the
elementCountmap. If it is, we update its count and check if it's become the most common element.If the element is not in the map, we add it with a count of 1.
After the loop, we return the most common element based on the maximum count.
In the
mainmethod, we provide an example array and callfindMostCommonElementto find and print the most common element.
How do you print all the three character strings made from the characters of string "abc" in Java?
To print all the three-character strings made from the characters of the string "abc" in Java, you can use a nested loop to generate combinations of characters. Here's an example:
public class ThreeCharacterStrings {
public static void main(String[] args) {
String characters = "abc";
for (int i = 0; i < characters.length(); i++) {
for (int j = 0; j < characters.length(); j++) {
for (int k = 0; k < characters.length(); k++) {
char firstChar = characters.charAt(i);
char secondChar = characters.charAt(j);
char thirdChar = characters.charAt(k);
String threeCharString = String.valueOf(firstChar) + secondChar + thirdChar;
System.out.println(threeCharString);
}
}
}
}
}
In this code:
We have the string "abc" in the
charactersvariable.We use three nested
forloops to generate all possible combinations of characters.The outer loop iterates over the characters in the string, and the inner loops iterate over all characters in the string.
Within the nested loops, we use the
charAtmethod to retrieve characters at specific indices and then concatenate them to create a three-character string.We print each generated three-character string in the innermost loop.
Leave a Comment