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?

8
  • From the JavaDoc for String: "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." Commented May 27, 2021 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(); Commented May 27, 2021 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()? Commented May 27, 2021 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). Commented May 27, 2021 at 18:04
  • 1
    For now I suggest reading What is the difference between a variable, object, and reference?. (BTW arrays are also considered as objects. new keyword creates object of specified type like new Car(..) new Person() new char[0]). Commented May 27, 2021 at 18:06

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Can you please stress on this more.
Almost: you never get access to the internal array (check yourself: editing the returned array does not affect the String). You get a copy.
honestly, didn't realize internal array is byte[] :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.