String dna[] = {"ATCTA"};
 int i = 0;
 dna[i] = dna[i].replace('T', 'C');
 System.out.println(dna[i]);

This works as expected. Double check your code if you follow a similiar pattern.


You may have expected, that dna[i].replace('T', 'C'); changes the content of the cell dna[i] directly. This is not the case, the String will not be changed, replace will return a new String where the char has been replaced. It's necessary to assign the result of the replace operation to a variable.


To answer your last comment:

Strings are immutable - you can't change a single char inside a String object. All operations on Strings (substring, replace, '+', ...) always create new Strings.

A way to make more than one replace is like this:

dna[i] = dna[i].replace('T', 'C').replace('A', 'S');
Answer from Andreas Dolk on Stack Overflow
๐ŸŒ
Learnerslesson
learnerslesson.com โ€บ JAVA โ€บ Java-Replace-Array-Elements.htm
Java - Replace Array Elements
JAVA SPRING SPRINGBOOT HIBERNATE HADOOP HIVE ALGORITHMS PYTHON GO KOTLIN C# RUBY C++ HTML CSS JAVA SCRIPT JQUERY ... Let us say, we have a Array that contains three names, Mohan, John, Paul, Kriti and Salim. And we want to replace the name John with a new name Neal. public class MyApplication { public static void main(String[] args) { String[] arr = {"Mohan", "John", "Paul", "Kriti", "Salim"}; System.out.println("\nBefore replacing the second element\n"); for (String str : arr) { System.out.println(str); } arr[1] = "Neal"; System.out.println("\nAfter replacing the second element\n"); for (String str : arr) { System.out.println(str); } } }
Discussions

java replacing elements of an array - Stack Overflow
The death toll on a and b is a ... reads the next integer (d) and computes the soldiers remaining after the second battle. I have no idea what I need, not even sure what is wrong. ... Is there a problem with replacing elements of this array like this at the end of the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 28, 2018
How do I replace something in an array?
Not sure if I should give the answer directly: To access the variable in array you can use e.g. System.out.println(array[1] ) will print โ€œ1.0โ€ from your example. To replace the value you can just assign the value to the index you want. array[index] = value to assign More on reddit.com
๐ŸŒ r/javahelp
3
1
August 24, 2023
java - Comparing and replacing values in an array - Software Engineering Stack Exchange
I am currently working on a program that replaces the value in an array if the value next to it is the same as the current value. So If the array is [0,0,0,1,0,1,0], when the program runs it'll tur... More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
java - replacing elements of an array change by change - Stack Overflow
I'm trying to do some basics concerning an array of elements, specifically characters. My question is, how do I get the program to print my changes one by one? for example (I do not want my output going from "moon" to "mOOn" in one instance, but from "moon" to "mOon" to "mOOn", like that. Here is my code. import java... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 3
1
Array values are mutable. Here's a quick solution: ```java import java.util.ArrayList; import java.util.List; import java.util.Random; public class ToDORNotTwoD { public static void main(String[] args) { int[][] array = new int[10][10]; List coordinateList = new ArrayList<>(); randomizeMatrix(array); printMatrix(array); manipulateMatrix(array, coordinateList); printCoordinateList(coordinateList); printMatrix(array); } private static void printMatrix(int[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.printf("%3d", matrix[i][j]); } System.out.println(); } System.out.println(); } private static void printCoordinateList(List coordinateList) { System.out.println(coordinateList.toString()); System.out.println(); } private static void randomizeMatrix(int[][] matrix) { Random rand = new Random(); for (int i = 0; i < matrix.length; ++i) { for (int j = 0; j < matrix[0].length; ++j) { matrix[i][j] = rand.nextInt(100); } } } private static void manipulateMatrix(int[][] matrix, List coordinateList) { for (int i = 0; i < matrix.length; ++i) { for (int j = 0; j < matrix[0].length; ++j) { if (matrix[i][j] % 3 == 0) { matrix[i][j] = -1; String pair = "( " + String.valueOf(i) + " , " + String.valueOf(j) + ")"; coordinateList.add(pair); } } } } } ```
2 of 3
0
Another way to phrase an answer, is to point out the fact that the SIZE of an array is immutable, while the values in the array are "mutable" (you can replace the values as you'd like, but putting a string in an array does not suddenly make it mutable.)
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ java collections โ€บ how to replace an element in java arraylist
How to Replace an Element in Java ArrayList
October 11, 2023 - The method returns the same ArrayList element that is just replaced. import java.util.ArrayList; import java.util.List; public class DriverClass { public static void main(String[] args) { List <String> weekDays = new ArrayList<>(); weekDays.add("Monday"); weekDays.add("Monday"); weekDays.add("Wednesday"); weekDays.add("Thursday"); weekDays.add("Friday"); weekDays.add("Saturday"); weekDays.add("Sunday"); System.out.println("Week Days (original) : " + weekDays + "\n"); String replacingText = "Tuesday"; String replacedText = weekDays.set(1, replacingText); System.out.println("Replacing Text: " + replacingText); System.out.println("Replaced Text: " + replacedText + "\n"); System.out.println("Week Days (updated) : " + weekDays); } }
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java list โ€บ replace element at a specific index in a java arraylist
Replace Element at a Specific Index in a Java ArrayList | Baeldung
April 3, 2025 - This position is what we call the index. Then, we can replace the old element with a new one. The most common way to replace an element in Java ArrayList is to use the set (int index, Object element) method.
๐ŸŒ
Java67
java67.com โ€บ 2016 โ€บ 08 โ€บ how-to-replace-element-of-arraylist-in-java.html
How to replace an element of ArrayList in Java? Example | Java67
In this example, I have an ArrayList of String which contains names of some of the most popular and useful books for Java programmers. Our example replaces the 2nd element of the ArrayList by calling the ArrayList.set(1, "Introduction to Algorithms") because the index of the array starts from zero.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ how-to-replace-a-element-in-java-arraylist
How to Replace a Element in Java ArrayList? - GeeksforGeeks
July 23, 2025 - To replace an element in Java ArrayList, set() method of java.util. An ArrayList class can be used. The set() method takes two parameters the indexes of the element that has to be replaced and the new element. The index of an ArrayList is zero-based.
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ java-program-to-replace-each-element-of-array-with-its-next-element
JAVA Program to Replace Each Element of Array with its Next Element
Step 3 ? Replace the current element arr[i] with arr[i+1]. Continue this till arr[lastIndex-1]. And replace the last index element with temp value. Step 4 ? Print the elements of the array. A for loop In Java is a control structure that allows you to repeat a block of code a specific number of times.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 50565199 โ€บ java-replacing-elements-of-an-array
java replacing elements of an array - Stack Overflow
May 28, 2018 - The string is parsed, a and b are replaced the integers in said returned string, then the next iteration of the loop will take the new values for a and b, and integer d. This will continue until the end where a and b are printed to the user. ... Here is the reading in from the file, it works as intended, I put it here for context. tl;dr is results[] is an integer array for the first line.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ replace-every-element-of-the-array-by-its-next-element
Replace every element of the array by its next element - GeeksforGeeks
March 23, 2023 - Given an array arr, the task is to replace each element of the array with the element that appears after it and replace the last element with -1. ... Approach: Traverse the array from 0 to n-2 and update arr[i] = arr[i+1]. In the end, set a[n-1] ...
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ how do i replace something in an array?
r/javahelp on Reddit: How do I replace something in an array?
August 24, 2023 -

I have an array with placeholder terms, call it double[] array = {0,1,2,3,4,5,6,7}. How do I write a statement that replaces one of the terms with a variable of the same type?

for example, replacing index 1 with a variable that is equal to 5.6.

Top answer
1 of 2
4
Not sure if I should give the answer directly: To access the variable in array you can use e.g. System.out.println(array[1] ) will print โ€œ1.0โ€ from your example. To replace the value you can just assign the value to the index you want. array[index] = value to assign
2 of 2
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://i.imgur.com/EJ7tqek.png ) 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.
๐ŸŒ
w3resource
w3resource.com โ€บ java-exercises โ€บ array โ€บ java-array-exercise-63.php
Java - Replace each element of the array with its product
May 9, 2025 - public static int[] find_Product_in_array(int[] nums) { int n = nums.length; // Initialize arrays to store left and right products. int[] left_element = new int[n]; int[] right_element = new int[n]; // Calculate left products. left_element[0] = 1; for (int i = 1; i < n; i++) { left_element[i] = nums[i - 1] * left_element[i - 1]; } // Calculate right products. right_element[n - 1] = 1; for (int j = n - 2; j >= 0; j--) { right_element[j] = nums[j + 1] * right_element[j + 1]; } // Calculate the product of every other element. for (int i = 0; i < n; i++) { nums[i] = left_element[i] * right_element
๐ŸŒ
Stack Exchange
softwareengineering.stackexchange.com โ€บ questions โ€บ 421661 โ€บ comparing-and-replacing-values-in-an-array
java - Comparing and replacing values in an array - Software Engineering Stack Exchange
Instead, rewrite your code with for (int x : ar). Since you need to evaluate two adjacent elements, you'll also need a local variable int previous which would remember the previous value from the array.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 33426914
java - replacing elements of an array change by change - Stack Overflow
public static void main(String[] args){ String array = "uuuuuuuupppppppssssssssss"; System.out.println(array); char[] chars = array.toCharArray(): //converted for (int i = 0; i < chars.length; i++) { if (chars[i] == 'p') { System.out.println(array.replace('p', 'P')); } } }
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 536091 โ€บ java โ€บ Remove-replace-array-element
Remove & replace array element (Beginning Java forum at Coderanch)
April 28, 2011 - Instead, use a List (such as ArrayList or LinkedList). That's got a remove(int) method that will do exactly what I think you want - remove the object at that position from the list (moving all the following elements up one), and returning that object. Basically, arrays aren't intended to change ...
Top answer
1 of 5
5

First, I would give slow the same scope as fast - give them both loop scope:

for (int slow = 0, fast = 0; fast < nums.length; ++fast) {

Second, rather than creating a new variable i and iterating backwards, I would write my second loop like this:

for (; slow < nums.length; ++slow) {
    nums[slow] = 0;
}

Instead of creating a new variable int i = fast and iterating backward until it is equal to slow to set the remaining elements of the array to 0, I just start with the variable in slow and iterate until the end of the array is reached. This will work because the outer loop has finished iterating anyway because once fast == nums.length - 1, we exit the outer loop.

Third, put spaces around your mathematical operator(s) to make it easy to read:

if (fast == nums.length - 1) {

Otherwise, I see nothing wrong with your code, you use reasonable variable names, you use braces around your ifs and loops, and you indent your code nicely.

2 of 5
6

It's extraordinarily confusing to have if (fast == nums.length - 1) as a conditional within a loop that continues while fast < nums.count returns true. This is the last part of the loop, and it only executes on the last iteration of the loop... so why is it even in the loop at all?

A couple of comments in our code can help us out. We have two distinct parts:

  1. Shuffling the non-tens to the front.
  2. Zero-ing out the tens.

So let's use comments to mark these in distinct blocks. And, let's move the second part to its own loop.

And while we're at it, let's make the method more generic to replace any number with another given number.

public int[] replaceNum(int[] nums, int eliminationNum, int replaceNum) {
    int nextMoveIndex = 0;

    // shuffle non-elims to the front
    for (int i = 0; i < nums.length; ++i) {
        if (nums[i] != eliminationNum) {
            nums[nextMoveIndex++] = nums[i];
        }
    }

    // zero out the elimination number
    while (nextMoveIndex < nums.length) {
        nums[nextMoveIndex++] = replaceNum;
    }

    return nums;
}
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ java-program-to-replace-element-of-integer-array-with-product-of-other-elements
JAVA Program to Replace Element of Integer Array with Product of Other Elements
December 30, 2022 - Step-2 ? Find the product of all array elements. Step-3 ? Divide the product value with the value of the respective index and replace the result.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 69067445 โ€บ remove-an-element-from-array-and-replace-with-0
java - Remove an element from array and replace with 0? - Stack Overflow
I believe I still don't follow though on how to shift all the other elements. ... Here is an approach, similar to what I described in the comments above. import java.util.Arrays; public class main { // tip: arguments are passed via the field below this editor public static void main(String[] args) { int[] arr = {3, 5, 7, 8, 5, 12, 2}; remove(arr, 5); System.out.println(Arrays.toString(arr)); // [3, 7, 8, 5, 12, 2, 0] } public static void remove(int[] arr, int toRemove) { int idx = -1; // determine first occurrence of toRemove for(int i = 0; i < arr.length; i++) { if(arr[i] == toRemove) { idx = i; break; } } // if not found, return if(idx == -1) return; // shift other elements down for(int i = idx; i < arr.length-1; i++) { arr[i] = arr[i+1]; } // set last element to 0 arr[arr.length-1] = 0; } }