- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- English Grammar
- School Programming
- Number System
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
StringBuilder setCharAt() in Java with Examples
- StringBuilder Class in Java with Examples
- StringBuffer class in Java
- StringBuilder append() Method in Java With Examples
- StringBuffer append() Method in Java with Examples
- Returning Multiple values in Java
- Arrays in Java
- How to add an element to an Array in Java?
- How to determine length or size of an Array in Java?
- length vs length() in Java
- Split() String method in Java with examples
- Java String trim() method with Example
- Trim (Remove leading and trailing spaces) a string in Java
- Java Program to Count the Number of Lines, Words, Characters, and Paragraphs in a Text File
- Check if a String Contains Only Alphabets in Java Using Lambda Expression
- Remove elements from a List that satisfy given predicate in Java
- Check if a String Contains Only Alphabets in Java using ASCII Values
- Check if a String Contains only Alphabets in Java using Regex
- How to check if string contains only digits in Java
- Check if given string contains all the digits
- Find first non-repeating character of given String
- First non-repeating character using one traversal of string | Set 2
- Missing characters to make a string Pangram
- Check if a string is Pangrammatic Lipogram
- Removing punctuations from a given string
- Spring Boot - Start/Stop a Kafka Listener Dynamically
- Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
- Arrays.sort() in Java with examples
- Difficulty Level : Easy
- Last Updated : 19 Aug, 2019
The setCharAt(int index, char ch) method of StringBuilder class is used to set the character at the position index passed as ch. This method changes the old sequence to represents a new sequence which is identical to old sequence only difference is a new character ch is present at position index. The index argument must be greater than or equal to 0, and less than the length of the String contained by StringBUilder object. Syntax:
Parameters: This method accepts two parameters:
- index – Integer type value which refers to the index of character you want to set.
- ch – Character type value which refers to the new char.
Returns: This method returns nothing. Exception: If the index is negative, greater than length() then IndexOutOfBoundsException.
Below programs illustrate the java.lang.StringBuilder.setCharAt() method: Example 1:
Example 3: When negative index is passed:
References: https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#setCharAt(int, char)
Please Login to comment...
Master Java Programming - Complete Beginner to Advanced
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Replace a character at a specific index in a string?
I'm trying to replace a character at a specific index in a string.
What I'm doing is:
This gives an error. Is there any method to do this?
- 13 I realize this has been answered to death, but it's worth noting that it is never allowed to assign the result of a function call in java. There are no such things as the references of C(?) and C++. – ApproachingDarknessFish Apr 14, 2013 at 0:11
- 1 @ValekHalfHeart in VB, you use parenthesis to access index of an array, that may be the reason why I'm confused when I was starting in Java :D – kazinix Aug 13, 2013 at 2:40
- @ApproachingDarknessFish I am not sure what you mean by it's "never allowed to assign the result of a function call in java". Surely you can do double r = Math.sin(3.14) ? How does it relate to this question? Thanks. – flow2k Oct 8, 2017 at 22:07
- 1 @flow2k Oh jeez, old comment so I can't edit but that's a typo, it should say that "it is never allowed to assign to the result of a function call in Java". I.e. you can write "foo = bar();" but never "bar() = foo;". – ApproachingDarknessFish Oct 8, 2017 at 22:26
- Thanks for the clarification @ApproachingDarknessFish. I think it would be strange to assign something to the result of a function - are there languages that actually permit this? I wonder what the use case would be. – flow2k Oct 15, 2017 at 19:56
9 Answers 9
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
Or you can use a StringBuilder:
- 3 Ah, you mean like the replace method which will not modify the string but will just return a new string? – kazinix Aug 5, 2011 at 6:39
- 1 That's kinda complicated Mr.Petar. Is that the best way you to do it? Ah, I heard of StringBuilder before, does that make any difference? Will it give me an easier method? – kazinix Aug 5, 2011 at 6:41
Turn the String into a char, replace the letter by index, then convert the array back into a String.
- 1 Love this solution. I ended up changing the 3rd line to be myNameChars[index] = character.toCharArray(); for simplification. Nice solution. – Dale Mar 1, 2017 at 21:22
- 6 it looks much better than the other uglier one myName.substring(0,4)+'x'+myName.substring(5); – user924 Nov 4, 2018 at 14:31
- 2 Keep in mind this copies the String twice. It's probably faster to use the String concatenation version instead. – Ariel Nov 11, 2020 at 1:46
String is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.
If you want to manipulate a string, consider StringBuilder or StringBuffer in case you require thread safety.
I agree with Petar Ivanov but it is best if we implement in following way:
- 26 and what makes your solution better? – kazinix May 3, 2012 at 1:43
- it handles unexpected values. Like null strings and out of bounds indexes. – Dominicentek Gaming Jul 13, 2021 at 19:42
As previously answered here, String instances are immutable . StringBuffer and StringBuilder are mutable and suitable for such a purpose whether you need to be thread safe or not.
There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).
You can overwrite a string, as follows:
Note that the string myName occurs on both lines, and on both sides of the second line.
Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.
- 1 I haven't downvoted your answer but I must admit I have a problem with the term "overwrite" (though I think we agree on the concept behind). The object itself remains unchanged. You just make your variable reference another object. By the way it you be interesting to mention that you create at least four String instances in your example. – C.Champagne Oct 20, 2015 at 12:47
First thing I should have noticed is that charAt is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.
You can overwrite on same string like this
where index = the index of char to replacement. index+1 to add rest of your string
this will work
Output : domaxokz
- 1 although i strongly detest this method of being allowed "editability" of other's work on this StackOverFlow site. thoroughly unfair :/ – Diabolus Infernalis Aug 23, 2012 at 16:39
- 2 Syntax error. And even if corrected, say I want to replace the first 'o' with 'x', the second 'o' will be replaced too. – kazinix Sep 7, 2012 at 4:46
- 3 This will replace all character which is same as charAt 4. – Shripad Bhat Aug 8, 2015 at 13:10
- 2 Problem: myName.replace(myName.charAt(5),'x') will give you dxmanxkz , which is probably not what's required. – Dawood ibn Kareem Jan 29, 2017 at 6:35
- It will give you "dxmanokz" as replace only replaces first occurrence, unless it's a regex. Still incorrect for the same reason, though. – konsumer Jul 26, 2021 at 0:27
Not the answer you're looking for? Browse other questions tagged java string replace indexing character or ask your own question .
- The Overflow Blog
- Building an API is half the battle: Q&A with Marco Palladino from Kong
- Developers think AI assistants will be everywhere, but aren’t sure how to...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Is it easier to unclip using a shoe with higher stiffness index?
- What's the real yield on this bond?
- H-Bridge blows the fuses in my house
- What to do when you find out a client went to another designer to change the finished design?
- Theoretical Computer Science vs other Sciences?
- Would a spider familiar be able to press the button on the immovable rod whilst swinging from a rope tied to said rod?
- Why are most US news programs silent about Iran-Saudi deal announced at Beijing on March 10th?
- Is it faster to add an element at the beginning of a list with add-to-list than at the end?
- Opamp with unbalanced rails
- Did mechanical hard drives often malfunction in high elevation places such as Bogota?
- XeLaTex does not show unicode symbol
- Epistemic failure and blaming others
- Is it traversable?
- How did the Virgin Birth of Jesus prove to be a “sign” as prophesied in Is 7:14?
- Is it OK practice to start a car while it's on jackstands?
- What is the concept of hole in semiconductor physics?
- broker cancelled life insurance policy without authorization
- Equivalent Russian for some idiomatic English phrases
- split/reference big file by offset reference
- Passing 10A through a nichrome wire (2.3 ohms) with 4.2V LiPo battery source
- Novel about an Indiana Jones type character rescuing mummies from Mexican banditos
- Movie where a man is abducted by beings believed to be aliens and finds out they were from the future
- Mechanic sent me this image and said my brake rotors should be replaced. Does this seem right?
- Is "throw an ape" an expression?
- How do I replace character from string at...
How do I replace character from string at specific indexes
I need to replace character from string at specific index.
This is how I am trying to do it:
This gives an error. Is there any method to do this?
Your comment on this question:
2 answers to this question., your answer.
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz" ; String newName = myName . substring ( 0 , 4 )+ 'x' + myName . substring ( 5 );
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder ( "domanokz" ); myName . setCharAt ( 4 , 'x' );
System . out . println ( myName );
- ask related question
Your comment on this answer:
You could turn the String into a char , replace the letter by index, then convert the array back into a String.
Hope this helps!
Related Questions In Java
How do i convert from int to string.
Normal ways would be Integer.toString(i) or String.valueOf(i). The concatenation will work, ... READ MORE
Given a string: s = "Test abc test ... READ MORE
How can I split the String with any whitespace character as delimiter?
String string = "Today's weather"; String arrayOfString = ... READ MORE
How can I do url string decoding in java
We can use URLDecoder: URLDecoder.decode( url, "UTF-8" ); READ MORE
What is the use of toString method in Java and how can I use it ?
Whenever you require to explore the constructor ... READ MORE
What is the 'instanceof' operator used for in Java?
It's an operator that returns true if ... READ MORE
String mapping without Case-Sensitivity
Yes, contains is case sensitive. You can ... READ MORE
Check if a String is numeric in Java
Java 8 Lambda Expression is used: String someString ... READ MORE
How do I create a Java string from the contents of a file?
If you're looking for an alternative that ... READ MORE
How do I read and convert an InputStream object to string type?
You can also use Java Standard Library ... READ MORE
- All categories
Join the world's most active Tech Community!
Welcome back to the world's most active tech community.
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Subscribe to our Newsletter, and get personalized recommendations.
Already have an account? Sign in .
Java string methods.
- Send your Feedback to [email protected]
Help Others, Please Share
Learn Latest Tutorials
Python Design Patterns
B.Tech / MCA
JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] Duration: 1 week to 2 week
Replace a character at a specific index in a String in Java
This post will discuss how to replace a character at a specific index in a Java String.
The string is an immutable class in Java. That means we cannot make any change in the String object. The only feasible solution is to create a new String object with the replaced character. There are several ways to replace a character at a specific index in a string:
1. Using substring() method
We can use String.substring(int, int) method to partition the string into two halves consisting of substring before and after the character to be replaced. Once we have isolated the character to be replaced, we can use the concatenation operator to build the final string, as shown below:
Download Run Code
2. Using StringBuilder
The recommended solution is to use mutable class StringBuilder to efficiently replace a character at a specific index in a string in Java. Alternatively, we can also use a slower StringBuffer class if thread safety is required.
3. Using toCharArray() method
Another plausible way of replacing character at the specified index in a string is using a character array that can be modified easily. The idea is to convert the given string to a character array using its toCharArray() method and then replace the character at the given index in the character array. Finally, convert the character array back into a string using String.valueOf(char) method.
4. Using Reflection
We have seen that we cannot make any change in the String object as string is immutable in Java. However, there is a way to modify a string using reflection. Reflection in Java allows code to perform illegal operations such as accessing and manipulating private fields and methods.
We know that string internally uses a character array that is final and private to the class. Although not recommended, reflection can easily modify that private character array.
That’s all about replacing a character at a specific index in a Java String.
Rate this post
Average rating 4.8 /5. Vote count: 25
No votes so far! Be the first to rate this post.
We are sorry that this post was not useful for you!
Tell us how we can improve this post?
- Coding Ground
- Corporate Training
- Java.lang Package classes
- Java.lang - Home
- Java.lang - Boolean
- Java.lang - Byte
- Java.lang - Character
- Java.lang - Character.Subset
- Java.lang - Character.UnicodeBlock
- Java.lang - Class
- Java.lang - ClassLoader
- Java.lang - Compiler
- Java.lang - Double
- Java.lang - Enum
- Java.lang - Float
- Java.lang - InheritableThreadLocal
- Java.lang - Integer
- Java.lang - Long
- Java.lang - Math
- Java.lang - Number
- Java.lang - Object
- Java.lang - Package
- Java.lang - Process
- Java.lang - ProcessBuilder
- Java.lang - Runtime
- Java.lang - RuntimePermission
- Java.lang - SecurityManager
- Java.lang - Short
- Java.lang - StackTraceElement
- Java.lang - StrictMath
- Java.lang - String
- Java.lang - StringBuffer
- Java.lang - StringBuilder
- Java.lang - System
- Java.lang - Thread
- Java.lang - ThreadGroup
- Java.lang - ThreadLocal
- Java.lang - Throwable
- Java.lang - Void
- Java.lang Package extras
- Java.lang - Interfaces
- Java.lang - Errors
- Java.lang - Exceptions
- Java.lang Package Useful Resources
- Java.lang - Useful Resources
- Java.lang - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
The java.lang.StringBuffer.setCharAt() method sets the character at the specified index to ch . This sequence is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index .
Following is the declaration for java.lang.StringBuffer.setCharAt() method
index − This is the index of the character to modify.
ch − This is the new character.
This method does not return any value.
IndexOutOfBoundsException − if index is negative or greater than or equal to length().
The following example shows the usage of java.lang.StringBuffer.setCharAt() method.
Let us compile and run the above program, this will produce the following result −
Replace a Character at a Specific Index in a String in Java
Last modified: October 29, 2019
- Java String
If you have a few years of experience in the Java ecosystem and you'd like to share that with the community, have a look at our Contribution Guidelines .
You can explore MongoDB through their free forever cluster - Atlas
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> check out the course, 1. introduction.
In this quick tutorial, we’ll demonstrate how to replace a character at a specific index in a String in Java.
We’ll present four implementations of simple methods that take the original String, a character, and the index where we need to replace it.
2. Using a Character Array
Let's begin with a simple approach, using an array of char.
Here, the idea is to convert the String to char and then assign the new char at the given index. Finally, we construct the desired String from that array.
This is a low-level design approach and gives us a lot of flexibility.
3. Using the substring Method
A higher-level approach is to use the substring() method of the String class.
It will create a new String by concatenating the substring of the original String before the index with the new character and substring of the original String after the index:
4. Using StringBuilder
We can get the same effect by using StringBuilder . We can replace the character at a specific index using the method setCharAt():
In this article, we focused on several ways of replacing a character at a specific index in a String using Java .
String instances are immutable, so we need to create a new string or use StringBuilder to give us some mutability.
As usual, the complete source code for the above tutorial is available over on GitHub .
Follow the Java Category
Unlike String Class, the StringBuilder class is used to represent a mutable string of characters and has a predefined method for change a
The setCharAt(int index, char ch) method of StringBuilder class is used to set the character at the position index passed as ch.
String are immutable in Java. You can't change them. You need to create a new string with the character replaced. String myName = "domanokz"
String are immutable in Java. You can't change them. You need to create a new string with the character replaced. String myName =
The setCharAt(int index, char ch) method of Java StringBuilder class is used to set the specified character at the given index. The specified character
The Java String class charAt() method returns a char value at the given index number. The index number starts from 0 and goes to n-1, where n is the length of
Replace a character at a specific index in a String in Java · 1. Using substring() method. We can use String. · 2. Using StringBuilder. The recommended solution
The Java StringBuilder setCharAt() method, is used to add/insert the character at the specified index in a StringBuilder object. The index refer to the
The java.lang.StringBuffer.setCharAt() method sets the character at the specified index to ch. This sequence is altered to represent a new character
replaceCharUsingCharArray · char chars = str.toCharArray(); chars[index] = ch; return String.valueOf(chars); } ; replaceChar · return str.