×

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

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

How to handle NullPointerException in Java

Introduction: Throwable class is the super or root class of the java exception hierarchy which contains two sub-classes. The classes’ are- ExceptionError Exception: If you are doing any wrong things in a...

3 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

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

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.