×

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

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.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

How to Convert Octal to Decimal in Java

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

2 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

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

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.