• Data Structure & Algorithm Classes (Live)
  • System Design (Live)
  • DevOps(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
  • Mathematical
  • Bitwise Algorithms
  • Randomized Algorithms
  • Greedy Algorithms
  • Dynamic Programming
  • Divide and Conquer
  • Backtracking
  • 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
  • BlueprintJS
  • TensorFlow.js
  • English Grammar
  • School Programming
  • Number System
  • Trigonometry
  • Probability
  • Mensuration
  • 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
  • Mathematics
  • 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
  • Testimonials
  • 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

Related Articles

StringBuilder setCharAt() in Java with Examples

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:

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

Java backend development - live, master c programming with data structures, python programming foundation -self paced, data structures and algorithms - self paced, javascript foundation - self paced, competitive programming - live, complete interview preparation - self paced, master c++ programming - complete beginner to advanced, complete test series for service-based companies, improve your coding skills with practice, start your coding journey now.

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?

jww's user avatar

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:

waldyr.ar's user avatar

Turn the String into a char[], replace the letter by index, then convert the array back into a String.

16dots's user avatar

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.

Ardent Coder's user avatar

I agree with Petar Ivanov but it is best if we implement in following way:

Leninkumar Koppoju's user avatar

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...).

C.Champagne's user avatar

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.

fenceop's user avatar

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

Hamodea Net's user avatar

this will work

Output : domaxokz

Rachel Gallen's user avatar

Not the answer you're looking for? Browse other questions tagged java string replace indexing character or ask your own question .

Hot Network Questions

string set char at java

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

2297/how-do-i-replace-character-from-string-at-specific-indexes

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?

string set char at java

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 );

string set char at java

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!

string set char at java

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

How do I replace all occurrences of a string in JavaScript?

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

string set char at java

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.

Google

Already have an account? Sign in .

string set char at java

Javatpoint Logo

Java String

Java string methods.

JavaTpoint

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.

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

RSS Feed

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

Output: Techie_Delight

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.

Download Code

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?

guest

java package tutorial

Java.lang.StringBuffer.setCharAt() Method

Description.

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 .

Declaration

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.

Return Value

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

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 .

announcement - icon

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():

5. Conclusion

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 .

Build your API with SPRING - book cover

Follow the Java Category

string set char at java

IMAGES

  1. Java Convert char to String with examples

    string set char at java

  2. how to convert char set in android?

    string set char at java

  3. Convert string to integer java

    string set char at java

  4. Ejemplo del método Java String charAt ()

    string set char at java

  5. Java Lang Nullpointerexception Println Needs A Message

    string set char at java

  6. How to convert a String to Char Array in Java?

    string set char at java

VIDEO

  1. Java program to convert first character of every string to Upper case

  2. I tried it first time too. Error is bc double quotes represent string and single quotes char in java

  3. Java Program to convert Character or Character array to String

  4. Dining set char kursi 🥰 modular dining set finishing furniture shisham kalakara Prasad furniture

  5. 🔴Frequently Asked Java Program 02: How to reverse a string using char array in JAVA?

  6. First repeating and non repeating char in a String java

COMMENTS

  1. Replace a character at a specific index in a String in Java

    Unlike String Class, the StringBuilder class is used to represent a mutable string of characters and has a predefined method for change a

  2. StringBuilder setCharAt() in Java with Examples

    The setCharAt(int index, char ch) method of StringBuilder class is used to set the character at the position index passed as ch.

  3. Replace a character at a specific index in a string?

    String are immutable in Java. You can't change them. You need to create a new string with the character replaced. String myName = "domanokz"

  4. How do I replace character from string at specific indexes

    String are immutable in Java. You can't change them. You need to create a new string with the character replaced. String myName =

  5. Java StringBuilder setCharAt() Method with Examples

    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

  6. Java String charAt() method

    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

  7. Replace a character at a specific index in a String in Java

    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

  8. Java StringBuilder setCharAt() Method

    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

  9. Java.lang.StringBuffer.setCharAt() Method

    The java.lang.StringBuffer.setCharAt() method sets the character at the specified index to ch. This sequence is altered to represent a new character

  10. Replace a Character at a Specific Index in a String in Java

    replaceCharUsingCharArray · char[] chars = str.toCharArray(); chars[index] = ch; return String.valueOf(chars); } ; replaceChar · return str.