Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll learn how to generate a sequence of characters from ‘A’ to ‘Z’ in Java. We’ll do this by incrementing ASCII values.

We’ll be generating a sequence of characters using a for loop and IntStream from the Java 8 Stream API.

2. Using a for Loop

We’ll create a list of capital letters from ‘A‘ to ‘Z‘ using a standard for loop:

@Test 
void whenUsingForLoop_thenGenerateCharacters(){
    List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
  
    List<Character> characters = new ArrayList<>();
    for (char character = 'A'; character <= 'Z'; character++) {
        characters.add(character);   
    }
  
    Assertions.assertEquals(alphabets, allCapitalCharacters);
}

Every letter has a unique number in the ASCII system. For example, ‘A’ is represented as 65, ‘B’ as 66, and ‘Z’ as 90.

In the example above, we first increment the number of each letter in a for loop. Then, we convert it to the corresponding ASCII letter.

Finally, by using the assertEquals() method of the Assertions class, we check if the generated list matches the expected list of all capital characters.

3. Using Java 8 IntStream

Using Java 8 IntStream, we can generate a sequence of all capital letters from ‘A’ to ‘Z’:

@Test
void whenUsingStreams_thenGenerateCharacters() {
    List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');

    List<Character> characters = IntStream.rangeClosed('A', 'Z')
      .mapToObj(c -> (char) c)
      .collect(Collectors.toList());
    Assertions.assertEquals(characters, allCapitalCharacters);
}

In the above example, employing IntStream from Java 8, we generate characters ranging from ‘A’ to ‘Z’ with ASCII values spanning 65 to 90.

Initially, we map these values to characters and then subsequently collect them into a list.

To conclude, we employ the assertEquals() method from the Assertions class to verify if the generated list aligns with the expected list of all capital letters.

4. Conclusion

In this short article, we explored how we can use the Stream API and for loop to increment the ASCII values of the characters and print their corresponding values.

As usual, the source code for the examples is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.