In Java, the chars() method of the StringBuffer class converts the characters in the StringBuffer to an IntStream. This method is useful for iterating over, processing, or filtering characters in a StringBuffer.
Example 1: Here, we will iterate over characters by using the chars() method and it will print the Unicode code points of each character in a StringBuffer object.
// Java Program to demonstrate chars() method with a StringBuffer
import java.util.stream.*;
public class Chars {
public static void main(String[] args) {
// Create a StringBuffer object
StringBuffer b = new StringBuffer("Java");
// Use chars() method to get an IntStream and
// print each character's Unicode
b.chars()
.forEach(codePoint -> System.out.println("" + codePoint));
}
}
Output
74 97 118 97
Syntax of chars() Method
IntStream chars()
- Parameter: None
- Return Type: IntStream: It returns an IntStream representing the Unicode code points of the characters in the StringBuffer.
Example 2: Here, we will use the chars() method to process numeric characters in the StringBuffer.
// Java Program to process numeric characters using chars() method
import java.util.stream.*;
public class Chars {
public static void main(String[] args) {
// Create a StringBuffer object
// with numeric characters
StringBuffer b = new StringBuffer("12345");
// Use chars() to iterate over the
// characters and print them
b.chars()
.forEach(ch -> System.out.print((char) ch + " "));
}
}
Output
1 2 3 4 5
Example 3: Here, we will use the chars() method with a StringBuffer containing both letters and digits.
// Java Program to handle mixed content in a
// StringBuffer using chars() method
import java.util.stream.*;
public class Chars {
public static void main(String[] args) {
// Create a StringBuffer object with
// mixed characters
StringBuffer b = new StringBuffer("swe217ami");
// Use chars() method to print
// Unicode values of each character
b.chars()
.forEach(cp -> System.out.println("" + cp));
}
}
Output
115 119 101 50 49 55 97 109 105