×

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

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Factorial Program in Java using Recursion

Factorial Program in Java Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to...

3 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Can Abstract Classes have Static Methods in Java

Abstract Class An abstract class in Java is one that explicitly uses the keyword "abstract" in its declaration. There are options for both non-abstract and abstract techniques (method with the body)....

4 minutes read.