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.

Advertisements

TCF { Try-Catch-Finally }

This morning I was going through an article try-catch-finally (TCF) in Java.
Suddenly got some weird thoughts.

Plugged myself to Eclipse to dive into the right answers. Here are few bullets:

1. Can try exist all alone ( without catch, without finally) ?
ANS: try block {1} i.e 1 time
catch block * i.e 0 or N times
finally block ? i.e 0 or 1 time

2. Can I put just try block in an “if” condition leaving catch block independent?

if(alive){
  try{
         //dive into pacific ocean once more
      {
} // end of if
catch(Exception e) {
     // Reported dead before entering to pacific
}

ANS: No. You cant associate catch without if.

3. I want to write the below JDBC scenario in below manner:

try block -> Establish a connection to the database & submit a query to the MySQL database for execution
catch block -> If connection failure or query failure happens, will give a message to the end user.
finally block -> close the database connection at any cost

Not a big deal, my code is ready. Here I go………

public class TtryCatchFinallyDemo {

	public static void main(String[] args) {
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "password");
			stmt = con.createStatement();
			rs = stmt.executeQuery("Select * FROM user");
			while (rs.next()) {
				System.out.println(rs.getString("User2")); //Mistaken purposely- User2 instead "User" // PlaceHolder_00
			}
			con.close(); // PlaceHolder_01
		}
		catch (Exception e) {
			System.out.println("Exception Occurred :- " + e.getMessage());
			// PlaceHolder_02
		}finally{
                         con.close; // PlaceHolder_03
			}
		}
	}
}

Looks absolutely fine. Right?

No. It has error.
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Unhandled exception type SQLException

Assume the error happens at PlaceHolder_00, control will move to the exception block and then finally block.

Writing con.close() at PlaceHolder_01 will not close the database connection. Thus I need to close it at finally block at PlaceHolder_03.
But will it serve my purpose?

Thus the correct way of doing it would be

Modify the above code to

finally{
			try{
				System.out.println(con.isClosed());  // false
				con.close();
				System.out.println(con.isClosed()); // true
				con = null;
			}catch(Exception e){// PlaceHolder_03
			     System.out.println("Exception occurred!");
			}
		}

But again re-writing try catch withing finally wont be a good idea.

Hopefully setting the con to null will solve everything.

finally{
   con = null;
}

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) {      
          convertInt_String();   
      }

      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
      }
}

Chars are digits?

When I was a kid for my computer classes, my master said – “Computer understands only binary digits”.

I thought – he is bluffing.  

I was into a position to digest — Okay computer understands 1 as 1, 2 as 2 — Coz I had a knowledge of decimal to binary conversion.

1 — 0000 0000 0000 0001 ( for 16 bit m/c)

5 — 0000 0000 0000 0110 ( for 16 bit m/c)

But I was not ready to accept the way my teacher said. I ask myself – How come “A” will be represented as some 1, 2, 3, 4 – in digit format. So if I write “Hello World” — does it mean ?- Is this something like 4324421625834  or 0010 1000 0011 1100…..

After 4 years of my engineering and 6 years of IT experience, I was going through the “Primitive Data Types” in the book “Java Certification by Khalid A. Mughal & Rolf W. Rasmussen”.

 The diagram in the book has given me a big shock!!!!!!!!!!!!!!!!!  
               
Primitive Data Types in Java
 How come the char data type is grouped under “Integral types”?

 After reading carefully I came to know — Oh it’s an unsigned number.

So what — still it’s a number!

After rehearsing the same line again and again –> “Characters are represented by the data type char. Their values are unsigned integers that denote all the 65536 (2 pow 16) characters in the 16-bit Unicode character set. This includes letters, digits, and special characters.

Ok, so got it finally. What does the line say … even if it is a character that will be stored as some integer values ( of course unsigned).

 So to say further ‘A’ is infact \u0041 [\u for Unicode, followed by for digit Hexadecimal number  – equivalent to 65 in Decimal ]

 This is where A is interpreted as \u0041 or 65 in decimal or 0000 0000 0110 0001 in binary.

Once A is a digit, your computer will understand it as

‘A’ – 65 – 0000 0000 0110 0001

‘a’ – 97 – 0000 0000 0100 0001

This explanation also proves that why char has been grouped under Integral types in the diagram.

And also my master was right -“Computer understands only binary digits”.

 Now look at the below Java code now:

public class CharTypeDemo {
	public static void main(String[] args) {
		char char1 = 'a';  // I will be stored in computes as 61 only, but you will be able to see me as it is
		char char2 = '\u0061'; // because of "\\u" plz put my converted charter value
		
		int int1 = 'a';  // should be a type conversion here from char to int
		int int2 = 97;
		
		System.out.println("char1   char2   int1  int2");
		System.out.println(char1 + "\t" + char2 + "\t"  + int1 + "\t" + int2);	
	}
}

Output:

char1 char2 int1 int2
a a 97 97