×

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

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java Instanceof Keyword

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). The type of comparison in java differentiates the...

4 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

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

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

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.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.