Java中的数组getChar()方法
java.lang.reflect.Array.getChar() 是Java中的内置方法,用于将位于指定数组中给定索引处的元素作为字符返回。 语法
Array.getChar(Object []array,int index)
参数:
- array : 要返回其索引的对象数组。
- index : 所给定数组中的特定索引。 返回给定数组中索引处的元素。
返回类型: 此方法返回数组的元素。
注意: 不需要进行类型转换,因为返回类型是char类型
异常: 此方法引发以下异常
- NullPointerException – 当数组为null时。
- IllegalArgumentException – 当给定的对象数组不是数组时。
- ArrayIndexOutOfBoundsException – 如果给定索引不在数组的大小范围内。
以下程序说明Array类的getChar()方法:
程序1 :
// Java code to demonstrate getChar() method of Array class
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining an byte array
char a[] = {'G','f','G'};
// Traversing the array
for(int i = 0;i<3;i++){
// Array.getChar() method
char x = Array.getChar(a, i);
// Printing the values
System.out.print(x);
}
}
}
输出:
GfG
程序2 :
// Java code to demonstrate getChar() method in Array
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining an char array
char a[] = {'G','f','G'};
try {
// invalid index
char x = Array.getChar(a, 6);
System.out.println(x);
} catch (Exception e) {
// throws Exception
System.out.println("Exception : " + e);
}
}
}
输出:
Exception : java.lang.ArrayIndexOutOfBoundsException
程序3 :
// Java code to demonstrate getChar() method in Array
import java.lang.reflect.Array;
public class GfG {
// main method
public static void main(String[] args) {
// Declaring and defining an char array to null
char a[] = null;
try {
// null Object array
char x = Array.getChar(a, 6);
System.out.println(x);
} catch (Exception e) {
// throws Exception
System.out.println("Exception : " + e);
}
}
}
输出:
Exception : java.lang.NullPointerException
程序4 :
// Java代码演示数组的getChar()方法
import java.lang.reflect.Array;
public class GfG {
// 主方法
public static void main(String[] args) {
// 声明并定义一个char变量
char a = 'a';
try {
// 非法参数
char x = Array.getChar(a, 6);
System.out.println(x);
} catch (Exception e) {
// 抛出异常
System.out.println("Exception : " + e);
}
}
}
输出:
Exception : java.lang.IllegalArgumentException: Argument is not an array
极客教程