Skip to content

Tag: string

Prevent round off in String.format(“%.2f”, doubleValue) in Java

How do I prevent String.format(“%.2f”, doubleValue); from rounding off (round half up algorithm) instead of just truncating it? e.g. after formatting, I just want to discard the last digit, I know there are other ways to do this, I just want to know if this is possible using the String.format. Answer You can always set the rounding mode: and

What is meant by immutable?

This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie. Can somebody clarify what is meant by immutable? Why is a String immutable? What are the advantages/disadvantages of the immutable objects? Why should a mutable object such as StringBuilder be preferred over String and vice-verse? A nice example (in Java) will

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