StringBuffer over String Class

String myStr = “SchoolHoood”;
myStr = myStr.concat(” – Learn to Enjoy”);
myStr = myStr.concat(” – For 5 to 55.”);

Since strings are immutable in java, the above codes makes 2 hanging string objects in heap namely:
1. SchoolHood
2. SchoolHood – Learn to enjoy
Of course the final string “SchoolHoood – Learn to Enjoy – For 5 to 55.” will have a reference var as myStr.

If lot many modifications are required on a string, StrinBuilder/StringBuffer should be preferred over just plain String class. This is to avoid the loosing of strings in the heap-pool and hence saving the memory. For detail read Immutable String in Java.

The above code could be rewritten as:
StringBuffer myStrBuff = nw StringBuffer(“SchoolHoood”);
myStrBuff.append(” – Learn to Enjoy”);
myStrBuff.append(” – For 5 to 55.”);

Since append method is invoked on the StringBuffer object “myStrBuff” itself, hence append happens to be on the same string. Thus StringBuffer/SringBuilder objects can be modified over and over again without leaving behind a discarded String objects.

These two methods are used widely in case of FILE I/O because there you need to treat a large amount of data as a single unit. Say for example , while reading a file line by line — youStrBuilderObj.append(lineContent) — will make you to deal with data easily.

String to Integer

In JAVA programming it is very frequent demand of converting an int/Integer to String.

Below snapshot shows how this is done. Easy to remember.
Integer to String

public class DataTypeCoversionDemo {
            private static String strVar = "11";
            private static int intVar = 22;
            private static Integer integerVar = 222;
      public static void main(String[] args) {      

      public static void convertInt_String(){
            // ********* Integer to int ********** //
            Integer tInteger = Integer.valueOf(intVar);
            int tSimpleIntValue = tInteger.intValue();

            System.out.println("Simple Int to Integer  :- " + tInteger); //22      
            System.out.println("Integer to Simple int :- " + tSimpleIntValue); //22

            // ********* int to String ********* //
            String tString = String.valueOf(intVar);
            int tInt = Integer.parseInt(strVar);

            System.out.println("Simple Int to String :- " + tString); //22
            System.out.println("String to Simple Int :- " + tInt); //11

            // ******* Integer to String ******* //  
            String tString2 = integerVar.toString();
            Integer tInteger2 = Integer.parseInt(strVar);        

            System.out.println("Integer to String :- " + tString2); //222
            System.out.println("String to Integer :- " + tInteger2); //11