0% found this document useful (0 votes)
8 views3 pages

Java Programming Practice Problems

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)
8 views3 pages

Java Programming Practice Problems

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

Question 1:

public class ReverseString {


public static void main(String[] args) {
String str = "Hello";
String reversed = reverseString(str);
[Link](reversed);
}

public static String reverseString(String str) {


StringBuilder sb = new StringBuilder(str);
return [Link]();
}

Expected Output:

Expected Output:
olleH

Question 2:
public class MaxFinder {
public static void main(String[] args) {
int[] arr = {1, 5, 3, 9, 2};
int max = findMax(arr);
[Link]("Max: " + max);
}

public static int findMax(int arr) {


int max = arr[0];
for (int i = 1; i <= [Link]; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
}

Expected Output:

Expected Output:
Max: 9

Question 3:
public class PrimeCheck {
public static void main(String[] args) {
int num = 29;
boolean result = isPrime(num);
[Link](num + " is prime: " + result);
}
public static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i <= num / 2; i++) {
if (num % i = 0) {
return false;
}
}
return true
}
}

Expected Output:

Expected Output:
29 is prime: true

Question 4:
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;
swap(a, b);
[Link]("a: " + a + ", b: " + b);
}

public static void swap(int a, int b) {


a = a + b;
b = a - b;
a = a - b;
}
}

Expected Output:

Expected Output:
a: 10, b: 5

Question 5:
public class VowelCounter {
public static void main(String[] args) {
String str = "Hello World";
int count = countVowels(str);
[Link]("Vowel count: " + count);
}

public static int countVowels(String str) {


int count = 0;
for (char c : [Link]()) {
if ("aeiouAEIOU".contains(c)) {
count++
}
}
return count;
}
}

Expected Output:

Expected Output:
Vowel count: 3

Common questions

Powered by AI

The VowelCounter program can be extended by creating a map structure to store counts of individual vowels, or by modifying the countVowels function to iterate over str and update a hash map with counts for each individual vowel, providing detailed statistics. Additionally, it can be extended to count vowel occurrences irrespective of case or provide percentages of vowel occurrence based on total letters. Another extension might include identifying the most frequent vowel in the input string.

Potential coding style improvements across all programs include adhering to naming conventions, such as using camelCase for variable names (e.g., maxFinder instead of MaxFinder), ensuring spacing around operators for readability, adding comments for code clarity, using proper access modifiers for methods and classes, and maintaining consistent indentation. Adding unit tests for each method to ensure functionality and prevent regressions would also be beneficial. Finally, considering the inclusion of logging instead of printing directly to ease debugging and enhance scalability.

The findMax method currently traverses the array using a single loop which is already optimal in time complexity, O(n). However, you could optimize further for readability and ensure robustness by checking for an empty array case or using Streams in Java 8+: Arrays.stream(arr).max(). Or, if parallel processing is a focus, using parallel streams for potential performance benefits on large datasets can be considered.

To correct the output while keeping the core swapping logic intact, a helper class or an array can be used. For example, encapsulate a and b within an object, or modify swap to take an integer array where the swap is performed directly on the array elements. This way, the original references are manipulated and produce the expected output. Alternatively, return a new array with swapped values and print accordingly.

The VowelCounter program contains a logic error in the if statement: "aeiouAEIOU".contains(c). The contains() method does not work directly with characters. Instead, it can be fixed by replacing "aeiouAEIOU".contains(c) with "aeiouAEIOU".indexOf(c) != -1. This will correctly identify vowels within the string.

The PrimeCheck program checks divisibility up to num / 2, which is less efficient than necessary. A more efficient algorithm would only check up to the square root of num, as if a number n is divisible by a number greater than its square root, then it must also be divisible by a number smaller than its square root. Thus, change for (int i = 2; i <= num / 2; i++) to for (int i = 2; i <= Math.sqrt(num); i++)

The mistake in the MaxFinder program is that the for-loop condition uses i <= arr.length, which leads to an ArrayIndexOutOfBoundsException because arrays in Java are zero-indexed and arr.length is the size, which is one index beyond the last element. The loop should use i < arr.length instead of i <= arr.length.

Error handling in the PrimeCheck program can be improved by checking if the input is negative or not a valid integer. While the program checks for num < 2, which covers negative inputs, adding a preliminary check and exception handling can improve robustness. For instance, try-catch blocks to handle non-integer inputs during parsing or method calls. Additionally, an if statement could explicitly check and log negative numbers or zero, or even throw IllegalArgumentException if unexpected values are provided.

The error in the ReverseString program is in the reverseString method where it uses sb.reverse.toString(); instead of sb.reverse().toString();. The reverse() is a method call and needs parentheses to be invoked properly. To correct this, change return sb.reverse.toString(); to return sb.reverse().toString()

The SwapNumbers program doesn't affect the original variables a and b in the main method because Java is pass-by-value, meaning the swap method only changes the copies of the values, not the originals. To actually swap the values, the swap method needs to be implemented to manipulate the actual objects containing a and b, or alternatively return the swapped values. As written, there's no correct way to fix it without altering its logic because integer swapping in Java requires either using wrapper objects or an array.

You might also like