0% found this document useful (0 votes)
71 views10 pages

Java String Array Problems Explained

The document presents a collection of Java programming problems focused on manipulating arrays of strings, including finding the longest and shortest strings, counting occurrences, concatenating, reversing, and replacing characters. Each problem includes a detailed explanation of the logic, sample Java code, and expected output. The document serves as a practical guide for practicing string and array operations in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views10 pages

Java String Array Problems Explained

The document presents a collection of Java programming problems focused on manipulating arrays of strings, including finding the longest and shortest strings, counting occurrences, concatenating, reversing, and replacing characters. Each problem includes a detailed explanation of the logic, sample Java code, and expected output. The document serves as a practical guide for practicing string and array operations in Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Array and String Programs – 10 Solved Questions

(Part 1 of 2)

Problem Statement:
Given an array of strings, find the longest string in the array.
Logic Explanation:
Iterate through the array while tracking the current longest string. Compare lengths and update when a longer
string is found. Return or print the longest at the end.
Java Code:
public class LongestStringInArray {
public static void main(String[] args) {
String[] arr = {"apple", "banana", "kiwi", "strawberry"};
String longest = [Link] > 0 ? arr[0] : "";
for (String s : arr) {
if ([Link]() > [Link]()) {
longest = s;
}
}
[Link]("Longest string: " + longest);
}
}

Expected Output:
Longest string: strawberry
Line-by-Line Explanation:
- Initialize `longest` to first element or empty.
- Loop through each string `s` in `arr`.
- If `[Link]()` is greater than `[Link]()`, assign `longest = s`.
- After loop, print `longest`.
Problem Statement:
Given an array of strings, count how many strings start with the letter 'a'.
Logic Explanation:
Traverse the array and for each string check if it starts with 'a' or 'A' using `startsWith` after lowercasing or by
checking first char. Increment a counter when true.
Java Code:
public class CountStartsWithA {
public static void main(String[] args) {
String[] arr = {"apple", "banana", "apricot", "avocado", "cherry"};
int count = 0;
for (String s : arr) {
if (![Link]() && [Link]([Link](0)) == 'a') {
count++;
}
}
[Link]("Count starting with 'a': " + count);
}
}

Expected Output:
Count starting with 'a': 3
Line-by-Line Explanation:
- Initialize `count` to 0.
- For each `s`, ensure it's not empty.
- Check first character using `charAt(0)` and `[Link]`.
- Increment `count` when the character is 'a'.
- Print the total.
Problem Statement:
Given an array of strings, concatenate all the strings into a single string separated by a space.
Logic Explanation:
Use a `StringBuilder` to append each string followed by a space. After loop, remove trailing space (if any) or
handle first element separately to avoid extra spaces.
Java Code:
public class ConcatStrings {
public static void main(String[] args) {
String[] arr = {"Hello", "world", "from", "AI"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < [Link]; i++) {
[Link](arr[i]);
if (i < [Link] - 1) [Link](" ");
}
[Link]([Link]());
}
}

Expected Output:
Hello world from AI
Line-by-Line Explanation:
- Create `StringBuilder sb`.
- Append each element; if not last, append a space.
- Convert `sb` to string and print.
Problem Statement:
Given an array of strings, find the shortest string in the array.
Logic Explanation:
Iterate through array while tracking the shortest string found so far by comparing lengths. Update when a
shorter string is found.
Java Code:
public class ShortestStringInArray {
public static void main(String[] args) {
String[] arr = {"cat", "dog", "elephant", "bee"};
String shortest = [Link] > 0 ? arr[0] : "";
for (String s : arr) {
if ([Link]() < [Link]()) {
shortest = s;
}
}
[Link]("Shortest string: " + shortest);
}
}

Expected Output:
Shortest string: bee
Line-by-Line Explanation:
- Initialize `shortest` to first element.
- For each `s`, if `[Link]()` < `[Link]()`, update `shortest`.
- Print `shortest`.
Problem Statement:
Given an array of strings, reverse each string in the array.
Logic Explanation:
Loop through the array, for each string build its reverse using `[Link]()` or manual character
swapping, and store the reversed string back or in a new array.
Java Code:
public class ReverseEachString {
public static void main(String[] args) {
String[] arr = {"abc", "def", "ghi"};
String[] res = new String[[Link]];
for (int i = 0; i < [Link]; i++) {
res[i] = new StringBuilder(arr[i]).reverse().toString();
}
for (String s : res) [Link](s);
}
}

Expected Output:
cba
fed
ihg
Line-by-Line Explanation:
- Create result array `res` of same length.
- For each index `i`, reverse `arr[i]` with `StringBuilder` and store in `res[i]`.
- Print each reversed string.
Problem Statement:
Given an array of strings, find the number of strings that have a length greater than 5.
Logic Explanation:
Traverse the array and increment a counter whenever the length of a string exceeds 5.
Java Code:
public class CountLengthGreaterThanFive {
public static void main(String[] args) {
String[] arr = {"apple", "banana", "kiwi", "strawberry"};
int count = 0;
for (String s : arr) {
if ([Link]() > 5) count++;
}
[Link]("Count > 5: " + count);
}
}

Expected Output:
Count > 5: 2
Line-by-Line Explanation:
- Initialize `count`.
- For each `s`, if `[Link]() > 5`, increment `count`.
- Print the count.
Problem Statement:
Given an array of strings, find the string that appears most frequently.
Logic Explanation:
Use a `HashMap` to count frequencies. Iterate entries to find the key with maximum value.
Java Code:
import [Link].*;
public class MostFrequentString {
public static void main(String[] args) {
String[] arr = {"apple", "banana", "apple", "kiwi", "banana", "banana"};
Map<String, Integer> freq = new HashMap<>();
for (String s : arr) [Link](s, [Link](s, 0) + 1);
String most = null;
int max = 0;
for ([Link]<String, Integer> e : [Link]()) {
if ([Link]() > max) {
max = [Link]();
most = [Link]();
}
}
[Link]("Most frequent: " + most);
}
}

Expected Output:
Most frequent: banana
Line-by-Line Explanation:
- Build frequency map `freq`.
- Track `most` and `max` while iterating map entries.
- Update when a higher count found.
- Print the result.
Problem Statement:
Given an array of strings, sort the array in alphabetical order.
Logic Explanation:
Use `[Link]` which sorts strings lexicographically. For custom locale or case-insensitive, use a
comparator.
Java Code:
import [Link];
public class SortStrings {
public static void main(String[] args) {
String[] arr = {"banana", "apple", "kiwi", "cherry"};
[Link](arr);
for (String s : arr) [Link](s);
}
}

Expected Output:
apple
banana
cherry
kiwi
Line-by-Line Explanation:
- Call `[Link](arr)` to sort in place.
- Print sorted array.
Problem Statement:
Given an array of strings, find all strings that contain the substring "an".
Logic Explanation:
Iterate through array and use `contains("an")` to check substring presence, collect matching strings in a list.
Java Code:
import [Link].*;
public class FindSubstringAn {
public static void main(String[] args) {
String[] arr = {"banana", "apple", "kiwi", "mango"};
List<String> res = new ArrayList<>();
for (String s : arr) if ([Link]("an")) [Link](s);
[Link](res);
}
}

Expected Output:
[banana, mango]
Line-by-Line Explanation:
- Create list `res`.
- For each `s`, if `[Link]("an")`, add to `res`.
- Print `res`.
Problem Statement:
Given an array of strings, replace all occurrences of the letter 'a' with 'x' in each string.
Logic Explanation:
Loop through each string and use `replace('a','x')`. Store results in a new array or overwrite the original.
Java Code:
public class ReplaceAWithX {
public static void main(String[] args) {
String[] arr = {"apple", "banana", "kiwi"};
String[] res = new String[[Link]];
for (int i = 0; i < [Link]; i++) {
res[i] = arr[i].replace('a', 'x');
}
for (String s : res) [Link](s);
}
}

Expected Output:
xpple
bxnxnx
kiwi
Line-by-Line Explanation:
- For each index, call `replace('a','x')` and store in `res`.
- Print each transformed string.

Common questions

Powered by AI

To count strings starting with 'a', iterate through the array, checking the first character of each string after converting it to lowercase. Use a counter to record each occurrence. This method is effective as it ensures all case variations are considered and that only non-empty strings are checked, maintaining efficiency and accuracy.

Finding the shortest string involves initializing a variable with the first string or an empty one if the array is empty, iterating through each string, and updating if a shorter one is found. This approach effectively ensures every string is checked, optimally identifying the shortest by minimizing operations and leveraging direct length comparisons.

Reversing each string in an array involves creating an array of the same length to store results. For each string, use methods like 'StringBuilder.reverse()' to create a reversed version and store it in the new array. The logic handle each string individually, reversing the characters using built-in string manipulation tools efficiently and storing each result separately.

Finding the most frequent string involves using a 'HashMap' to count occurrences of each string. The map iterates to track frequency, updating if a higher frequency is found. Challenges include handling ties in frequencies and ensuring the map efficiently stores and updates count for potentially large arrays to maintain performance.

The longest string in an array can be identified by iterating through each string and keeping track of the currently longest string. Initially, the longest string is set to the first element or an empty string if the array is empty. For each string, compare its length to the current longest string. If it's longer, update the longest string variable. This approach ensures all strings are checked, and the longest is found by the end of the loop.

The logic to find strings longer than five characters involves iterating through the array and incrementing a counter for each string exceeding length five. This simple and direct comparison ensures efficiency, directly checking each string without unnecessary operations, maintaining clarity and performance.

Identifying strings with a specific substring involves iterating through the array and using a method like 'contains()' to check each string for the presence of the substring. Results are collected in a list. Considerations include case sensitivity and the possibility of overlapping substrings. Efficient string operations are vital to handling large arrays.

Concatenating strings into one involves using a 'StringBuilder' to append each string followed by a space. After the last string, the trailing space is either manually removed or avoided by a conditional space addition during the loop. This prevents extra spaces in the final output. The approach leverages 'StringBuilder' for performance efficiency over repeated string concatenation.

To replace 'a' with 'x', loop through each string and apply 'replace('a','x')', storing results in a new or the same array. The method efficiently replaces all occurrences in one pass per string. Benefits include simplicity and use of direct method calls, which ensure performance and code readability.

Strings are sorted alphabetically using 'Arrays.sort', which orders strings lexicographically by default. For custom sorting, such as ignoring case or specific locale consideration, a comparator can be used. This method effectively rearranges strings based on natural order unless specified otherwise by a comparator, ensuring proper localization and case ordering as needed.

You might also like