0

I have been trying to understand string handling techniques in Java, while I came across that my code is accepting the entire string that is initialized to the string object to a character array of lesser size than the number of characters in that string object. My example code:

public class test{
    public static void main(String args[]){
        String s = new String ("Test String");
        char ch[] = new char[0];
        
        ch = s.toCharArray();
        
        for (int i = 0 ; i < s.length() ; i++ ){
            System.out.print(ch[i]);
        }
    }
}

While I have initialized the ch to be of size 0, the entire string in s is being printed in the output. Is it not supposed to give me an error stating the array initialized is lesser than the length of the characters in the string s? Can someone help me if I am wrong in my understanding?

Richard Wilson
  • 297
  • 4
  • 17
  • From the [JavaDoc for String](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()): "**a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.**" – Randy Casburn May 27 '21 at 17:57
  • 1
    At `ch = s.toCharArray();` you are *not* filling array created via `new char[0];` but assigning to `ch` reference to *separate* array created by `toCharArray();` – Pshemo May 27 '21 at 17:58
  • @RandyCasburn: Does that mean the character array size gets "overidden" from what is initialised to the length of the string when assigned using `toCharArray()`? – learner May 27 '21 at 18:01
  • @learner - yes it does. – Randy Casburn May 27 '21 at 18:01
  • 2
    "*Does that mean the character array size gets "overidden"*", no arrays have fixed size. Once created you can't resize it. What happens here is that you are assigning to `ch` variable *separate* array. So `ch` will no longer hold reference to array of size 0, but will be holding reference to another array (filled with characters same as in string). – Pshemo May 27 '21 at 18:04
  • @Pshemo: Can you please stress on "but assigning to `ch` reference to separate array created by `toCharArray()`; I didn't clearly get this statement. – learner May 27 '21 at 18:04
  • 1
    For now I suggest reading [What is the difference between a variable, object, and reference?](https://stackoverflow.com/q/32010172). (BTW arrays are also considered as objects. `new` keyword creates object of *specified type* like `new Car(..)` `new Person()` `new char[0]`). – Pshemo May 27 '21 at 18:06
  • Sure. Thanks @Pshemo – learner May 27 '21 at 18:09

1 Answers1

1

With this line

ch = s.toCharArray();

You are pointing ch variable to a char array created from s internal array

You need something like

ch = Arrays.copyOfRange(s.toCharArray(), 0, 1);
Dragonborn
  • 1,755
  • 1
  • 16
  • 37