-1

please advise below is the code to extract the first 4 characters from the string as shown below..

String external = ak.getReference();    
String s= external.substring(0,4);

Can I wrap this into one so that no extra String s need to be created and finally string external will have four initial characters in one go

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108

2 Answers2

3

Well, you can always chain the method calls...

String s = ak.getReference().substring(0,4);

... But that doesn't mean that an extra string won't be created, starting with Java 7u6 the substring() method will return a new String object with a freshly allocated char[] (see this post). You're just eliminating an intermediate local variable, that's all.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

Same strings are going to be created no matter what. Compiler will optimize that anyways. Otherwise the comment of @ZouZou is correct.

String external = ak.getReference().substring(0,4);
akostadinov
  • 17,364
  • 6
  • 77
  • 85