As far as correctness goes, this only works for Unicode Code Points in the Basic Multilingual Plane (those that can be represented by a single two byte char in Java). If you have characters outside of that, you will get two chars with an individual surrogate pair in each of them to represent a single real world character.

I use a for loop to iterate the string and use charAt() to get each character to examine it. Since the String is implemented with an array, the charAt() method is a constant time operation.

String s = "...stuff...";

for (int i = 0; i < s.length(); i++){
    char c = s.charAt(i);        
    //Process char
}

That's what I would do. It seems the easiest to me.

Answer from jjnguy on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterate-over-the-characters-of-a-string-in-java
Iterate Over the Characters of a String in Java - GeeksforGeeks
July 23, 2025 - In this approach, we convert string to a character array using String.toCharArray() method. Then iterate the character array using for loop or for-each loop. ... // Java Program to Iterate Over the Characters of a String // Using String.toC...
Discussions

Beginner Help: Iterate for each character in a string
You can iterate over an array easily… now strings are array of characters. And String has inbuilt function called toCharArray() which converts the strings to character array. for(Char c: str.toCharArray()){ …logic.. } More on reddit.com
🌐 r/javahelp
10
6
November 27, 2021
java - Repeating a string using a for loop - Stack Overflow
I'm fairly new to programming. I'm trying to repeat the word in a given string the amount of times by a given number in the same string. I have decided to loop through the string and add each char ... More on stackoverflow.com
🌐 stackoverflow.com
In Java, is it possible to check string startsWith with a List? - Oracle Forums
Hi All, for example i am having a string called "ONE". I'm having a list which has "ONE", "TWO", "THREE", "FOUR" etc., Now i want to check whether &... More on forums.oracle.com
🌐 forums.oracle.com
October 29, 2007
returning a String in an if else loop in Java
Which message are you trying to give it? It looks like it's skipping the if statements since, presumably, none of the conditions apply. If you have a default message, either set it in the initialize statement on line 3 String message = "Attack succeeded."; or set it in an else statement after the last 'else if' else { message = "Attack succeeded."; } More on reddit.com
🌐 r/learnprogramming
9
1
July 12, 2022
🌐
Trinket
books.trinket.io › thinkjava2 › chapter6.html
Loops and Strings | Think Java | Trinket
As an exercise, try writing two nested for loops (in main) that invoke timeString and display all possible times over a 24-hour period. Be sure to skim through the documentation for String. Knowing what other methods are there will help you avoid reinventing the wheel. The easiest way to find documentation for Java classes is to do a web search for “Java” and the name of the class.
🌐
Baeldung
baeldung.com › home › java › java string › how to iterate over the string characters in java
How to Iterate Over the String Characters in Java | Baeldung
May 11, 2024 - For most cases, the simple for loop or the enhanced for loop is the most straightforward and efficient way to iterate over characters in a string. They have a low space complexity and a time complexity of O(n), which is the best we can achieve for this task. We can use Java 8 Streams when we need to perform complex operations on the characters or if we want to take advantage of the functional programming capabilities it provides.
🌐
Vultr Docs
docs.vultr.com › java › examples › iterate-through-each-characters-of-the-string
Java Program to Iterate through each characters of the string | Vultr Docs
December 16, 2024 - Gain the skills to implement these methods in your Java applications to handle character-specific logic seamlessly. Understand that the String.charAt(int index) method allows you to retrieve a character at a specific index. Use this method inside a standard for loop to access each character sequentially.
🌐
Reddit
reddit.com › r/javahelp › beginner help: iterate for each character in a string
r/javahelp on Reddit: Beginner Help: Iterate for each character in a string
November 27, 2021 -

I am struggling to wrap my head around the for each loop and how it can be applied through iteration of a defined string.

I need to step through the string character by character and for each character use a char variable to hold the value of that character. The issue is that I am not sure how to do this.

Please can someone explain this in layman's terms or provide an example of how I can achieve this?

Top answer
1 of 4
2
You can iterate over an array easily… now strings are array of characters. And String has inbuilt function called toCharArray() which converts the strings to character array. for(Char c: str.toCharArray()){ …logic.. }
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
W3Schools
w3schools.com › java › java_for_loop.asp
Java For Loop
Strings Concatenation Numbers and Strings Special Characters Code Challenge Java Math Java Booleans · Booleans Real-Life Example Code Challenge Java If...Else · if else else if Short Hand If...Else Nested If Logical Operators Real-Life Examples Code Challenge Java Switch ... For Loop Nested Loops For-Each Loop Real-Life Examples Code Challenge Java Break/Continue Java Arrays
Find elsewhere
🌐
Sololearn
sololearn.com › en › Discuss › 1829030 › is-it-possible-to-create-a-loop-in-java-using-a-string-not-an-integerint-and-how-it-it-done
Is it possible to create a loop in java using a String not an Integer(int) and how it it done? | Sololearn: Learn to code for FREE!
June 4, 2019 - As far as for loops go you must define an integer to indicate how many times the process is.supposed to repeat ... Yes you can. You can create an String array for example: String[] names = {"Name1","Name2","Name3"}; for(String n: names) ...
🌐
Runestone Academy
runestone.academy › ns › books › published › csawesome › Unit4-Iteration › topic-4-3-strings-loops.html
4.3. Loops and Strings — CSAwesome v1
The following code loops through a string replacing all 1’s with l’s. Trace through the code below with a partner and explain how it works on the given message. You can run it line by line in the Java visualizer. Note that indexOf here can work repeatedly to find the next occurrence of a 1 because they are replaced as soon as they are found. Change the code to add code for ...
🌐
Sentry
sentry.io › sentry answers › java › java for-each loops
Java for-each loops | Sentry
December 15, 2023 - The equivalent for loop looks like this: for (Iterator<String> productIterator = products.iterator(); productIterator.hasNext(); ) { String product = productIterator.next(); System.out.println(product); } In the for loop expression, we create ...
🌐
Coderanch
coderanch.com › t › 405709 › java › Colon-loop
Colon : in for{} loop? (Beginning Java forum at Coderanch)
December 24, 2006 - What I mean by that is that in Marc's code, the for loop is declared as:Within that loop, s is already known to be a String, and can be treated as such. Now lets look at some (deliberately) ugly code to show how this can be beneficial:In line 5 I deliberately decided not to use generics. (This is noticeable when you try and compile this code - it will complain about unsafe operations.) If I had used generics, then a lot of what I am trying to demonstrate just couldn't be demonstrated - the big aim of Java 5 was making life easier for the programmer after all.
🌐
Opensource.com
opensource.com › article › 23 › 1 › java-for-loops
A guide to Java for loops | Opensource.com
What you do with the Stream depends on what you want to achieve. Stream methods are well documented in Java docs, but to mimic the basic example of the for loop it makes sense to use the forEach or forEachOrdered method, which iterates over each element in the Stream.
🌐
Medium
donraab.medium.com › what-if-java-had-no-for-85302ab7e484
What if Java had no for? | Medium
January 17, 2024 - For loops are used to do things until a condition is met, or infinitely if no condition is specified. There is a for statement in Java that is well structured and extremely useful for executing a block of code a number of times.
🌐
CodeGym
codegym.cc › java blog › core java › java for loop
For loop Java
Attention: the for-each loop can be applied to arrays and any classes that implement the java.lang.Iterable interface. Let’s solve the same problem with greetings friends, ignoring strangers ("Stranger") but this time use for-each loop. public class ForEachExample { public static void main(String[] args) { String[] names = {"Mike", "Dustin", "Stranger", "Lucas", "Will"}; // for each loop, Java code for (String name : names) { if (name.equals("Stranger")) { System.out.println("I don't chat with strangers"); continue; } System.out.println("hello, " + name); } } } To reinforce what you learned, we suggest you watch a video lesson from our Java Course
Published   July 23, 2024
🌐
Programiz
programiz.com › java-programming › for-loop
Java for Loop (With Examples)
In this tutorial, we will learn how to use for loop in Java with the help of examples and we will also learn about the working of Loop in computer programming.
🌐
Oracle
forums.oracle.com › ords › apexds › post › in-java-is-it-possible-to-check-string-startswith-with-a-li-2125
In Java, is it possible to check string startsWith with a List? - Oracle Forums
October 29, 2007 - Hi All, for example i am having a string called "ONE". I'm having a list which has "ONE", "TWO", "THREE", "FOUR" etc., Now i want to check whether &...
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 226257 › stop-a-loop-at-input-of-character
java - Stop a Loop at input of Character | DaniWeb
DataAnalyzer { public static void main(String[] args) { Scanner in = new Scanner(System.in); DataSet data = new DataSet(); boolean done = false; while (!done) { System.out.print("Enter value, Q to quit: "); String input = in.next(); if (input.equalsIgnoreCase("Q")) done = true; else { double x = Double.parseDouble(input); data.add(x); } } ... A simple way to meet the requirement without manual character checks is to let Scanner validate tokens for you. Keep consuming values while the next token is a double; the moment the user types a letter (or anything non‑numeric), the loop ends.
🌐
Edureka
edureka.co › blog › string-array-in-java
Java String Array | String Array in Java with Examples | Edureka
July 5, 2024 - Iteration over a string array is done by using java for loop, or java for each loop.
🌐
O'Reilly
oreilly.com › library › view › java-cookbook › 0596001703 › ch03s05.html
Processing a String One Character at a Time - Java Cookbook [Book]
June 21, 2001 - To process all the characters in a String, one after another, use a for loop ranging from zero to String.length( )-1. Here we process all the characters in a String: // StrCharAt.java String a = "A quick bronze fox leapt a lazy bovine"; for ...
Author   Ian F. Darwin
Published   2001
Pages   888