×

Replace character in string Java

Characters in Java

In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters, Character class gives us much useful class (i.e., static) methods. The Character function Object can be used to generate a Character object.

Creating character object

Character ch = new Character('a');

The preceding code generates a Character object with the char type 'a'. The Character class has only one function Object that takes a char data type argument.

When we send a simple character into a method that expects an object, then the compiler turns it to a Char class object automatically. Autoboxing and Unboxing are the terms for this feature.

Methods in the character class

  • Boolean isLetter (char ch):-

This method tells us whether or not the supplied char value is a letter. If it's letter([A-Z],[a-z]), the procedure will return true; otherwise, it'll return false. As char to int is automatically typecasted in java, we may pass an ASCII value also as an input in place of a character.

Syntax:

boolean isLetter(char ch);

  • Boolean isDigit(char ch):-

This method estimates whether or not the supplied char value(ch) is a digit. We can also pass an ASCII value as an input here.

Syntax:

boolean isDigit(char ch)

  • Boolean isWhitespace(char ch):-

It checks to see if the given char value is white space. Space, tab, and newline are examples of whitespace.

Syntax:

boolean isWhitespace(char ch)

  • boolean isUpperCase(char ch):-

It checks whether or not the provided char value is uppercase.

Syntax:

boolean isUpperCase(char ch);

  • char toUpperCase(char ch):

It returns the provided char value's uppercase. If an ASCII value is supplied, the uppercase ASCII value will be returned.

Syntax:

char toUpperCase(char ch);

  • boolean isLowerCase(char ch):-

It checks whether or not the provided char value is lowercase.

Syntax:

boolean isLowerCase(char ch);

  • toString(char ch):-

It provides a String class object that represents the char value, which is a one-character string. We can't pass an ASCII value here.

Syntax:

String toString(char ch);

What is a String?

Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language.

“String” is a Java platform class that allows you to construct and handle strings.

Creating Strings

The normal way to create a string in Java is to simply write:-

String s = “Hello World”;

The compiler constructs a String object with the value "Hello world!" whenever it detects a string phrase in your code.

String objects cannot be made by using the new keyword and a function Object, just like any other object. The String class provides 11 constructors that allow you to set the string's initial value from a variety of sources, including an array of characters.

Another way to create a string is :-

String s = new String (“Hello World”);

String Builder:

The char value, which is a one-character string, is represented by a String class object. We can't use an ASCII value in this case.

Syntax:

StringBuilder str = new StringBuilder();
str.append("GFG");

String Buffer:-

StringBuffer is a String companion class that provides a lot of the same functionality as strings. StringBuffer shows growable and writable character sequences, whereas string represents fixed-length, immutable character sequences.

Syntax:

StringBuffer s = new StringBuffer("Hello World");

String Tokenizer:-

The StringTokenizer class in Java is used to tokenize a string.

String Joiner:-

String Joiner is a java.util package class that is used to build a sequence of characters divided by a delimiter and optionally starting with a transferred prefix and finishing with a transferred suffix.

Syntax:

public StringJoiner(CharSequence delimiter);

As we study in the above part, we have sufficient knowledge about replacing a character in a string. So, there are a few ways to replace characters in a string:

 String Builder:

In contrast to the String Class, the StringBuilder class includes a built-in function for this — setCharAt (). By calling this function and giving the character and the index as parameters, you can replace the character at a given index.

Now take a look at an example:

public class GFG {


public static void main(String args[])
{
String str = "Hello World";
int index = 3;
char ch = 'F';
System.out.println("Original String = " + str);


StringBuilder string = new StringBuilder(str);
string.setCharAt(index, ch);
System.out.println("Modified String = " + string);
}
}

OUTPUT:

Original String: Hello World
New String: Hello World

String Buffer:

The StringBuffer class, like StringBuilder, provides a predefined method for this - setCharAt (). By calling this function and giving the character and the index as parameters, you can replace the character at a given index. Thread-safe StringBuffer When compared to StringBuffer, StringBuilder is faster, but it is not thread-safe.

Example:

public class GFG {


public static void main(String args[])
{
String str = “Hello World";
int index = 6;
char ch = 'F';
System.out.println("Original String = " + str);


StringBuffer string = new StringBuffer(str);
string.setCharAt(index, ch)
System.out.println("Modified String = " + string);
}
}

OUTPUT:

Original String: Hello World
New String: Hello World

Related Topics

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Access specifiers in Java

What are access specifiers in Java? Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify...

7 minutes read.

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Brilliant Number in Java

It is a number N that is made up of two prime numbers that have the same number of digits and is called a brilliant number. Several/Some of the brilliant Numbers...

3 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.