topics content@scaler.com
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- title: Java String replace() Method - Scaler Topics description: In Java, we can replace occurrences of a character or substring using the replace() method. Learn more on Scaler topics. category: Java author: Bharat L. Vora --- :::section{.main} In Java, we can replace occurrences of a character or substring using the `replace()` method, which has two variations: 1. `replace(char oldChar, char newChar)` 2. `replace(CharSequence oldString, CharSequence newString)` These methods return a new string with the replacements made. Note that the original string is not modified since strings in Java are immutable. ### Syntax The `replace()` method in Java has two syntaxes. * 1. Syntax for Replacing a Character: ```java public String replace(char searchChar, char newChar) ``` * 2. Syntax for Replacing a Substring: ```java string.replace(CharSequence oldString, CharSequence newString); ``` ### Parameters Values To replace all occurrences of a particular character with another character in Java, we use the first syntax of the replace() method in Java. > 1. **`oldChar`** - The character to be replaced in the string. > 2. **`newChar`** - The character to be used instead of oldChar in the string. To replace all occurrences of a particular string or substring with another string or substring, we use the second syntax of the replace() method in java. > 1. **`oldString`** - The string or substring to be replaced in the original string. > 2. **`newString`** - The string or substring to be used in place of the old string or substring in the original string. ::: :::section{.main} ### Return Value The `replace()` method in Java returns a new string where each occurrence of a character/word/sentence has been replaced with a new character/word/sentence. If there is no match for the new character/word/sentence, the `replace()` in java method returns the original string. ### Exception We cannot use `null` as an argument in the `replace()` method. If we use `null` as an argument, the system will throw a `NullPointerException`. ### Internal Implementation Here is the internal implementation of the replace method in java: ```java public String replace(char oldChar, char newChar) { // If the characters are not equal if (oldChar != newChar) { int len = value.length; // Length of the string int i = -1; // Initialize index variable char[] val = value; // Get the character array of the string // Find the index of the first occurrence of oldChar while (++i < len) { if (val[i] == oldChar) { break; } } // If oldChar is found if (i < len) { char buf[] = new char[len]; // Create a new character array to store the modified string // Copy characters from the original string until the index of oldChar for (int j = 0; j < i; j++) { buf[j] = val[j]; } // Replace all occurrences of oldChar with newChar while (i < len) { char c = val[i]; buf[i] = (c == oldChar) ? newChar : c; i++; } // Return the new string created from the modified character array return new String(buf, true); } } // If oldChar is not found or oldChar equals newChar, return the original string return this; } ``` ::: :::section ## Java String replace() Method Examples ### Example 1: Java String replace(char old, char new) Method Replacing One Character with Another in Java Using `replace()` in java. ```java public class Main { public static void main(String[] arg) { System.out.println("Original String - G00d M0rning"); //replacing '0' with 'o' and displaying it on the screen. System.out.println( "Corrected String - " + "G00d M0rning".replace('0', 'o') ); } } ``` **Output:** ```java Original String - G00d M0rning Corrected String - Good Morning ``` In the above code, we display the string object "`G00d M0rning`" and then call the replace() method on this object. We replace '0' with 'o' and then print the modified string on the screen. ### Example 2: Java String replace(CharSequence target, CharSequence replacement) Method Example of the `replace(CharSequence oldString, CharSequence newString)` method in Java: ```java public class Main { public static void main(String[] args) { String originalString = "Hello, World!"; String newString = originalString.replace("World", "Java"); System.out.println("Original String: " + originalString); System.out.println("Replaced String: " + newString); } } ``` **Output:** ``` Original String: Hello, World! Replaced String: Hello, Java! ``` ### Exception 3: Exception in Java replace() method ```java public class Main { public static void main(String[] arg) { String obj = "Hello World"; try { //replacing "World" with null and trying to store it again in 'obj' obj = obj.replace("World", null); //Displaying the replaced string System.out.println(obj); } catch (NullPointerException e) { System.out.println("NullPointerException occurred!"); } } } ``` **Output** ``` NullPointerException occurred! ``` ::: :::section{.summary} ## Conclusion - The `replace()` in java is a built-in method of the Java `String` class. - It is utilized to replace characters or substrings within a string. - If the replacement does not find a match, the original string remains unchanged and is returned as the result. ::: :::section{.faq-section} ## Frequently Asked Questions (FAQs) **Q**. What implementations are available for the replace() in Java String class? **A**. There are various other built-in method implementations, such as: * replaceFirst() * replaceAll() **Q**. Do replaceAll() and replace() work the same? **A**. replaceAll() is an advanced implementation of replace() where regular expressions can be used to replace in java all occurrences of characters in a string.

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully