Skip to content
Advertisement

Tag: string

Why can’t I use switch statement on a String?

Is this functionality going to be put into a later Java version? Can someone explain why I can’t do this, as in, the technical way Java’s switch statement works? Answer Switch statements with String cases have been implemented in Java SE 7, at least 16 years after they were first requested. A clear reason for the delay was not provided,

What is meant by immutable?

What exactly does immutable mean – that is, what are the consequences of an object being mutable or immutable? In particular, why are Java’s Strings immutable? My understanding is that the StringBuilder type is something like a mutable equivalent to String. When would I use StringBuilder rather than String, and vice-versa? Answer Immutable means that once the constructor for an

How do I count the number of occurrences of a char in a String?

I have the string I want to count the occurrences of ‘.’ in an idiomatic way, preferably a one-liner. (Previously I had expressed this constraint as “without a loop”, in case you’re wondering why everyone’s trying to answer without using a loop). Answer My ‘idiomatic one-liner’ for this is: Why write it yourself when it’s already in commons lang? Spring

How to split a string with any whitespace chars as delimiters

What regex pattern would need I to pass to java.lang.String.split() to split a String into an Array of substrings using all whitespace characters (‘ ‘, ‘t’, ‘n’, etc.) as delimiters? Answer Something in the lines of This groups all white spaces as a delimiter. So if I have the string: This should yield the strings “Hello” and “World” and omit

How to generate a random alpha-numeric string

I’ve been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would “likely” be unique over 500K+ generation (my needs don’t really require anything much more sophisticated). Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a

Advertisement