×

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

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

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

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.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

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.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.