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

Java String Programs: Anagrams, Pangrams, Palindromes

Java Programs
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)
63 views3 pages

Java String Programs: Anagrams, Pangrams, Palindromes

Java Programs
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

Professional Java String Programs

1. Anagram Program (Java)


1.1 Explanation
An anagram is a word or phrase formed by rearranging the letters of another. This Java
program sorts and compares character arrays to check for anagrams.

1.2 Code
1 // Anagram Check Program in Java
2 import java . util . Arrays ;
3 import java . util . Scanner ;
4

5 public class AnagramCheck {


6 public static boolean areAnagram ( String str1 , String str2 ) {
7 if ( str1 . length () != str2 . length () ) return false ;
8 char [] a = str1 . toCharArray () ;
9 char [] b = str2 . toCharArray () ;
10 Arrays . sort ( a ) ;
11 Arrays . sort ( b ) ;
12 return Arrays . equals (a , b ) ;
13 }
14

15 public static void main ( String [] args ) {


16 Scanner sc = new Scanner ( System . in ) ;
17 System . out . print ( " Enter string 1: " ) ;
18 String str1 = sc . nextLine () ;
19 System . out . print ( " Enter string 2: " ) ;
20 String str2 = sc . nextLine () ;
21

22 if ( areAnagram ( str1 , str2 ) ) {


23 System . out . println ( " The strings are anagrams . " ) ;
24 } else {
25 System . out . println ( " The strings are not anagrams . " ) ;
26 }
27 }
28 }

1
1.3 Example Output
Input: listen, silent
Output: The strings are anagrams.

2. Pangram Program (Java)


2.1 Explanation
A pangram contains every letter of the alphabet. This Java program uses a boolean array
to mark the presence of all alphabets.

2.2 Code
1 // Pangram Check Program in Java
2 import java . util . Scanner ;
3

4 public class PangramCheck {


5 public static boolean isPangram ( String str ) {
6 boolean [] alphabet = new boolean [26];
7 str = str . toLowerCase () ;
8

9 for ( int i = 0; i < str . length () ; i ++) {


10 char ch = str . charAt ( i ) ;
11 if ( ch >= ’a ’ && ch <= ’z ’) {
12 alphabet [ ch - ’a ’] = true ;
13 }
14 }
15

16 for ( boolean present : alphabet ) {


17 if (! present ) return false ;
18 }
19 return true ;
20 }
21

22 public static void main ( String [] args ) {


23 Scanner sc = new Scanner ( System . in ) ;
24 System . out . print ( " Enter a string : " ) ;
25 String str = sc . nextLine () ;
26

27 if ( isPangram ( str ) ) {
28 System . out . println ( " The string is a pangram . " ) ;
29 } else {
30 System . out . println ( " The string is not a pangram . " ) ;
31 }
32 }
33 }

2
2.3 Example Output
Input: The quick brown fox jumps over the lazy dog
Output: The string is a pangram.

3. Palindrome Program (Java)


3.1 Explanation
A palindrome reads the same from both ends. This Java program compares characters
from start and end to check.

3.2 Code
1 // Palindrome Check Program in Java
2 import java . util . Scanner ;
3

4 public class PalindromeCheck {


5 public static boolean isPalindrome ( String str ) {
6 int start = 0 , end = str . length () - 1;
7 while ( start < end ) {
8 if ( str . charAt ( start ) != str . charAt ( end ) ) return
false ;
9 start ++;
10 end - -;
11 }
12 return true ;
13 }
14

15 public static void main ( String [] args ) {


16 Scanner sc = new Scanner ( System . in ) ;
17 System . out . print ( " Enter a string : " ) ;
18 String str = sc . nextLine () ;
19

20 if ( isPalindrome ( str ) ) {
21 System . out . println ( " The string is a palindrome . " ) ;
22 } else {
23 System . out . println ( " The string is not a palindrome . " )
;
24 }
25 }
26 }

3.3 Example Output


Input: madam
Output: The string is a palindrome.

Common questions

Powered by AI

Using 'toCharArray' and 'Arrays.sort' in the anagram checking program is effective for straightforward scenarios due to its clear logic: by converting strings to character arrays and sorting, the program can easily compare the two arrays. However, this approach requires additional memory for the char arrays and has a time complexity of O(n log n), which can be suboptimal for very large strings. A frequency count method using hashmaps could potentially offer better efficiency, particularly for varying character sets, by operating in linear time complexity without the overhead of sorting .

In the Java palindrome verification program, characters from the start and the end of the string are compared using two indices: 'start' and 'end'. Initially set to the first and last positions of the string, these indices are incremented and decremented respectively after each comparison. The program checks if the characters at these positions are the same; if they differ at any point, the string is not a palindrome. This process continues until the 'start' index is greater than or equal to the 'end' index .

Using Scanner for input is straightforward and user-friendly, allowing for easy reading of string inputs from the console in an interactive setting. However, Scanner can be less efficient in terms of performance due to its heavy reliance on I/O operations and parsing capabilities. Alternatives like BufferedReader can be more efficient due to its buffering capabilities, which minimize the number of I/O operations. In situations where performance is critical, using BufferedReader in conjunction with InputStreamReader could be explored .

The Java pangram checking program ensures all letters of the alphabet are present by using a boolean array of size 26, where each index corresponds to a letter of the alphabet. Firstly, the program converts the input string to lowercase to handle case insensitivity. It then iterates through each character of the string, marking the corresponding index in the boolean array as true for each letter encountered. Finally, it checks if all entries in the boolean array are true, indicating the presence of every letter .

The logic of comparing start and end characters in a palindrome program can be applied to other data structures like arrays and lists. For instance, in a list of integers, one can define a 'palindrome' as the list being symmetric. By using two indices at the start and end of the list, and incrementing and decrementing these indices respectively while ensuring the elements match, one can determine if a list is a 'palindrome'. This concept could further be expanded to validate symmetry in matrix rows or arrays in two-dimensional arrays .

The key steps in the Java anagram checking program involve first verifying if the lengths of the two strings are equal, as anagrams must be of the same length. After confirming the lengths, the next step is to convert each string into a character array and sort these arrays. Finally, the sorted character arrays are compared using the 'Arrays.equals' method to determine if they are identical, which would mean the strings are anagrams .

Input normalization via case conversion in the pangram checking program ensures that the check for the presence of all alphabets is case insensitive. By converting the entire input string to lowercase, the program allows for a simple, uniform check of each letter against a lowercase alphabet index, avoiding discrepancies between upper and lower case that could lead to false negatives in pangram detection .

A potential enhancement to the pangram checking program could involve using bit masking instead of a boolean array to track the presence of alphabets. By representing each letter as a bit in an integer, the program can perform bitwise OR operations to mark the presence of letters, reducing memory usage compared to a boolean array. Additionally, by checking if the bitmask equals (1 << 26) - 1 at the end of the string traversal—equivalent to all letters being present—the efficiency and simplicity of the code could be improved .

The main method integrates user interaction with logic processing by first using Scanner to prompt the user for input and then reading the string. It immediately passes this string to the 'isPalindrome' method to process and determine if the string is a palindrome. Depending on the boolean result returned, it provides feedback to the user by printing an appropriate message to the console, thus seamlessly integrating user inputs with back-end logic processing .

Using sorting to detect anagrams has the advantage of simplicity and clarity. By sorting both strings and comparing them, it becomes straightforward to determine if they contain the same letters in the same frequency. However, this method can be less efficient for longer strings, as sorting has a time complexity of O(n log n). In contrast, counting the frequency of each character and comparing the counts can achieve an O(n) time complexity, providing better performance for large inputs. The sorting method also does not handle characters beyond the standard ASCII efficiently, unless extended to support unicode sorting .

You might also like