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.

       


电子产品 排行榜


Gurmandise 哆啦A梦 铜锣烧 手机手环

IT電腦補習 java補習 為大家配對電腦補習,IT freelance, 私人老師, PHP補習,CSS補習,XML,Java補習,MySQL補習,graphic design補習,中小學ICT補習,一對一私人補習和Freelance自由工作配對。
立刻註冊及報名電腦補習課程吧!

facebook 查詢:
24 hours enquiry facebook channel :
https://www.facebook.com/itteacheritfreelance/?ref=aymt_homepage_panel

Be the first to comment

Leave a Reply

Your email address will not be published.


*