Get an OutputStream into a String

I would use a ByteArrayOutputStream. And on finish you can call: new String( baos.toByteArray(), codepage ); or better: baos.toString( codepage ); For the String constructor, the codepage can be a String or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8. The method toString() accepts only a String as a codepage parameter (stand Java 8).

Difference between string object and string literal

When you use a string literal the string can be interned, but when you use new String(“…”) you get a new string object. In this example both string literals refer the same object: String a = “abc”; String b = “abc”; System.out.println(a == b); // true Here, 2 different objects are created and they have different references: String … Read more

java: use StringBuilder to insert at the beginning

StringBuilder sb = new StringBuilder(); for(int i=0;i<100;i++){ sb.insert(0, Integer.toString(i)); } Warning: It defeats the purpose of StringBuilder, but it does what you asked. Better technique (although still not ideal): Reverse each string you want to insert. Append each string to a StringBuilder. Reverse the entire StringBuilder when you’re done. This will turn an O(n²) solution … Read more

String is immutable. What exactly is the meaning?

Before proceeding further with the fuss of immutability, let’s just take a look into the String class and its functionality a little before coming to any conclusion. This is how String works: [java]String str = "knowledge";[/java] This, as usual, creates a string containing “knowledge” and assigns it a reference str. Simple enough? Lets perform some more functions: [java] String s = str; // … Read more