Increment Character in Java

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.

       

\"IT電腦補習
立刻註冊及報名電腦補習課程吧!

Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses

Email:
public1989two@gmail.com






www.itsec.hk
www.itsec.vip
www.itseceu.uk

Be the first to comment

Leave a Reply

Your email address will not be published.


*