Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a String is immutable, then why do you have to call a method to get the length instead of just accessing a variable, like array.length?

Tags:

java

string

It seems to me that calling string.length() each time takes significantly longer than just accessing a variable.

like image 297
Jrom Avatar asked Jul 29 '11 05:07

Jrom


1 Answers

String implements interface CharSequence, which in turn defines length method. You couldn't do the same with variables since variables can't be abstract or overridden.
As other people say, Java is using interfaces heavily.

like image 77
Nikita Rybak Avatar answered Oct 01 '22 05:10

Nikita Rybak