[Go to site: main page, start]

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

Java String Array Operations

The document contains Java code snippets for various string and array manipulations, including reversing a string, counting vowels, checking for palindromes, and calculating character frequency. It also includes operations for arrays such as summing elements, finding the maximum value, reversing, sorting, and copying arrays. Each code snippet is self-contained and demonstrates a specific programming task.

Uploaded by

4010vandana
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)
23 views3 pages

Java String Array Operations

The document contains Java code snippets for various string and array manipulations, including reversing a string, counting vowels, checking for palindromes, and calculating character frequency. It also includes operations for arrays such as summing elements, finding the maximum value, reversing, sorting, and copying arrays. Each code snippet is self-contained and demonstrates a specific programming task.

Uploaded by

4010vandana
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

public class ReverseString {


public static void main(String[] args) {
String str = "Hello";
String reversed = "";
for(int i = [Link]() - 1; i >= 0; i--) {
reversed += [Link](i);
}
[Link]("Reversed string: " + reversed);
}
}

2. Count Vowels in a String

public class VowelCount {


public static void main(String[] args) {
String str = "Programming";
int count = 0;
for(char c : [Link]().toCharArray()) {
if("aeiou".indexOf(c) != -1) count++;
}
[Link]("Vowels: " + count);
}
}

3. Palindrome Check

public class Palindrome {


public static void main(String[] args) {
String str = "madam";
String rev = new StringBuilder(str).reverse().toString();
[Link]([Link](rev) ? "Palindrome" : "Not a palindrome");
}
}

4. Frequency of Characters

import [Link];
public class CharFrequency {
public static void main(String[] args) {
String str = "hello";
HashMap<Character, Integer> freq = new HashMap<>();
for(char c : [Link]()) {
[Link](c, [Link](c, 0) + 1);
}
[Link](freq);
}
}

5. String to Character Array

public class StringToCharArray {


public static void main(String[] args) {
String str = "World";
char[] chars = [Link]();
for(char c : chars) {
[Link](c + " ");
}
}
}

6. Sum of Array Elements

public class SumArray {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
for(int num : arr) sum += num;
[Link]("Sum: " + sum);
}
}

7. Find Maximum in Array

public class MaxArray {


public static void main(String[] args) {
int[] arr = {10, 5, 20, 8};
int max = arr[0];
for(int num : arr) {
if(num > max) max = num;
}
[Link]("Max: " + max);
}
}

8. Reverse an Array

public class ReverseArray {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
for(int i = [Link] - 1; i >= 0; i--) {
[Link](arr[i] + " ");
}
}
}

9. Sort an Array

import [Link];
public class SortArray {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1};
[Link](arr);
[Link]([Link](arr));
}
}

10. Copy an Array

import [Link];
public class CopyArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
int[] copy = [Link](arr, [Link]);
[Link]([Link](copy));
}
}

Common questions

Powered by AI

The Palindrome class checks if a string is a palindrome by reversing the string using a StringBuilder and then comparing the original and reversed strings. It uses the `reverse` method of StringBuilder to efficiently reverse the string and the `equals` method to compare . StringBuilder is chosen over String concatenation because it is more efficient for string manipulations, allowing for mutable sequences of characters, which reduces the overhead of creating new objects.

The CopyArray class demonstrates array copying using the `Arrays.copyOf()` method to create a duplicate of an existing array . Such copying is critical in scenarios where modifications to the cloned array should not affect the original array, like in multi-threaded applications or when implementing undo features, ensuring data integrity.

The MaxArray class determines the maximum value by iterating through the array with an initial assumption that the first element is the maximum. As it iterates, it updates this maximum if it finds a larger value . This method is effective for large datasets with a time complexity of O(n), but if concurrency or distributed arrays are involved, additional considerations for efficiency might be needed.

The SumArray class calculates the sum of array elements by iterating through the array and accumulating the total in a variable `sum` initialized to zero . The efficiency implication of this method is its simplicity with a time complexity of O(n), where n is the length of the array, making it optimal for this operation.

The SortArray class sorts an array using the `Arrays.sort()` method, which is part of Java's standard library . This method uses the TimSort algorithm, which is a hybrid sorting algorithm derived from merge sort and insertion sort, providing O(n log n) performance on average and is efficient on many real-world data sets.

The ReverseString class reverses a string by iterating through the original string from the last character to the first and appending each character to a new string. This process uses the `charAt` method to access each character and concatenates it to the `reversed` string . A potential inefficiency in this method is the repeated string concatenation, which creates a new string each time due to the immutability of strings in Java, leading to increased time complexity and memory usage with longer strings.

The CharFrequency class determines character frequency using a HashMap, where it iterates over each character of the string. It uses the `getOrDefault` method to check the current count of each character, updating the count and placing it back into the map . This approach allows quick updates and retrieval of counts, making it efficient with a time complexity of O(n) for processing the string.

The ReverseArray class manually reverses an array by iterating from the last index to the first, printing each element . An improvement could involve performing an in-place reversal using a two-pointer approach, swapping elements from both ends until the center is reached, avoiding unnecessary memory usage.

The StringToCharArray class converts a string into a character array using the `toCharArray` method and then prints each character followed by a space . A limitation of this approach is that it simply prints characters with spaces, offering no additional functionality for operations on the array or formatted outputs.

The VowelCount class counts vowels by converting the string to lowercase and iterating over its characters. For each character, it checks if it is present in the string 'aeiou' using the `indexOf` method. If it is, it increments the count . The time complexity of this approach is O(n), where n is the length of the string, because each character is checked once.

You might also like