Monday 30 December 2019

Convert string to CharSequence


When you see the definition of String class, it implements CharSequence interface.

public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
         .....
         .....
}

Since String class implements CharSequence interface, any string is a char sequence too.

Example
String str = "Hello World";
CharSequence cs = str;

App.java
package com.sample.app;

public class App {

	public static void main(String args[]) {
		String str = "Hello World";
		CharSequence cs = str;

		for (int i = 0; i < cs.length(); i++) {
			System.out.println(cs.charAt(i));
		}
	}

}


Run App.java, you can see below messages in console.
H
e
l
l
o
 
W
o
r
l
d

You may like

No comments:

Post a Comment