learner
learner

Reputation: 1

Java- Character array accepting entire string even if declared of lesser size

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?

Upvotes: 0

Views: 55

Answers (1)

Dragonborn
Dragonborn

Reputation: 1815

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);

Upvotes: 1

Related Questions