Solution:
Well, in Java, there are a couple of ways to iterate through characters in a string. As per your question, you can use the .charAt() or the .toCharArray() function. These two are the easiest and efficient ways to iterate through chars in a string. Let me give an example by using them in my program.
Using .charAt() function:
public class MyClass{
public static void main (String[] args){
String str = "I am Gavin";
for (int n = 0; n < str.length(); n++){
System.out.print(str.charAt(n));
}
}
}
Using .toCharArray() function:
public class MyClass{
public static void main (String[] args){
String str = "I am Gavin";
char[] chars = str.toCharArray();
for (char ch : chars){
System.out.print(ch);
}
}
}
Above both program will produce the same output
I am Gavin