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

Java ArrayList Examples and Usage

The document contains multiple Java classes that demonstrate different functionalities. The 'SeparatePositiveNegative' class separates positive and negative integers from an array, the 'LongestWord' class finds the longest word in a given sentence, and the 'PangramChecker' class checks if a sentence is a pangram using two different implementations. Each class includes a main method that executes the respective functionality and prints the results.

Uploaded by

hitechbrain7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Java ArrayList Examples and Usage

The document contains multiple Java classes that demonstrate different functionalities. The 'SeparatePositiveNegative' class separates positive and negative integers from an array, the 'LongestWord' class finds the longest word in a given sentence, and the 'PangramChecker' class checks if a sentence is a pangram using two different implementations. Each class includes a main method that executes the respective functionality and prints the results.

Uploaded by

hitechbrain7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import [Link].

ArrayList;

public class SeparatePositiveNegative {


public static void main(String[] args) {
int[] arr = {-12, 11, -5, -7, -9, 6, -1, 5};
ArrayList<Integer> negative = new ArrayList<>();
ArrayList<Integer> positive = new ArrayList<>();

// Separate negative and positive numbers


for (int num : arr) {
if (num < 0) {
[Link](num);
} else {
[Link](num);
}
}

// Combine both lists into a single output array


[Link](positive);
[Link](negative);
}
}

public class LongestWord {


public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog";
String[] words = [Link](" ");
String longestWord = "";

for (String word : words) {


if ([Link]() > [Link]()) {
longestWord = word;
}
}

[Link]("The longest word is: " + longestWord);


}
}

package predrive9;

import [Link];
import [Link];

public class PangramChecker {


public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog";

if (isPangram(sentence)) {
[Link]("The sentence is a pangram.");
} else {
[Link]("The sentence is not a pangram.");
}
}
public static boolean isPangram(String sentence) {
Set<Character> letters = new HashSet<>();
sentence = [Link]();

for (int i = 0; i < [Link](); i++) {


char c = [Link](i);
if (c >= 'a' && c <= 'z') {
[Link](c);
}
}

return [Link]() == 26;


}
}

package predrive9;

public class PangramChecker {


public static void main(String[] args) {
String sentence = "The quick brown fox jumps over the lazy dog";

if (isPangram(sentence)) {
[Link]("The sentence is a pangram.");
} else {
[Link]("The sentence is not a pangram.");
}
}

public static boolean isPangram(String sentence) {


sentence = [Link]();
boolean[] letters = new boolean[26]; // Array to track each letter in the
alphabet

for (int i = 0; i < [Link](); i++) {


char c = [Link](i);
if (c >= 'a' && c <= 'z') {
letters[c - 'a'] = true; // Mark the corresponding letter as found
}
}

for (boolean found : letters) {


if (!found) {
return false; // If any letter is missing, it's not a pangram
}
}

return true; // All letters were found, so it's a pangram


}
}

Common questions

Powered by AI

The methodology involves splitting the sentence into an array of words using 'sentence.split(" ")'. It then iterates through each word and compares its length to the current longest known word, stored in 'longestWord'. If a word is found to be longer than 'longestWord', it overwrites 'longestWord'. After iterating through all words, the program prints the longest word determined from the sentence .

In the alternative method, the program uses a boolean array 'letters' of size 26 to track the presence of each lowercase alphabet letter in the sentence. As the program processes each character of the sentence, it checks if the character is a lowercase letter and marks the corresponding index in the 'letters' boolean array as 'true'. After processing, the program iterates through the boolean array, checking that every value is 'true'; if all are 'true', the sentence is a pangram, confirming that each letter of the alphabet has appeared at least once .

The method splits the sentence based on spaces, not accounting for punctuation that may be attached to words (e.g., 'dog;' or 'fox.'); thus, punctuation would be considered part of the word and might affect the length calculation inaccurately. This means the actual longest word might not be identified correctly if trailing punctuation is not stripped. An improved approach would separate punctuation from the words during the initial split or cleanse the input sentence before processing .

Testing for edge cases ensures algorithm robustness by identifying potential failures in unusual or extreme inputs not covered by typical scenarios. For pangram checking, examples include sentences with non-standard characters, extremely long texts filled with non-alphabetic symbols, or entirely uppercase sentences. For the longest word identification, edge cases involve sentences with only punctuation, variable whitespace, or words with punctuation. Considering edge cases reveals logical gaps or assumptions in initial implementations, prompting refinement to handle all potential inputs gracefully, ultimately improving reliability and performance in real-world applications .

Converting a sentence to lowercase ensures uniformity in character comparison, as it normalizes the input by eliminating case sensitivity issues. This step simplifies the algorithm since it avoids using additional logic to handle both uppercase and lowercase letters. If this step were omitted, the method would need to track both cases for each character separately or modify the logic to map cases to a unified representation, potentially complicating the implementation and increasing the likelihood of errors .

The program converts the sentence to lowercase to ensure uniformity in character comparison. It then iterates through each character, adding only alphabetic characters ('a' to 'z') to a HashSet named 'letters'. Since sets do not allow duplicates, this effectively results in a collection of unique alphabetic characters from the sentence. After processing the entire sentence, the program checks if the size of the 'letters' set is 26, which would confirm that all letters of the alphabet are present, indicating a pangram .

The 'addAll()' method in Java is used to append all elements from one collection to the end of another. This operation allows for efficient combination of collections, maintaining their order. However, the primary trade-off is the temporary increase in memory usage which can be considerable for large lists. Additionally, if the destination list is used elsewhere in the program, modifying it with 'addAll()' may inadvertently affect its other usages, potentially introducing side effects if not handled appropriately .

The program initializes two ArrayLists, 'negative' and 'positive', to store negative and positive integers, respectively. It iterates over the input array 'arr' and adds each number to the corresponding list based on whether it is negative or positive. After populating the lists, it combines 'negative' and 'positive' lists by using 'negative.addAll(positive)' to create a single list containing all integers from the input array, with all negative numbers first, followed by positive numbers. This list is then printed as the final output .

Modifying the sentence by removing any alphabet letter, regardless of which pangram check method is used, would result in both methods indicating that the sentence is no longer a pangram, as both methods rely on each letter of the alphabet being present. Additional spaces, punctuation, or non-alphabetic symbols will not affect the outcome since both methods specifically check for alphabetic characters. However, altering the logic that checks for these characters (e.g., changing the range conditions) could render them ineffective and lead to incorrect results .

Using a HashSet offers the advantage of simplicity in terms of automatically managing character presence since it inherently handles duplicates and size dynamically. However, it involves additional overhead due to object management and dynamic resizing. In contrast, a boolean array provides constant time access and manipulation since it directly maps characters to their respective index without additional overhead, making it more memory and time-efficient given a fixed alphabet size. For the task of checking pangrams, a boolean array might be slightly more efficient due to these reasons, particularly in constrained environments where performance overheads of dynamic data structures like HashSets can be significant .

You might also like