<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener('load', function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <div id="navbar-iframe-container"></div> <script type="text/javascript" src="https://apis.google.com/js/platform.js"></script> <script type="text/javascript"> gapi.load("gapi.iframes:gapi.iframes.style.bubble", function() { if (gapi.iframes && gapi.iframes.getContext) { gapi.iframes.getContext().openChild({ url: 'https://www.blogger.com/navbar.g?targetBlogID\x3d1074803565153692547\x26blogName\x3dInnoLearning\x26publishMode\x3dPUBLISH_MODE_BLOGSPOT\x26navbarType\x3dBLUE\x26layoutType\x3dCLASSIC\x26searchRoot\x3dhttps://innolearning.blogspot.com/search\x26blogLocale\x3den_US\x26v\x3d2\x26homepageUrl\x3dhttp://innolearning.blogspot.com/\x26vt\x3d2174717628392424844', where: document.getElementById("navbar-iframe-container"), id: "navbar-iframe", messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER, messageHandlers: { 'blogger-ping': function() {} } }); } }); </script>

InnoLearning

Asynchronous Call in Java
Tuesday, July 30, 2013

The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is thus very similar to a thread pool. In fact, the implementation of ExecutorService present in the java.util.concurrentpackage is a thread pool implementation:

   /**
     * Asynchronous call to invoke any method
     * * *
     * @author Manesh Abhimanyu
     * @param String Input 1
     * @param String Input 2
     */
    public void asyncServiceMethod( final String input1, final String input2)
    {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        try {
            Runnable task = new Runnable(){
                public void run()
                {
                    try {
                        invokeMyMethod( input1, input2 );
                    } catch ( Exception ex ) {
                          // handle error which cannot be thrown back
                    }
                }
            };
            executor.execute( task );
        } catch ( Exception e ) {
            // handle error which cannot be thrown back
        }  finally {
            // gargabe collect
            executor.shutdown();
        }
    }






More reading:
Service Execute API


Labels: , , , , , ,

posted by MIGHTYMAK @ 11:52 PM, ,




Different ways of creating objects in Java
Saturday, March 3, 2012

1. Using new keyword
This is the most common way to create an object in java. In this, we will be using the new operator which will allocates the memory space and initialize the field with default value. Then it executes the code inside the specified constructor which normally re-writes the default values with the value inside the constructor.
MyObject object new MyObject();

2. Using Class.forName()
Generally we use this while creating a database connection. If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object (MyObject) Class.forName( jcapsmentor.com.Manesh ).newInstance();
jcapsmentor.com.Manesh – is the class name

3. Using clone()
The clone() can be used to create a copy of an existing object. Object.clone() is a native method which translates into instructions for allocating the memory and copying the data.Even if you override the clone method then also you need to call the super.clone() method inside the overridden clone method. In this method a copy instruction is called and which copy the data from original object to clone object.
MyObject anotherObject new MyObject();
MyObject object anotherObject.clone();

4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form. It will uses the ‘new’ operator internally and always calls the default constructor.

ObjectInputStream inStream new ObjectInputStream(anInputStream );
MyObject object (MyObject) inStream.readObject();

5. Using class loader
one more is through creation of object using classloader like
this.getClass().getClassLoader().loadClass( com.amar.myobject ).newInstance();

Labels: , , , , ,

posted by MIGHTYMAK @ 8:48 PM, ,




Simple steps to Self Sign the JAR through command prompt
Friday, June 4, 2010

Step 1: Generating Keystore, In the command prompt, cd to the path where we have placed the Jars and type:
keytool -genkey -keystore myKeystore -alias myself
(Note that if you run keytool it would prompt you for information like your First Name and Last Name, Organization, Business Unit, etc - I usually provide everything as blank (by pressing the return key at the prompt. At the end please provide "yes" reply for confirmation question)

Step 2: Self-Signing the key & cert in the keystore:
keytool -selfcert -alias myself -keystore myKeystore

Step 3: (Optional)
Confirming by listing all the values in the keystores which we have created.
keytool -list -keystore myKeystore

Step4: Signing the Jar. Below command will finally sign the UIManager.jar present in the current directory with the keystore which we have created in above steps.
jarsigner -keystore myKeystore UIManager.jar myself

Self-Signed Jar is ready!!!

Labels: , , , , ,

posted by MIGHTYMAK @ 9:06 PM, ,




JDBC interview questions and answers
Wednesday, December 16, 2009

1.What are the steps involved in establishing a JDBC connection? This action involves two steps: loading the JDBC driver and making the connection.

2.How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:

Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);

Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line of code:

Class.forName(”jdbc.DriverXYZ”);


3.What will Class.forName do while loading drivers? It is used to create an instance of a driver and register it with the
DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

4.How can you make the connection? To establish a connection you need to have the appropriate driver connect to the DBMS.
The following line of code illustrates the general idea:

String url = “jdbc:odbc:Fred”;
Connection con = DriverManager.getConnection(url, “Fernanda”, “J8?);

5.How can you create JDBC statements and what are they?A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object

Statement stmt = con.createStatement();

6.How can you retrieve data from the ResultSet?
JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

ResultSet rs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);
String s = rs.getString(”COF_NAME”);

The method getString is invoked on the ResultSet object rs, so getString() will retrieve (get) the value stored in the column COF_NAME in the current row of rs.

7.What are the different types of Statements?
Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall)

8.How can you use PreparedStatement? This special type of statement is derived from class Statement.If you need a
Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement’s SQL statement without having to compile it first.

PreparedStatement updateSales =
con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

9.What does setAutoCommit do?
When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:

con.setAutoCommit(false);

Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.

con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);

10.How do you call a stored procedure from JDBC?
The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open
Connection object. A CallableStatement object contains a call to a stored procedure.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

11.How do I retrieve warnings?
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an
application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a
Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these
classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object:

SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
System.out.println("n---Warning---n");
while (warning != null)
{
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
System.out.println("");
warning = warning.getNextWarning();
}
}

12.How can you move the cursor in scrollable result sets?
One of the new features in the JDBC 2.0 API is the ability to move a result set’s cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);

The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

13.What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?
You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened:

Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet srs =
stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
srs.afterLast();
while (srs.previous())
{
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}

14.How to Make Updates to Updatable Result Sets?
Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.

Connection con =
DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs =
stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Labels:

posted by MIGHTYMAK @ 5:01 PM, ,




Java 5 Interview Questions
Monday, November 16, 2009

What are the new features in Java 5 as compared to its earlier versions?

Java 2 Platform Standard Edition 5.0 was a major feature release. The following features were introduced in 5.0 since previous major release and that was 1.4.0.

Summary:
- Performance Enhancements
a.Garbage collection performance enhancements
b.Introduction to StringBuilder
c.Java 2D technology
d.Image I/O - Performance and memory

- Language Specific Features:
a.Generics
b.Enhanced for Loop
c.Autoboxing/Unboxing
d.Typesafe Enums
e.Varargs
f.Static Import
g.Metadata (Annotations)

The list is long which you can catch in detail at following URL:

Java 5 New Features

- What is Autoboxing/Unboxing and what are its advantages?

The conversion from primitive types to wrapper types objects is automated. This facility eleminates pain of manual conversion from primitive to wrapper types.
Boxing converts primitive values to objects of corresponding wrapper types.
Unboxing converts objects of wrapper types to values of corresponding primitive types.

Assignment Conversions on boolean and numeric types.
boolean boolValue = true;
byte b = 2;
short s = 2;
char c ='2';
int i = 2;

// Boxing
Boolean boolReference = boolValue;
Byte bReference = (byte) 4;
Short sReference = (short) 4;
// both byte and short type casting is to be done as int cannot be assigned to Byte and Short respectively
Character cReference = '4';
Integer iReference = 4;

// Unboxing
boolean boolValue1 = boolReference;
byte b1 = bReference;
short s1 = sReference;
char c1 = cReference;
int i1 = iReference;


The usage of autoboxing/unboxing can be found:
- In the if statement, condition can be Boolean.
- In the switch statement, the switch expression can be Character, Byte, Short or Integer.
- In the while, do-while and for statements, the condition can be Boolean.

posted by MIGHTYMAK @ 4:43 PM, ,




Cleared SCJP 5 with 78%
Friday, September 4, 2009

Following are some tips that i want to share with you all who are
planning to give SCJP 1.5

The exam which i gave consisted of 60 questions. Passing Percentage: 58%

Please master in rules of overriding and overloading , coz almost
all the questions test you knowledge of overloading and overriding

Make your concept clear for boxing , unboxing, wrapper to primitive ,
primitive to wrapper .

Criteria for selecting appropriate overloaded method when there are
2-3 methods overloaded with Object, Primitive, Var args as an
argument .

For file i/o , Serialization , get thorough with steps , you will
mostly get drag and drop questions on this section .


String , string buffer , String builder get familiar with API


Threading , Synchronization …… Generics and Collections -- get
thorough with Collection and Array API .HashCode and Equals
overriding , Generics concept , Generic classes


Special thanks to Devaka for ExamLabs simulator.***

The generics concept which is given in Kathy book is good but to get
thorough with each and every syntax when you use generics
we need some more material . There are many ways by which you can
declare generics (with warning and without warning compilation )
and use it . And you need to understand it more critically since here
we do have one more answer “compilation with warning or without
warning ” in the options given ;)


Othere imp topics were Enum , Var-args , Boxing unboxing and File I/0 ..
Since these are new topics included for scjp 1.5 . we need to focus more on these new topics .
(It is obvious that we should be good in other topics also but we can get so
many questions on these old topics from hundred of sites )

By referring questions which are given at the back of Kathy’s book you can
get exam cleared but if you want to get good score you have to go through
different types of questions on these new topics.

All The Best !!!!!!!!
(for those Who all are planning to give SCJP 1.5 )

- Manesh Koovappillil, SCJP

posted by MIGHTYMAK @ 10:48 PM, ,




J2EE or JEE, Java 5 or Java 1.5 - Is SUN Crazy?
Sunday, March 8, 2009

Will they take a J2EE professional or a JEE professional now is the thing I am worrying about. It is obvious for a technical person to know that J2EE and JEE are one and the same except for the HR persons! How do we go about convincing them? Many people including me, still are confused about the version and the mysterious number attached to the “Java” word. Let’s try to explore what actually goes on behind these mysteries. Check this out!

The product confusion
If you are still thinking that Java 2 meant version 2 of Java then you are being duped. Java 2 means version 1.4 of Java. I am still dumbfounded as to where Java 3 and Java 4 disappeared but I guess with the success of Java 5 they were buried in debris even before they born!
I was still in bewilderment until the web started to roar about Java 6. It took me a lot of time to actually sink in the fact whether Java 5 referred to version 1.5 of Java and Java 6 referred to version 1.6 of Java. This confusion was due to the use of Java 5.0 in some places. Are Java 5.0 and version 1.5 of Java one and the same?

The fact is that Sun makes use of dual naming convention for the same thing. One naming convention if for the product and one is for the developer. The official documents mentions,
Both version numbers “1.5.0″ and “5.0″ are used to identify this release of the Java 2 Platform Standard Edition. Version “5.0″ is the product version, while “1.5.0″ is the developer version. The number “5.0″ is used to better reflect the level of maturity, stability, scalability and security of the J2SE.

Really, a lot of maturity I say!

Developmental and Mental Destruction
SUN has not left people in peril by their naming conventions swapping not only in the case of Java releases but also in the names of the development kits. Earlier for programming in Java I used to download JDK which meant Java Development Kit. I don’t remember which version I was working upon. Maybe it was 1.1.

But when the Java 2 reign started I was asked to download J2SDK which means Java 2 Software Development Kit. SUN had finally realized that people were actually making softwares on Java!!
Java 2 was there to stay for a long time until the hue and uproar for Java 5 came in the picture. But wait, SUN was ready for another swap of naming to gain momentum with the success Java 5, which was reverting back to the name of JDK. The official document mentions, Due to significant popularity within the Java developer community, the development kit has reverted back to the name “JDK” from “Java 2 SDK”

Am I supposed to NOW assume if JDK still stands for the same meaning i.e “Java Development Kit“. No! Sun has more surprises for me. NOW, JDK actually means “J2SE Development Kit“. I still fear when this meaning will come crashing by! Did I hear some one shouting “Jean Claude Van Damn Karate Club” for JDK!!

Certifications Confusion
The certifications were also not spared. If you happen to prepare yourself for the SCBCD (Sun Certified Business Component Developer) exam, then you are in for trouble with making sure which exam are you heading for. I bet you would definitely get fumbled in this-
SCBCD 1.3 refers to you working with EJB 2.0
SCBCD 5.0 refers to you working with EJB 3.0

Didnt it all appear to SUN to keep the version of SCBCD same as the EJB we are working on?
The reality is that EJB 2.x was meant to work with J2EE 1.3 and since now after the up gradation of EJB to EJB 3.0 even the Java EE specifications have been upgraded to 5.0. Hence the certification number is the number of the Java EE specification and not of the version of EJB it is based on. Similarly it is SCJP 1.4 and SCWCD 1.4 which are for J2EE.. err.. I mean J2EE 1.4 or is it so.

Now you must have been enlightened about which version you are associated with. I will take some time to digest this completely. My head is still reeling with these numerological mumbo jumbo. Maybe there is something more in store for us. Before that hey, which version are you currently working on?

Labels: , ,

posted by MIGHTYMAK @ 7:12 AM, ,