Exercise:
Write a Java Program to iterate through each character of the string.
1.Iterate using for loop
Click Here to View the Solution!
public class Iterate {
public static void main(String[] args) {
String name = "CodeOfCode";
System.out.println("Characters in " + name + " are:");
// iterating through each element
for(int i = 0; i<name.length(); i++) {
char a = name.charAt(i);
System.out.print(a + ", ");
}
}
}
Click Here to View the Output!
Characters in CodeOfCode are: C, o, d, e, O, f, C, o, d, e,
Click Here to View the Explanation!
- In this program, firstly a variable named
name
has been initialized. - Then a
for loop
is executed which runs till the end ofname
variable’s length. - Inside this loop, every character in
name
is fetched throughcharAt()
method. - The fetched character is then printed on the screen with a comma next to it.
2.Iterate using for-each loop
Click Here to View the Solution!
public class Iterate {
public static void main(String[] args) {
String name = "CodeOfCode";
System.out.println("Characters in string \"" + name + "\":");
// using for-each loop to iterate through each element
for(char ch : name.toCharArray()) {
System.out.print(ch + ", ");
}
}
}
Click Here to View the Output!
Characters in string "CodeOfCode": C, o, d, e, O, f, C, o, d, e,
Click Here to View the Explanation!
- In this program, firstly a variable named
name
has been initialized. - Next, a
for-each loop
executes which first converts the variablename
into a character array usingtoCharArray()
method. - Thus each character from
name
is retrieved and printed on the screen with a comma following it. - This process continues till all the characters in
name
have been traversed.