Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to access a substring of a Java String without creating a new String object?

Tags:

java

string

I just want to read it as its own "String" but a view is fine -- I don't need it to be materialized as a separate object. I'd prefer to not incur the overhead of creating a new object.

like image 741
trikk Avatar asked Dec 18 '25 02:12

trikk


1 Answers

You can access the characters one by one with the charAt() method. If you already have a character array allocated, you could copy the characters into it, and use that. Neither of these would involve creating any more objects. But that's about it.

Note that if you call substring(), the String class doesn't copy the underlying char[] -- it only creates the new String object itself, and they share the char[].

like image 138
Ernest Friedman-Hill Avatar answered Dec 19 '25 14:12

Ernest Friedman-Hill