How about:

    String input = "TestInput";

    StringBuilder b = new StringBuilder();
    b.append(input.charAt(0));
    for (int i = 1; i < input.length(); i++) {
        b.append("*").append(input.charAt(i));
    }
    System.out.println(b);
}

gives:

T*e*s*t*I*n*p*u*t

Is this what you wanted?

Edit: Pshemo's suggestion - use StringJoiner (Java 8 solution)

StringJoiner sj = new StringJoiner("*");
        for (int i = 0; i < input.length(); i++) {
            sj.add(input.substring(i, i + 1));
        }
        System.out.println(sj.toString());

And no StringBuilder version:

  String input="TestInput";
    String y = "";
    for (int i = 0; i < input.length(); i++) {
        y += "*" + input.charAt(i);
    }

And to your knowlage - using string concatenation is discouraged. It is better to use StringBuilder or StringJoiner

Answer from Antoniossss on Stack Overflow
Discussions

beginner here, how do i create a string by adding up chars?
Use StringBuilder and append one character at a time as you read them. More on reddit.com
🌐 r/javahelp
13
3
September 10, 2022
How to repeatedly add characters to a String Java - Stack Overflow
For homework, I got a question that wants me to print the characters of a string in a staircase fashion. //so if String str = "Compute", I should end up with C o m p u t e Thi... More on stackoverflow.com
🌐 stackoverflow.com
Concatenating a string in Java within a loop
The string s keeps getting longer, so it needs to copy larger and larger strings (really arrays of bytes). That's why it's O(n) and why you'd normally use a StringBuilder here. More on reddit.com
🌐 r/learnjava
27
3
January 10, 2022
foreach - Looping through a list to add characters to a list of Strings in Java - Stack Overflow
I'm trying to create a method that returns a linked list of Strings. There is a tree, and each node in the tree stores a character. The method is supposed to find all possible paths through the t... More on stackoverflow.com
🌐 stackoverflow.com
November 15, 2012
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-add-characters-to-a-string
Java Program to Add Characters to a String - GeeksforGeeks
July 23, 2025 - Methods: This can be done using multiple methods of which frequently used methods are listed below as follows: ... Example: One can add character at the start of String using the '+' operator.
🌐
Reddit
reddit.com › r/javahelp › beginner here, how do i create a string by adding up chars?
beginner here, how do i create a string by adding up chars? : r/javahelp
September 10, 2022 - Sum of chars is not a string https://stackoverflow.com/questions/8688668/in-java-is-the-result-of-the-addition-of-two-chars-an-int-or-a-char ... You might try using an array instead of 11 separate variables-- I'm guessing you missed a 'char' on one of them or something ... There is a better way you could do this is by declaring a global string that would be your result and then use a for loop that goes from 1 to 10 and on each iteration you append the inputed character to the global variable of type string that you defined instead of typing the same instruction 11 times.
🌐
GeeksforGeeks
geeksforgeeks.org › java › insert-a-string-into-another-string-in-java
Insert a String into another String in Java - GeeksforGeeks
July 11, 2025 - Copy the remaining characters of the first string into the new String · Return/Print the new String Below is the implementation of the above approach: Program: ... // Java program to insert a string into another string // without using any pre-defined method import java.lang.*; class GFG { // Function to insert string public static String insertString( String originalString, String stringToBeInserted, int index) { // Create a new string String newString = new String(); for (int i = 0; i < originalString.length(); i++) { // Insert the original string character // into the new string newString
🌐
Runestone Academy
runestone.academy › ns › books › published › csawesome › Unit4-Iteration › topic-4-3-strings-loops.html
4.3. Loops and Strings — CSAwesome v1
Here is a for loop that creates ... in characters from the string s. You can also run this code in this Java visualizer link or by clicking on the Code Lens button below. ... What would happen if you started the loop at 1 instead? What would happen if you used <= instead of <? What would happen if you changed the order in which you added the ithLetter ...
🌐
Medium
medium.com › @AlexanderObregon › breaking-a-word-into-characters-using-java-strings-751bd923be63
Breaking a Word into Characters Using Java Strings | Medium
July 21, 2025 - Learn how Java strings store characters, how charAt() works, and how to loop through strings one letter at a time for formatting, counting, and more.
Find elsewhere
🌐
Reddit
reddit.com › r/learnjava › concatenating a string in java within a loop
r/learnjava on Reddit: Concatenating a string in Java within a loop
January 10, 2022 -

Hi All,

I am trying to understand the reason why the following code executes in quadratic time

String s = "";
for (int i = 0; i < n; ++i) {
    s = s + n;
}

I understand that strings are immutable and therefore each execution of s = s + n creates a new instance of string but I am still not sure what the issue is that makes it quadratic. So, I understand there will be n string creations, but is it specifically the concatenation operator? because we are saying "take all contents of s, and add n to the end" and since we can not mutate s, copying all elements of s + appending into a new string is required?

Top answer
1 of 4
3
The string s keeps getting longer, so it needs to copy larger and larger strings (really arrays of bytes). That's why it's O(n) and why you'd normally use a StringBuilder here.
2 of 4
1
Okay so I looked more into it and first of all I want to say don't worry too much about such a problem because its not typical or as "black and white" as other time complexity examples, such as nested for loops. Usually, we consider a statement or a block of statements that don't involve a for loop as constant in execution time. This includes creating objects like Arrays or Strings for example. O(1): String s1 = new String("hello"); Now consider this statement in a for loop executing n times. The time complexity will be O(n). The issue with concatenation however, is it is similar to having this statement in a for loop, but everytime you are creating a string of an increased size from before. This is because strings are immutable. For example, if we're appending the string to itself with each iteration, if you had a string "hello", next iteration, you will create a new string in memory called "hellohello" and so on. This complicates things because instead of the execution time of creating a string being constant, you are creating increased length strings with each iteration of n. What others are saying is assuming the time complexity of creating a string to be O(x), where x is the number of characters/length in said string. So if you are increasing it by x n times, your time complexity is: O(x + 2x + 3x +.... nx) Now this line of reasoning would be valid if the creation of string objects truly scaled up in this manner. It's not unlikely however that strings of a decent range in length can be created in what can be assumed to be a constant time O(1). On the other hand, at a certain point, the length of the string will appreciably affect how long it takes to create it. You are also adding more and more work for the garbage collector to perform, so it's not as black and white as O(n) or O(n²), realistically speaking. Assuming you can go with the O(x) convention for creating a string length x, then as said before time complexity is O(x+2x...nx) Let's look at the arithmetic series inside the O. This is x + 2x +... nx. Using some math magic this arithmetic series is actually equal to x multiplied by n(n+1)/2. So the time complexity is actually, since x is constant and can be taken out of O: O( n[n+1]/2 ) Now to make this even more complicated, you can take the limit of the term n(n+1)/2 as n increases towards infinity. This is called the upper bound of the term and serves to approximate it for large values of n. This is the term n(n+1)/2 converges to as n increases. If you have a math background, you know you can leave the constant out of the denominator and keep the higher power terms of the products in the numerator. Resulting in n². So the upper bound of the time complexity is O(n²), but as I said before, this took a lot of stretching and assumptions and is honestly too convoluted to be helpful or insightful in my view. Long story short, don't use string concatenations inside a loop, it's bad practice
🌐
Baeldung
baeldung.com › home › java › java string › generating a java string of n repeated characters
Generating a Java String of N Repeated Characters | Baeldung
January 8, 2024 - Let’s start with the StringBuilder class. We’ll iterate through a for loop N times appending the repeated character:
🌐
TutorialsPoint
tutorialspoint.com › article › java-program-to-add-characters-to-a-string
Java Program to Add Characters to a String
May 30, 2025 - Let's see an example of adding a character to a string using the '+' operator. public class Main { public static void main(String[] args) { String st = "Tutorial"; char chartoadd = 's'; st = st + chartoadd; // performing concatenation System.out.println(st); } } ... Strings are immutable in Java, but to perform modifications of strings, Java provides two inbuilt classes, StringBuilder and StringBuffer. Both have insert() and append() methods that can be used to add characters to a string.
🌐
Trinket
books.trinket.io › thinkjava2 › chapter6.html
Loops and Strings | Think Java | Trinket
The following loop iterates the characters in fruit and displays them, one on each line: Because length is a method, you have to invoke it with parentheses (there are no arguments). When i is equal to the length of the string, the condition becomes false and the loop terminates.
🌐
Techie Delight
techiedelight.com › home › java › iterate over characters of a string in java
Iterate over characters of a String in Java | Techie Delight
1 week ago - We can also convert a string to char[] using String.toCharArray() method and then iterate over the character array using enhanced for-loop (for-each loop) as shown below: ... We can also use the StringCharacterIterator class that implements ...
🌐
Wordpress
algocoding.wordpress.com › 2013 › 03 › 15 › java-concatenating-strings-efficiently-in-a-loop
Java – Concatenating strings efficiently in a loop | Programming, algorithms and data structures
April 14, 2015 - Appending “2” takes at least 90 000 steps because the original string first has to be copied. Compare this to a char array A filled with ‘2’ from A[0] to A[89 999]. Appending a ‘2’ is simply done by assigning A[90 000]=2 which requires only 1 step. The difference becomes apparent when we repeat this in a loop.
🌐
Arrowhitech
blog.arrowhitech.com › add-character-to-string-java-how-to-implement-it-in-java-2
Add character to string java: How to implement it in Java – Blogs | AHT Tech | Digital Commerce Experience Company
But in Java, a string is an object ... The java String class is used to create a string object. ... There are multiple ways to add character to String. You can add character at start of String using + operator. ... You can add character at start of String using + operator. For ...
🌐
codippa
codippa.com › home › iterate through string in java
Java iterate through string characters in 7 ways
January 16, 2025 - This string can be converted to a character array with toCharArray() and iterated using a for loop as shown earlier. Example, String s = "codippa"; // split on empty string String[] arr = s.split(""); // string array has only 1 string char[] ...
🌐
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.