Tutorial: Copying a Character Array

Authored by
Ronald S. Holland
Total Application Works

To visit my site

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

To contact us

© 2002 - 2009 All Rights Reserved Total Application Works

  • Tell a friend about this site (copy and paste the following link or send this page to a friend.)
  • <html>
    <title>Example of a link </title>
    <table border>
    <a href="http://sumtotalz.com/TotalAppsWorks/Structures/Arrays/CharArrayCopyExample.html">An Introduction to copying a character array </a>
  1. Java Table of contents
  2. 2nd Java Cup
  3. Pie Chart I
  4. Pie/Bar Chart IB
  5. Pie/Bar Chart II
  6. Pie/Bar Chart III
  7. A Basic Calculator
  8. Linked Lists
  9. Linked List II
  10. Linked List III
  11. Linked List IV
  12. Hardware Store I
  13. Hardware Store II
  14. Hardware Store III
  15. Client/Server
  16. Client/Server II
  17. Client/Server III
  18. Client/Server IV
  19. Multithreaded Client/Server
  20. Multithreaded Client/Server II
  21. Multithreaded Client/Server III
  22. Basic Calculator II
  23. Basic Calculator III


After you finish this tutorial, you will understand:

  • The array data structure.
  • The use of arrays to store of values.
  • How to declare an array, initialize an array and refer to individual elements in am array.
  • Some basic comparison techniques.

Introduction to Arrays

What is an array? We all understand the concept of an array. If I say that you have a bookcase that has ten shelves and you can place one book on a shelf. We all understand this instruction. Furthermore, if I say once you place the first book on a shelf, the other nine books must be of the same type (i.e., dictionary, mystery, computer science, etc.), we all understand this instruction. If we all understand the above instructions, then we understand the concept of an array. A bookcase contains books. An array contains data. An array of size ten contains 10 pieces of data. This is just like our bookcase that contained ten books with one book per shelf. An array is an important data structure in any programming language. An array is a fixed-length structure that stores multiple values of the same data type (i.e., int, float, long, char, double, etc.). You can group values of the same type within arrays. You cannot mix data types. For instance, you cannot store data of type int and float in the same array of primitive data types. Arrays are supported directly by the Java programming language. Primitive arrays (not to be confused with the Array class) should be considered as:

  • Data structures - consisting of related data items of the same type
  • Static - remain the size once they are created
  • An array - a group of contiguous memory locations that all have the same name and type
    • Most variables occupy a single location. The name of that variable is a reference to a memory location where that value of that variable is stored. Consider the following example.

      char a = 'D' ;
             |    |
             | D  |
        a -> +----+
      address of where 
      'a' is located in 
      int ar[] = new int[5] ;
      ar[0] = 10 ;
             |    |    |    |    |    |
             | a  |  b |  c | d  | e  |
       ar -> +----+----+----+----+----+
      ^ | address of where 'ar' is located in memory
      Figure 1: Variable locations

      You will note that the value of 'D' is stored at the location referenced by 'a'. In other words, the letter/reference 'a' does not contain the value of 'D'. Your house address does not contain your possessions; it is the house at that location that contains your possessions. Also note that ar[0] refers to the first location of the array ar.
  • The first element in an array is referenced by subscript 0. ar[0] is where the letter 'a' is located.
  • The position number in the square brackets is called a subscript
  • A subscript must be an integer or an integer expression
  • When an expression is used as a subscript, the expression is evaluated first
  • If the array name is ar, the length may be determined by
        int len = ar.length ;
  • Every array in Java knows its own length
  • The brackets that enclose the subscript are an operator in Java
    • An array reference may be reassigned to an array of a different size

Declaring and allocating arrays

    Arrays occupy space in memory. The programmer specifies the data type of the elements and uses the new operator to dynamically allocate the space required to hold the elements specified. Arrays are considered objects and all objects must be allocated with the new operator. For example, to allocate a ten-element array named ar

        char ar[] = new char[10];
    ---------------- or case 2 --------------------
        char ar[];
        ar = new char[10];
    ---------------- or case 3 --------------------
    char ar[] = { a, b, c, d, e, f, g, h, i, j };
    The above list encased within the brackets 
    is called an initializer list. It initializes the
    array with the initial values and the size of the
    array equals the number of values in the list.
    Figure 2: Declarations and Allocations

    When arrays are allocated, the elements are automatically initialized to

    • Zero for the numeric primitive types variables.
    • false for boolean, or
    • null for references (any nonprimitive type).
    For examples of declarations, consider the following:
    1-  String b[] = new String[ 100 ], 
           s[] = new String [ 27 ];
    2-  double[] array1, array2;
    3-  double[] array1 = new double[ 10 ], 
                   array2 = new double[ 20 ];
  • Every element of a String is a reference to a String that has the value null by default

CharArrayCopyExample template

In the following table, we will show a CharArrayCopyExample code template.

public class CharArrayCopyExample {

/** *************************************************
 * The CharArrayCopyExample() class:  
 * 1- Uses an initializer list to populate an array
 * 2- Displays the contents of the character array
 * 3- Creates a sub-string from the array
 * 4- Displays the sub-string 

   public CharArrayCopyExample() {


   public static void main(String[] args) {

      CharArrayCopyExample cace = new CharArrayCopyExample() ;
} /****************** End of CharArrayCopyExample class ************************/  
Figure 3: CharArrayCopyExample template

CharArrayCopyExample code example

In the following figure, you will find the code for this example.

/** **********************************************
 * The CharArrayCopyExample class
 * 1- Uses an initializer list to populate an array
 * 2- Displays the contents of the character array
 * 3- Creates a sub-string from the array
 * 4- Displays the sub-string 

import javax.swing.* ;

public class CharArrayCopyExample {

   private char charArray[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
   private String text , output = "" ;

   /** *************************************************
    * The CharArrayCopyExample() method 
    * 1- Creates a string out of charArray.
    * 2- Creates a sub-string out of charArray.
   public CharArrayCopyExample() {
      output += "Printing entire array\n" ;	

      output += String.valueOf( charArray ) + "\n\n" ;
      output += "Printing sub-array elements 3 to 5\n" ;	
      output += copyValueOf(charArray, 3, 5) ; 

      JOptionPane.showMessageDialog( null, 
               "Initializing a Character Array with",
                  JOptionPane.INFORMATION_MESSAGE );


   /** ***************************************************
    * The copyValueOf() method:
    * 1- is passed an array and the start and stop index
    *    for the sub-string.
    *    - int a is the start index
    *    - int b is the stop index
    * 2- Creates a sub-string from a charArray.   
    * 3- Returns a sub-string to the caller.
   public String copyValueOf( char ca[], int a , int b ) {
      String str = "";
      int loopctrl = a+b ;

      for( int ii = a ; ii <= loopctrl ; ii++ ) { 
          str += ca[ ii ] ;

      return str ;

   /** **********************************************
    * The main() method is the entry point that is 
    * called by Java when the program is loaded into
    * memory.
   public static void main( String[] args ) {
       CharArrayCopyExample cace = new CharArrayCopyExample()  ;
}/****************** End of CharArrayCopyExample class ************************/
Figure 4: CharArrayCopyExample Example Code

Methods used in the CharArrayCopyExample example

In the following table, you will find a brief description of some of the methods used in the example.

Methods Descriptions
String class Methods
valueOf(char[] data) Returns the string representation of the char array argument.
JOptionPane Methods
showMessageDialog(null, "alert", "alert", JOptionPane.INFORMATION_MESSAGE) Show an error/message dialog that displays the message, 'alert':
Figure 5: CharArrayCopyExample API Method Description

CharArrayCopyExample .bat file

The following example is the Bat file used to compile and run the CharArrayCopyExample program.

javac  CharArrayCopyExample.java

java   CharArrayCopyExample 

Figure 6: Bat file used to compile and run CharArrayCopyExample example.

To run this example

To run this example,

  1. Cut and paste the code in Figure 4 and place it in a file called CharArrayCopyExample.java.
  2. Cut and paste the code in Figure 5 and place it in a file called CharArrayCopyExample.bat.
  3. Double click on the CharArrayCopyExample.bat file and you will see the following.

    Figure 7: Image of CharArrayCopyExample

The Array class

    provides static methods to dynamically create, access and manipulate Java array objects. This is not a primitive array structure (e.g., int, float, long double, etc.)

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2009 All Rights Reserved Total Application Works