Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
String type in Java is Immutable i.e. if you do any operation it creates a new string. So if dealing with large number of Strings using StringBuffer is a better alternative.
Storing :: We can store strings in a trie.
is there a way to save strings in some other format inorder to save on bytes occupied by strings ? u r working on limited memory .
Drawback of String is being the immutable that you have to create a new instance all time. As suggested stringbuffer is the way to go.
A trie could be used on this as well - but the question specifically mentioned that there is no space - so I would go by something space worthy which would be compression.
Strings are immutable. Any new string defined or changed (I.E. by calling any method on string) always creates a new string. All these new strings are present in common string pool (for the sake of re-usability). So, use string builder to keep one string and do a lot of changes to it without filling up the string pool. Event better, use char arrays for extreme efficiency.
As far as saving space goes, use an encoding which can accommodate all your character s in minimum bytes, plus, use compression algorithms (will cause CPU overhead).
It's called compression. Not everything can be compressed in a way that will produce gains, but often text written in a natural language can benefit at least somewhat from compression.
- Anonymous July 07, 2012