Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Character Array in Java
Next article icon

Character Array in Java

Last Updated : 01 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, a character array is a data structure used to store a sequence of characters. The characters are stored in contiguous memory locations and can be accessed by their index, similar to an array of integers or any other data type.

Declaring a Character Array

A character array can be declared in the following way:

char[] charArray;

This declares a reference variable called charArray that can store the memory address of a character array. To initialize the array and allocate memory for it, you can use the new keyword:

charArray = new char[10];

This creates an array with a length of 10, which means it can store 10 characters. The elements of the array are initialized to the default value of the char data type, which is the null character ('\u0000').

Alternatively, you can declare and initialize a character array in a single line:

char[] charArray = new char[10];

You can also initialize a character array with a set of characters by using the curly braces {} notation:

char[] charArray = {'a', 'b', 'c', 'd', 'e'};

This creates an array with a length of 5 and assigns the characters 'a', 'b', 'c', 'd', and 'e' to the elements at indexes 0 through 4, respectively.

Accessing Elements in a Character Array

You can access the elements of a character array using the array name followed by the element's index in square brackets. For example:

charArray[0] = 'f';

This assigns the character 'f' to the element at index 0 of the charArray. You can also use the array elements to perform operations. For example:

System.out.println(charArray[0] + " " + charArray[1]);

This prints the characters at index 0 and 1 of the charArray, separated by a space.

Iterating Over a Character Array

You can use a for loop to iterate over the elements of a character array. For example:

Java
for (int i = 0; i < charArray.length; i++) {     System.out.println(charArray[i]); } 

This prints each element of the charArray on a new line.

Another way to iterate over a character array is to use the enhanced for loop (also known as the for-each loop):

Java
for (char c : charArray) {     System.out.println(c); } 

This also prints each element of the charArray on a new line.

Comparing Character Arrays

To compare two character arrays for equality, you can use the Arrays.equals() method:

Java
char[] charArray1 = {'a', 'b', 'c', 'd', 'e'}; char[] charArray2 = {'a', 'b', 'c', 'd', 'e'};  if (Arrays.equals(charArray1, charArray2)) {     System.out.println("The arrays are equal."); } else {     System.out.println("The arrays are not equal."); } 

This compares the elements of charArray1 and charArray2, and if all the elements are identical, it prints "The arrays are equal." Otherwise, it prints "The arrays are not equal."

Converting a String to a Character Array

You can convert a String to a character array using the toCharArray() method:

Java
String str = "Hello World"; char[] charArray = str.toCharArray(); 

This creates a character array with the same characters as the string and assigns it to the charArray variable.

Converting a Character Array to a String

You can convert a character array to a String using the String constructor that takes a character array as an argument:

Java
char[] charArray = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}; String str = new String(charArray); 

This creates a new String object with the same characters as the charArray, and assigns it to the str variable.

Note that, while you can use the "==" operator to compare the references of two arrays, it will not compare the elements of the arrays. So if you want to compare the two arrays, you should use the Arrays.equals(arr1, arr2) method, which returns true if the two arrays are equal, and false otherwise.

copyOf() method from the Arrays class: This method creates a new array with the same length as the original array and copies the elements from the original array to the new array. It can be used to make a copy of a character array, which is useful when you want to make changes to the original array without affecting the original data.

Example of copyOf() method:

Java
char[] originalArray = {'a', 'b', 'c', 'd', 'e'}; char[] copiedArray = Arrays.copyOf(originalArray, originalArray.length); 

Here, the originalArray is copied to the copiedArray. Now, you can make changes to the copiedArray without affecting the originalArray.

copyOfRange() method from the Arrays class: This method creates a new array with the specified range of elements from the original array and copies the elements from the original array to the new array. It can be used to make a copy of a specific range of elements in a character array.

Example of copyOfRange() method:

Java
char[] originalArray = {'a', 'b', 'c', 'd', 'e'}; char[] copiedArray = Arrays.copyOfRange(originalArray, 1, 4); 

Here, the elements of the originalArray are copied from index 1 to index 3 to the copiedArray.

When working with character arrays is that they are mutable, meaning their elements can be changed after they are created. Strings, on the other hand, are immutable, meaning their characters cannot be changed after they are created. If you need to change the characters in a string, you must create a new string with the desired characters.


Next Article
Character Array in Java

S

sarthakhanda
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Technical Scripter 2022
  • Java-Arrays
Practice Tags :
  • Java

Similar Reads

    How to Convert Character Array to String in Java?
    Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character "\0". A character array can be converted to a string and vice versa. In this article, we will discuss how to convert a character array to a string
    4 min read
    Difference between String and Character array in Java
    Unlike C/C++ Character arrays and Strings are two different things in Java. Both Character Arrays and Strings are a collection of characters but are different in terms of properties. Differences between Strings and Character Arrays:PropertyStringCharacter ArrayDefinitionA sequence of characters is r
    3 min read
    CharsetDecoder Class in Java
    For encoding and decoding tasks, many methods are offered in Charset Encoder and Charset Decoder classes in Java. The Charset Decoder class is used for text handling to convert bytes to characters. The Charset decoder accepts a sequence of bytes as its input and displays Unicode characters as output
    5 min read
    Character.isSpaceChar() method in Java
    The java.lang.Character.isSpaceChar(char ch) is an inbuilt method in java which determines if the specified character is a Unicode space character. A character is considered to be a space character if and only if it is specified to be a space character by the Unicode Standard. This method returns tr
    2 min read
    Character.digit() in Java with examples
    The java.lang.Character.digit() is an inbuilt method in java which returns the numeric value of the character ch in the specified radix. It returns -1 if the radix is not in the range MIN_RADIX or if the value of ch is not a valid digit in the specified radix. A character is a valid digit if at leas
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences