0% found this document useful (0 votes)
22 views9 pages

Essential Java String and Array Methods

Java multiple coding questions

Uploaded by

styles7001
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)
22 views9 pages

Essential Java String and Array Methods

Java multiple coding questions

Uploaded by

styles7001
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

1. Reverse a string.

String str = "hello";


String rev = "";
for (int i = [Link]() - 1; i >= 0; i--) {
rev += [Link](i);
}
[Link](rev);

2. Check if a string is a palindrome.


String str = "madam";
boolean isPalindrome = true;
for (int i = 0; i < [Link]() / 2; i++) {
if ([Link](i) != [Link]([Link]() - 1 - i)) {
isPalindrome = false;
break;
}
}
[Link](isPalindrome);

3. Print Fibonacci series up to N terms.


int n = 10, a = 0, b = 1;
for (int i = 1; i <= n; i++) {
[Link](a + " ");
int sum = a + b;
a = b;
b = sum;
}

4. Check if a number is prime.


int num = 7;
boolean isPrime = num > 1;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
[Link](isPrime);

5. Find factorial of a number.


int num = 5;
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
[Link](fact);

6. Find the largest element in an array.


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

7. Find the second largest element in an array.


int[] arr = {4, 2, 7, 1};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int i = 0; i < [Link]; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
[Link](second);

8. Count vowels and consonants in a string.


String str = "hello";
int vowels = 0, consonants = 0;
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
if ("aeiouAEIOU".indexOf(ch) != -1) vowels++;
else consonants++;
}
}
[Link]("Vowels: " + vowels + ", Consonants: " + consonants);

9. Reverse an integer.
int num = 1234, rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
[Link](rev);

10. Check if two strings are anagrams.


String a = "listen", b = "silent";
if ([Link]() != [Link]()) {
[Link]("Not Anagram");
} else {
int[] count = new int[256];
for (int i = 0; i < [Link](); i++) {
count[[Link](i)]++;
count[[Link](i)]--;
}
boolean isAnagram = true;
for (int i = 0; i < 256; i++) {
if (count[i] != 0) {
isAnagram = false;
break;
}
}
[Link](isAnagram ? "Anagram" : "Not Anagram");
}

21. Check if a number is even or odd.


int num = 10;
if (num % 2 == 0) {
[Link](num + " is even.");
} else {
[Link](num + " is odd.");
}

22. Find GCD of two numbers.


int a = 36, b = 60, gcd = 1;
for (int i = 1; i <= a && i <= b; i++) {
if (a % i == 0 && b % i == 0) gcd = i;
}
[Link]("GCD: " + gcd);

23. Find LCM of two numbers.


int a = 12, b = 18;
int max = (a > b) ? a : b;
while (true) {
if (max % a == 0 && max % b == 0) {
[Link]("LCM: " + max);
break;
}
max++;
}

24. Check if a number is positive or negative.


int num = -5;
if (num > 0) [Link]("Positive");
else if (num < 0) [Link]("Negative");
else [Link]("Zero");

25. Find power of a number.


int base = 2, exp = 3, result = 1;
for (int i = 1; i <= exp; i++) {
result *= base;
}
[Link]("Result: " + result);

26. Print all even numbers up to N.


int n = 10;
for (int i = 2; i <= n; i += 2) {
[Link](i + " ");
}

27. Print all prime numbers up to N.


int n = 20;
for (int i = 2; i <= n; i++) {
boolean prime = true;
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
prime = false;
break;
}
}
if (prime) [Link](i + " ");
}

28. Count words in a string.


String str = "This is a test";
String[] words = [Link]().split("\\s+");
[Link]("Word count: " + [Link]);

29. Convert string to uppercase.


String str = "hello";
[Link]([Link]());

30. Convert string to lowercase.


String str = "HELLO";
[Link]([Link]());

31. Reverse each word in a string.


String str = "Java Code";
String[] words = [Link](" ");
for (String word : words) {
String rev = "";
for (int i = [Link]() - 1; i >= 0; i--) {
rev += [Link](i);
}
[Link](rev + " ");
}
32. Remove duplicate characters from string.
String str = "programming";
String result = "";
for (int i = 0; i < [Link](); i++) {
if ([Link]([Link](i)) == -1) {
result += [Link](i);
}
}
[Link](result);

33. Count occurrences of each character.


String str = "hello";
int[] count = new int[256];
for (char c : [Link]()) count[c]++;
for (int i = 0; i < [Link]; i++) {
if (count[i] > 0) [Link]((char)i + ": " + count[i]);
}

34. Check if string contains only digits.


String str = "12345";
boolean isDigit = [Link]("\\d+");
[Link]("Only digits? " + isDigit);

35. Find missing number in array 1 to N.


int[] arr = {1, 2, 4, 5};
int n = 5, sum = n * (n + 1) / 2, actual = 0;
for (int val : arr) actual += val;
[Link]("Missing: " + (sum - actual));

36. Sum of array elements.


int[] arr = {1, 2, 3};
int sum = 0;
for (int num : arr) sum += num;
[Link]("Sum: " + sum);

37. Merge two arrays.


int[] a = {1, 2}, b = {3, 4};
int[] result = new int[[Link] + [Link]];
[Link](a, 0, result, 0, [Link]);
[Link](b, 0, result, [Link], [Link]);
for (int i : result) [Link](i + " ");

38. Copy array.


int[] src = {1, 2, 3};
int[] dest = new int[[Link]];
for (int i = 0; i < [Link]; i++) dest[i] = src[i];
for (int i : dest) [Link](i + " ");

39. Check if array contains an element.


int[] arr = {1, 2, 3};
int key = 2, found = 0;
for (int i : arr) if (i == key) found = 1;
[Link](found == 1 ? "Found" : "Not Found");

40. Find smallest element in array.


int[] arr = {5, 2, 8};
int min = arr[0];
for (int i = 1; i < [Link]; i++) if (arr[i] < min) min = arr[i];
[Link]("Min: " + min);

41. Example coding problem 41.


// Complete code for problem 41
[Link]("Code for problem 41 here.");

42. Example coding problem 42.


// Complete code for problem 42
[Link]("Code for problem 42 here.");

43. Example coding problem 43.


// Complete code for problem 43
[Link]("Code for problem 43 here.");

44. Example coding problem 44.


// Complete code for problem 44
[Link]("Code for problem 44 here.");

45. Example coding problem 45.


// Complete code for problem 45
[Link]("Code for problem 45 here.");

46. Example coding problem 46.


// Complete code for problem 46
[Link]("Code for problem 46 here.");

47. Example coding problem 47.


// Complete code for problem 47
[Link]("Code for problem 47 here.");

48. Example coding problem 48.


// Complete code for problem 48
[Link]("Code for problem 48 here.");

49. Example coding problem 49.


// Complete code for problem 49
[Link]("Code for problem 49 here.");

50. Example coding problem 50.


// Complete code for problem 50
[Link]("Code for problem 50 here.");

51. Example coding problem 51.


// Complete code for problem 51
[Link]("Code for problem 51 here.");

52. Example coding problem 52.


// Complete code for problem 52
[Link]("Code for problem 52 here.");

53. Example coding problem 53.


// Complete code for problem 53
[Link]("Code for problem 53 here.");
54. Example coding problem 54.
// Complete code for problem 54
[Link]("Code for problem 54 here.");

55. Example coding problem 55.


// Complete code for problem 55
[Link]("Code for problem 55 here.");

56. Example coding problem 56.


// Complete code for problem 56
[Link]("Code for problem 56 here.");

57. Example coding problem 57.


// Complete code for problem 57
[Link]("Code for problem 57 here.");

58. Example coding problem 58.


// Complete code for problem 58
[Link]("Code for problem 58 here.");

59. Example coding problem 59.


// Complete code for problem 59
[Link]("Code for problem 59 here.");

60. Example coding problem 60.


// Complete code for problem 60
[Link]("Code for problem 60 here.");

Common questions

Powered by AI

Checking for anagrams by using character counts is generally more efficient than sorting because it operates in linear time complexity, O(n), relative to the string length, whereas sorting involves O(n log n) complexity . The count method involves comparing the frequency of each character in both strings, offering a simple and practical way to determine if two strings are anagrams without rearranging them. The method is particularly effective in cases where unnecessary reordering of strings is undesirable or when handling very long strings.

The Least Common Multiple (LCM) of two numbers is calculated by iterating from the larger of the two numbers. This approach works because the LCM must be at least as large as the largest number. The algorithm starts from the larger number and checks successive multiples of it to find the smallest multiple that both numbers divide without a remainder . This method effectively minimizes the number of checks needed, as starting from the larger number directly reduces unnecessary iterations at lower multiples.

The array merging algorithm ensures elements are combined by first allocating a new array large enough to hold the contents of both input arrays, then copying the elements of the first array followed by the second array into their respective positions in the new array using `System.arraycopy` method . However, limitations exist if the arrays need dynamic resizing, as the static nature of arrays in such an approach doesn't allow for resizing without reallocating and copying, unlike more dynamic structures like lists.

The algorithm to check if a string is a palindrome works by comparing characters from the beginning and end of the string simultaneously, moving towards the center. If any pair of characters does not match, the string is not a palindrome. This is implemented by iterating up to half the length of the string, using `str.charAt(i) != str.charAt(str.length() - 1 - i)` to compare the characters . A limitation of this method is that it does not account for case insensitivity or non-alphanumeric characters, which could be relevant depending on the definition of 'palindrome' required in specific contexts.

The integer reversing algorithm works by repeatedly extracting the last digit of the number and appending it to the reverse number, updating the reverse by multiplying it by 10 and adding the digit. This process continues until all digits are reversed . However, this method does not handle overflows, which occur when the reversed number exceeds the representable range of integers. In a real application, additional checks would be needed to detect and handle such overflows, potentially using long variables or checking before multiplication.

The iterative algorithm to find the GCD of two numbers works by identifying the largest number that can divide both numbers without leaving a remainder. This is done by iteratively checking each number from 1 up to the smaller of the two input numbers, updating the GCD whenever the current number divides both inputs perfectly . This method is simple but not the most efficient for large numbers compared to algorithms like the Euclidean algorithm.

In a basic string reversal function, potential errors include using an invalid index if the string length is not checked appropriately, or incurring high memory consumption if the string is very large and not handled carefully . These can be mitigated by ensuring index boundaries are respected (using `str.length()` for loops) and by potentially optimizing memory usage using character arrays or streams instead of concatenating strings directly. Handling null or empty strings with early return conditions can also prevent such errors.

The method to determine prime numbers up to a specified limit iterates over each number starting from 2 to the limit, checking each number for primality. For each number, it checks divisibility by all numbers from 2 up to half of the number itself (as no factor other than the number itself can be greater than half). If no divisors are found, the number is prime . While simple, this method is inefficient for large limits as it checks many unnecessary numbers - optimization can be achieved by using methods like the Sieve of Eratosthenes, which is more computationally efficient.

Potential pitfalls in counting vowels and consonants include handling case sensitivity (not distinguishing between uppercase and lowercase letters properly) and treating non-alphabetical characters as consonants if not properly filtered . These can be mitigated by normalizing the case of characters using methods like `toLowerCase()`, and ensuring only alphabetical characters are counted by checking character properties (`ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'`). Additional checks should be included to ignore characters that are neither vowels nor consonants.

The algorithm to find the second largest element in an array iterates through the array once, maintaining two variables: one for the largest element (first) and one for the second largest (second). As it iterates, it updates the two variables such that any element bigger than 'first' makes 'second' take on 'first's value before 'first' is updated to the new largest. If an element is only larger than 'second' but not 'first', 'second' is updated directly . This ensures that by the end of the loop, 'second' captures the second-largest value, requiring only a single pass through the array.

You might also like