charAt是String的内置方法
charAt方法的源码:
public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; }这个方法就是 取出字符串指定位置的字符。index就是索引值。
index的范围就是0 ~ index.length-1,如果超出这个范围就会抛出越界异常StringIndexOutOfBoundsException。
public class Test { public static void main(String[] args) { String s = "With great power comes great responsibility. This is my gift, my curse."; System.out.println("取出第二个字符:"+s.charAt(1)); }}运行结果: