×

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java programming language all support the UTF-16 format. As arrays are immutable in Java, with the help of character arrays, we can manipulate the arrays. It is very efficient and faster in execution.

Characters in Java

Char is a data type which is used to hold values like

  • Alphabets
  • Special Characters (@,# , $,%)
  • Numbers between (0 to 65535)
  • Unicode characters

Char data type is used to declare character types of variables and methods. Its default size is 2 bytes.

The syntax for Declaration of Character arrays

To declare character arrays, we use the char keyword and two square brackets [].

Syntax:

char array name [];

We can also place the square brackets before the array name.

(OR)
char [] array name;

The syntax for initialization of Character arrays

Syntax:

char array name [] = new char [size of the array];

Example for initialization of character array

Main.java

public class Main
{
public static void main(String[] args) {
// Declaration character array
    char a[]=new char[6];
//Initializing the values to a character array
    a[0]='r';
    a[1]='0';
    a[2]='h';
    a[3]='i';
    a[4]='t';
    a[5]='h';
// Printing the values of the character array
System.out.println(a[0]);
}
}

Explanation

In the above program, a character array with the name 'a' is declared and initialized with characters of the word "Rohith". We will print the characters using the println method.

Loops for Iterating the character arrays

To iterate the character arrays, we use loops like for, while, do while and for each loop in Java.

Iterating using for each loop

Program for iteration of character arrays

Main.java

import java.util.*;
public class Main
{
public static void main(String[] args) {
    char a[]=new char[6];
    a[0]='r';
    a[1]='0';
    a[2]='h';
    a[3]='i';
    a[4]='t';
    a[5]='h';
// printing character array values using for each loop
for(char c:a) {  
        System.out.println(c);  
        }  
}
}

Output

CHARACTER ARRAY IN JAVA

Explanation

In the above program, a character array with the name 'a' is declared and initialized with characters of the word "Rohith". We will print the characters using each loop method.

Iterating using for loop

Program for iteration of character arrays

Main.java

public class Main {  
    public static void main(String[] args) {  
        char[] A = {'H', 'e', 'l', 'l', 'o'};  
// printing character array values using for loop
        for (int i=0; i<A.length; i++) {  
        System.out.println(A[i]);  
        }  
        }  
}  

Output

CHARACTER ARRAY IN JAVA

Explanation

In the above program, a character array with the name 'a' is declared and initialized with characters of the word "Hello". We will print the characters using for loop method.

Sorting a character array

To sort a character array, we will use Arrays.sort() method

The syntax for sorting Character arrays

Syntax:

Arrays.sort(ArrayName) ;

Program for sorting character arrays

Main.java

import java.util.Arrays;  
public class Main {  
    public static void main(String[] args)
    {  
// Declaring a character array with random characters
        char[] A = {'v', 'a', 'c', 'g', 'r','q'};  
// Sorting the array using Arrays.sort() method 
        Arrays.sort(A);  
// By default, the sorted array will be in ascending order.
System.out.println("Sorted array is");
        System.out.println(Arrays.toString(A));  
    }  
}  

Output

CHARACTER ARRAY IN JAVA

Explanation

In the above program, a character array with the name 'a' is declared and initialized with characters. By using Arrays. sort(), we will sort the characters in ascending order by default.

Length of a character array

To find the length of a character array, we use Arrayname. Length method.

Syntax:

Array name.length;

Program for finding the length of character arrays

Main.java

public class Main
{  
    public static void main(String[] args)
    {  
        // Declaring the array and initializing it with characters.
        char A []= {'R', 'o', 'h', 'i', 't','h'};  
        // Using the length method to find the length of an array.
        System.out.println("length of the character array is "+A.length);  
    }  
}  

Output

CHARACTER ARRAY IN JAVA

Explanation

In the above program, a character array with the name 'a' is declared and initialized with characters of the word "Rohith". We will use the length method to find the length of a character array.

To convert a string array into a character array.

The toCharArray() function makes it simple to change a string array into a character array. Changing a string field into a character field is the simplest.

Program to convert string arrays into character arrays

Main.java

class Main
{  
    public static void main(String[] args) 
    {  
        String s = "Hello"; 
        char[] a = s.toCharArray();  
        for(char c : a) 
        {  
            System.out.println(c);  
        }  
    }  
}

Output

CHARACTER ARRAY IN JAVA

Related Topics

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

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.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 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 calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.