×

Char and String differences in Java

Characters in Java

Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals.

A Java char has 16 bits in length and has a range of 0 to 65,536. In addition, the normal ASCII character set spans 0 to 127.

Syntax of char Java.

char variable_name = ‘variable_value’;

Characteristics of Char in Java

As previously stated, the range is between 0 to 65,536.

Because Java uses the Unicode system rather than the ASCII coding system, the default size is 2 bytes.

The default value is 'u0000,' which is the lowest Unicode range.

Simple program to display the characters

public class example {
 
    public static void main(String[] args) {
         
        char c1 = 'a';
        char c2 = 'A';
         
        System.out.println("c1 is: " +c1);
        System.out.println("c2 is: " +c2);
         
    }
 }

OUTPUT:

c1 is: a
c2 is: A

Character using ASCII value

We've used integers to initialize three char Java variables in the example below. Those integers will be transformed into their ASCII equivalents when printed. The compiler will convert a number to a character and display the associated ASCII value.

Example:

public class example {
 
    public static void main(String[] args) {
         
        char c1, c2, c3;
         
        /*
         *  Since 69 and 71 are the ASCII value for E and G, 
         *  we have assigned c1 as 69 and c3 as 71.
         */
         
        c1 = 69;
        c2 = 'F';
        c3 = 71;
         
        System.out.println("The characters are: " + c1 + c2 + c3);
         
    }
 
}

OUTPUT:

The characters are: EFG

Breaking string into character Java

We'll split a String in the form of Character Java in this part. To begin, we've turned an input String into a Java character array. The function toString() method was then used to print the value of the original String as well as the characters contained within that array.

Example:

import java.util.Arrays;
 
public class example {
 
    public static void main(String[] args) {
         
        String str1 = "helloworld";
         
        // conversion into character array
        char[] chars = str1.toCharArray();
         
        System.out.println("Original String was: " + str1);
        System.out.println("Characters are: " + Arrays.toString(chars));
         
    }
 
}

OUTPUT:

Original string was: helloworld
Characters are: [h, e, l, l, o, w, o, r, l, d]

Incrementing and Decrementing the characters

We've initialized a Java character variable in the program below and then tried incrementing and decrementing it with the operator. Before and after each operation, a print statement is inserted to examine how the value changes.

Example:

public class example {
public static void main(String[] args) {
char c1 = 'C';
System.out.println("The value of c1 is: " + c1);
c1++;
System.out.println("After incrementing: " + c1);
c1--;
System.out.println("After decrementing: " + c1);
         }
}

OUTPUT:

The value of c1 is: C
After incrementing: D
After decrementing: C

Typecast integer to character Java

In this part, we've explicitly typecast an integer value to Java char after initializing a variable with an integer value. All of these numeric-initialized integer variables are associated with a certain character.

Example:

public class example {
 
    public static void main(String[] args) {
         
        int number1 = 75;
        char chars1 = (char)number1;
         
        int number2 = 73;
        char chars2 = (char)number2;
     
        int number3 = 84;
        char chars3 = (char)number3;
         
        int number4 = 69;
        char chars4 = (char)number4;
     
        System.out.println(chars1);
        System.out.println(chars2);
        System.out.println(chars3);
        System.out.println(chars4);
         
    }
 
}

OUTPUT:

K
I
T
E

Represent character into Unicode:

In this part, we've set the Unicode value for three Java characters (escape sequence). Following that, we simply printed those variables. The rest will be handled by the compiler, which will explicitly translate the Unicode value to a Java character.

Example:

public class example {
 
    public static void main(String[] args) {
         
        char chars1 = '\u0058';
        char chars2 = '\u0059';
        char chars3 = '\u005A';
         
        System.out.println("chars1, chars2 and chars3 are: " + chars1 + chars2 + chars3);
         
    }
 
}

OUTPUT:

chars1, chars2, and chars3 are: XYZ

Strings in Java?

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 three ways to replace character 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.

Difference between char and strings

StringsCharacters  
A string is a collection of characters that are represented as a single data type.A Character Array is a collection of char data in sequential order.
Strings supports build in functions like charAt(), substring() etc.Characters do not support build-in functions
Strings are unchangeable.Characters are changeable
Strings can be stored in memory in a variety of waysCharacter Array elements are sequentially stored at increasing memory regions.
The String Constant Pool holds all of the StringsThe Heap holds all of the Character Arrays.
In Java, it is not recommended to store passwords.In Java, this is the preferred method for saving passwords.

Related Topics

CRC Program in Java

The acronym CRC stands for Cyclic Redundancy Check. It is invented by W. Wesley Peterson in 1961. It is an error detection technique that detects errors in digital networks (also...

5 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.