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,
Tag: string
How do I read / convert an InputStream into a String in Java?
If you have a java.io.InputStream object, how should you process that object and produce a String? Suppose I have an InputStream that contains text data, and I want to convert it to a String, so for example I can write that to a log file. What is the easiest way to take the InputStream and convert it to a String?
Why does Java’s hashCode() in String use 31 as a multiplier?
Per the Java documentation, the hash code for a String object is computed as: using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. Why is 31 used as a multiplier? I understand that the multiplier should be a relatively large prime number. So why not 29,
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