Java program to iterate through each characters of the string.
www.igiftidea.com
To iterate through each character of a string in Java, you can use a for
loop with the charAt()
method of the String
class. Here's an example:
String str = "Hello, World!"; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); System.out.print(c + " "); }
In the above example, we define a String
variable str
with the value "Hello, World!". We then use a for
loop to iterate through each character of the string.
Inside the loop, we use the charAt()
method to get the character at the current index i
. We store the character in a char
variable c
. Finally, we print the character to the console using the System.out.print()
method.
After running the above code, the output would be:
H e l l o , W o r l d !
This program iterates through each character in the String
and prints it to the console. Note that the charAt()
method starts at index 0 and goes up to length() - 1
.