Wednesday, 14 October 2015

Split string on the first white space occurence

If you only care about the space character (and not tabs or other whitespace characters) and only care about everything before the first space and everything after the first space, you can do it without a regular expression like this:

var str = "Hello India Jai Hind";
str.substr(0,str.indexOf(' ')); // "Hello"
str.substr(str.indexOf(' ')+1); // "India Jai Hind"

Note that if there is no space at all, then the first line will return an empty string and the second line will return the entire string. Be sure that is the behavior that you want in that situation (or that that situation will not arise).

Friday, 25 September 2015

How to clear File Input

You can just clone it and replace it with itself, with all events still attached:'

<input type="file" id="control">


var input = $("#control");

function something_happens() {

Tuesday, 11 August 2015

How System.out.println() really works

  • Commonly asked by Java beginners is the question, “How does System.out.println() work?”; 
  • Most of the relevant code can be found on OpenJDK, which is the primary implementation of Java itself. System.out.println() may be implemented completely differently on other Java platforms.

I will warn you now that this article is very long and not for the easily bored.

First steps

  • Our first step in figuring out how System.out.println works is by first understanding what System.out is and how it came to be.
  • Let’s take a look through the OpenJDK’s Mercurial online repository. Digging around a bit, we find In this file System.out is declared:

public final static PrintStream out = nullPrintStream();

But when we find the code for nullPrintStream():

private static PrintStream nullPrintStream() throwsNullPointerException{      
if (currentTimeMillis() > 0) {        
  return null;    
  throw new NullPointerException();


  • So nullPrintStream() simply returns null or throws an exception. This can’t be it. What’s going on here?

The answer can be found in the function initializeSystemClass(), also in

FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);

setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));

  • There’s a lot of stuff going on in this code. I’m going to refer back to this two lines of code later, but setOut0() is what actually initializes System.out.
  • The function setOut0() is a native function. We can find its implementation in System.c:
Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream)
    jfieldID fid =
    if (fid == 0)

  • This is pretty standard JNI code that sets System.out to the argument passed to it.
  • At first all this deal with setting System.out to nullPrintStream() and later setting it with JNI seems entirely unnecessary. But this is actually justified.
  • In Java, static fields are initialized first, and everything else comes after. So even before the JVM and the System class is fully initialized, the JVM tries to initialize System.out.
  • Unfortunately at this point the rest of the JVM isn’t properly initialized so it’s impossible to reasonably set System.out at this point. The best that could be done would be to set it to null.
  • The System class, along with System.out is properly initialized in initializeSystemClass() which is called by the JVM after static and thread initialization.

There is a problem, however. System.out is final, meaning we cannot simply set it to something else in initializeSystemClass(). There’s a way around that, however. Using native code, it is possible to modify a final variable.

Friday, 24 July 2015

JDBC Driver in Java : Difference between Type 1, 2, 3 and 4

  • One of the oldest Java interview question is what is difference between different types of JDBC drivers e.g. what is difference between type 1, type 2, type 3 or type 4 drivers? Sometime also asked as how do you choose between different JDBC driver?
  • When to use type 3 over type 4 driver etc. Its 2015 now and I doubt anyone is using JDBC driver other than type 4 for connecting to database, but let's see how to answer this question when you face it during interview. 
  • Difference between different types of JDBC driver comes from the fact how they work, which is basically driven by two factor, portability and performance. 
  • Type 1 JDBC driver is the poorest in terms of portability and performance, while type 4 JDBC driver is highly portable and gives best performance. 
  • You will learn more differences between different JDBC drivers as we go along. Since database is very important and almost all Java application uses database in some form or other, its important to learn JDBC well. 
  • If you are a beginner started to learn Java and struggling with JDBC then I suggest you to take a look at Practical Database Programming with Java By Ying Bai. It's one of the rarest book, which covers Java database connectivity well,

What is JDBC Driver in Java?

  • A driver is nothing but software required to connect to a database from Java program. JDBC is just an API, which Java has designed and onus to implement this API lies on different vendor because different database works in different way, they internally use different protocols
  • So MySQL gives its own implementation of JDBC, we call it MySQL JDBC driver and we use it when we want to connect to MySQL database from Java program
  • Similarly Oracle, SQL SERVER, Sybase and PostgreSQL has provided their own implementation of JDBC API to connect them. 
  • Since Java program uses JDBC API, they are portable across different database, all you need to do is change the JDBC driver, which is just a JAR file if you are using type 4 JDBC driver.
  •  By the way, migrating to database is not as easy, especially if you are using any proprietary feature of database, but if you ANSI SQL and not using any database specific feature, its easy.

How many drivers are there in JDBC?

  • There are total 4 types of JDBC drivers exists in Java. They are known as type 1, 2, 3, and 4 drivers. In order to understand difference between different JDBC drivers, first and most important thing to understand is why Java has so many types of JDBC drivers? 
  • Why not just one? the answer lies in portability and performance. The first JDBC driver is known as type 1 JDBC driver and the most recent one is known as type 4 JDBC driver. 
  • There has been some talk about type 5 JDBC driver but I have not heard anything concrete about it from Oracle or any other reliable source. So, type 4 JDBC driver is still the latest one.

                 Difference between different JDBC drivers in Java

What is type 1 driver in JDBC?

  • This is the oldest JDBC driver, mostly used to connect database like MS Access from Microsoft Windows operating system. Type 1 JDBC driver actually translate JDBC calls into ODBC (Object Database connectivity) calls, which in turn connects to database. 
  • Since it acts as bridge between JDBC and ODBC, it is also known as JDBC ODBC bridge driver. This driver had very poor performance because of several layers of translation which took place before your program connects to database. 
  • It has also less portable because it relies on ODBC driver to connect to database which is platform dependent. It is now obsolete and only used for development and testing, I guess Java 7 even removed this driver from JDK.

What is type 2 driver in JDBC?

  • This was the second JDBC driver introduced by Java after Type 1, hence it known as type 2. In this driver, performance was improved by reducing communication layer. Instead of talking to ODBC driver, JDBC driver directly talks to DB client using native API. 
  • That's why its also known as native API or partly Java driver. Since it required native API to connect to DB client it is also less portable and platform dependent. 
  • If native library e.g. ocijdbc11.dll, which is required to connect Oracle 11g database is not present in client machine then you will get java.lang.UnsatisfiedLinkError: no dll in java.library.path error.  Performance of type 2 driver is slightly better than type 1 JDBC driver.

What is type 3 driver in JDBC?

  • This was the third JDBC driver introduced by Java, hence known as type 3. It was very different than type 1 and type 2 JDBC driver in sense that it was completely written in Java as opposed to previous two drivers which were not written in Java. 
  • That's why this is also known as all Java driver. This driver uses 3 tier approach i.e. client, server and database. So you have a Java client talking to a Java server and Java Server talking to database. 
  • Java client and server talk to each other using net protocol hence this type of JDBC driver is also known as Net protocol JDBC driver. This driver never gained popularity because database vendor was reluctant to rewrite their existing native library which was mainly in C and C++

What is type 4 JDBC driver?

  • This is the driver you are most likely using to connect to modern database like Oracle, SQL Server, MySQL, SQLLite and PostgreSQL
  • This driver is implemented in Java and directly speaks to database using its native protocol. 
  • This driver includes all database call in one JAR file, which makes it very easy to use. All you need to do to connect a database from Java program is to include JAR file of relevant JDBC driver. Because of light weight, this is also known as thin JDBC driver. 
  • Since this driver is also written in pure Java, its portable across all platform, which means you can use same JAR file to connect to MySQL even if your Java program is running on Windows, Linux or Solaris. Performance of this type of JDBC driver is also best among all of them because database vendor liked this type and all enhancement they make they also port for type 4 drivers.

Difference between type 1 and type 2 JDBC driver?

  • Though both type 1 and type 2 drivers are not written in Java, there was some significant difference between them. Type 2 driver has better performance than type 1 driver because of less layer of communication and translation. 
  • As opposed to type 1 JDBC driver, in which JDBC calls are translated into ODBC calls before they go to database, type 2 JDBC driver directly connect to db client using native library.

Difference between type 2 and type 3 JDBC driver?

  • Main difference between type 2 and type 3 JDBC driver is that as opposed to type 2 driver, type 3 is completely written in Java. 
  • Another difference which comes from this fact is that type 3 driver is more portable than type 1 and type 2 drivers because it doesn't require any native library on client side to connect to database. In terms of architecture, this was 3 tier architecture and uses net protocol for client server communication.

Difference between type 3 and type 4 JDBC driver?

  • Main difference between type 3 and type 4 JDBC driver was removal of 3 tier architecture. Type 4 JDBC driver directly connect to database using their native protocol as opposed to net protocol used by type 3 driver. 
  •  Though both type 3 and type 4 driver is written in Java. Another key difference is ease of use, type 4 drivers just require one JAR file into classpath in order to connect to db. Performance of type 4 JDBC driver is also better than type 3 driver because of direct connectivity to database as opposed to 3 tier architecture of type 3 driver.

When to use different types of JDBC driver?

  • You should always use type 4 JDBC driver, there is hardly any situation when you need to go to previous version of JDBC driver. Though, if you want to connect to Oracle database using TNS name using OCI client, you need to use type 2 JDBC driver also known as thick JDBC driver. 
  • That requires database native client library e.g. ocijdbc11.dll and if that's not present in the machine then your Java program will throw java.lang.unsatisfiedlinkerror no ocijdbc11 in java.library.path error at run time. 

*Summary of above all story ...

  • That's all about difference between type 1, 2, 3, and type 3 JDBC driver in Java. JDBC drivers are evolved in Java from less portable to most portable and from low performance to high performance. 
  • Type 1 JDBC driver is the oldest while type 4 JDBC driver is the latest. In real world, you will be mostly likely using type 4 JDBC driver, which is bundled in a JAR file. Just make sure to put them into your Java application's classpath when you connect to database from Java program.

Insert Image in database

Require Driver : mysql-connector-java-5.0.8-bin.jar

Table Structure : 

CREATE TABLE myImageFiles (
  id int(11) NOT NULL auto_increment,
  document blob

Friday, 12 June 2015

How do I conditionally apply CSS styles in AngularJS?

Angular provides a number of built-in directives for manipulating CSS styling conditionally/dynamically:
  • ng-class - use when the set of CSS styles is static/known ahead of time
  • ng-style - use when you can't define a CSS class because the style values may change dynamically. Think programmable control of the style values.
  • ng-show and ng-hide - use if you only need to show or hide something (modifies CSS)
  • ng-if - new in version 1.1.5, use instead of the more verbose ng-switch if you only need to check for a single condition (modifies DOM)
  • ng-switch - use instead of using several mutually exclusive ng-shows (modifies DOM)
  • ng-disabled and ng-readonly - use to restrict form element behavior
  • ng-animate - new in version 1.1.4, use to add CSS3 transitions/animations
The normal "Angular way" involves tying a model/scope property to a UI element that will accept user input/manipulation (i.e., use ng-model), and then associating that model property to one of the built-in directives mentioned above.
When the user changes the UI, Angular will automatically update the associated elements on the page.

Q1 sounds like a good case for ng-class -- the CSS styling can be captured in a class. ng-class accepts an "expression" that must evaluate to one of the following:
  1. a string of space-delimited class names
  2. an array of class names
  3. a map/object of class names to boolean values
Assuming your items are displayed using ng-repeat over some array model, and that when the checkbox for an item is checked you want to apply the pending-delete class:
<div ng-repeat="item in items" ng-class="{'pending-delete': item.checked}">
   ... HTML to display the item ...
   <input type="checkbox" ng-model="item.checked">
Above, we used ng-class expression type #3 - a map/object of class names to boolean values.

Q2 sounds like a good case for ng-style -- the CSS styling is dynamic, so we can't define a class for this. ng-style accepts an "expression" that must evaluate to:
  1. an map/object of CSS style names to CSS values
For a contrived example, suppose the user can type in a color name into a texbox for the background color (a jQuery color picker would be much nicer):
<div class="main-body" ng-style="{color: myColor}">
   <input type="text" ng-model="myColor" placeholder="enter a color name">

Fiddle for both of the above. The fiddle also contains an example of ng-show and ng-hide. If a checkbox is checked, in addition to the background-color turning pink, some text is shown. If 'red' is entered in the textbox, a div becomes hidden.

Wednesday, 10 June 2015

Top Ten Things Every Java Programmer Should Know

These are in no particular order, but these are things that all Java programmers should probably know.
  1. Who Invented Java, and when?
    James Gosling, at Sun Labs, around 1992; the group was building a set-top box and started by "cleaning up" C++ and wound up with a new language and runtime. 
  2. What does Java stand for?
    Java is not an acronym (not even Just Another Vague Acronym :-)). The language was first named Oak, after the tree outside James' window. The lawyers found a computer company called Oak so, legend has it, the gang went out to the local cafe to discuss names and wound up naming it Java; the "0xCafeBabe" magic number in the class files was named after the Cafe where the Java team used to go for coffee.
  3. What is the JLS?
    JLS is The Java Language Specification. Every developer should buy or download (free) this specification and read it, a bit at a time.
  4. How do changes get into Java? JCP (Java Community Process).
  5. Why is there no printf-like function in Java?
    Actually there are! This was fixed in Java 5; see Java Cookbook (2nd Edition) Chapter 9. Java 5 (J2SE 1.5) includes printf (and scanf), String.format(), and lots more.
  6. What is the GOF book?
    The Gang Of Four book is entitled Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. This is a very good book. You should read it. Not when you're just learning Java, but when you've let it sink in for about six months.
  7. What other Java book do I need?
  8. What is the Java Cookbook?
    That's my own book of Java recipes (for the programming language, not the coffee, but some bookstores still wind up listing it under Cooking).
  9. What other Java sites do I need to know about?
  10. What else do I need to know? Everything! But nobody can know everything about Java - the subject is now too vast. Imagine somebody saying that they know everything about every single Microsoft product and technology. If someone like that calls me, I'm always out.

How to draw an html table with diagonal lines and diagonal text?

The main building blocks are:
  • A nicely marked up <table>
  • A pseudo element border with skew to get the basic shape
  • A rotate on the span that contains the header text.
The concept is pretty basic, the pseudo elements and spans are positioned using position: absolute and they are positioned relative to their parent <th> headers which have position: relative
Here is the example!
Here is what it looks like in Chrome / Firefox / IE10+. IE 8 - 9 should work with their proprietary filters.
Here is the HTML / CSS:
* {
    margin: 0;
    padding: 0;

body {
    background: #FFF;
table {
    border-collapse: collapse;
    margin: 50px 0 0 50px;
    border-top: solid 1px #000;
    position: relative;

/* Very top border */
 table:before {
    display: block;
    position: absolute;
    top: -20px;
    left: 120px;
    height: 20px;
    width: 240px;
    border: solid 1px #000;
    border-bottom: none;

/* Far right headers top border (it's outside the table) */
 table:after {
    display: block;
    position: absolute;
    border-top: solid 1px #000;
    width: 101px;
    right: -101px;
    top: 0;

     - Apply header background/font colour 
     - Set base z-index for IE 9 - 10
 thead, th:before {
    background: #03a9f4;
    color: #FFF;
    z-index: 1;

/* min-width and max-width together act like a width */
 th {
    min-width: 60px;
    max-width: 60px;
    position: relative;
    height: 100px;

/* Pseudo element borders */
 th:before {
    display: block;
    position: absolute;
    top: 0;
    right: -50px;
    height: 100px;
    width: 60px;
    border: solid 1px #000;
    border-right: none;
    border-top: none;
    transform: skew(-45deg);
    border-bottom: none;

/* Apply the right border only to the last pseudo element */
 thead th:last-child:before {
    border-right: solid 1px #000;

/* Apply the top border only to the first rows cells */
 tbody tr:first-child td {
    border-top: solid 1px #000;

     - Rotate and position headings
     - Padding centers the text vertically and does the job of height
     - z-index ensures that the text appears over the background color in IE 9 - 10
 th span {
    transform: rotate(-45deg);
    display: inline-block;
    vertical-align: middle;
    position: absolute;
    right: -70px;
    bottom: 29px;
    height: 0;
    padding: 0.75em 0 1.85em;
    width: 100px;
    z-index: 2;

/* Create first two th styles */
 th:nth-child(1), th:nth-child(2) {
    border: solid 1px #000;
    border-top: none;
    border-bottom: none;
th:nth-child(2) {
    border-right: none;
th:nth-child(1):before, th:nth-child(2):before {
    display: none;

td {
    border: solid 1px #000;
    border-bottom: none;
    border-top: none;
    height: 20px;
    text-align: center;
tfoot {
    border: solid 1px #000;
HTML Code :  

Create diagonal border of a cell


<div id="square">
      <span id="room">ROOM TYPE</span>
       <span id="hosp">HOSPITALITY</span></div>
<div id="line"></div>


#square {
    position: absolute;
    top: 100px;
    left: 100px;
    background: #3b2a32;
    border: 2px solid #ad1b59;
    color: #ad1b59;
    height: 200px;
    width: 400px;
    font-family: arial, verdana;
    font-size: 22px;
    font-weight: bolder;

#room {
    display: block;
    position: absolute;
    top: 50px;
    left: 220px;

#hosp {
    display: block;
    position: absolute;
    top: 140px;
    left: 50px;

#line {
    position: absolute;
    top: 190px;
    left: 33px;
    height: 200px;
    width: 450px;
    border-top: 2px solid #ad1b59;   
    -webkit-transform: rotate(26.5deg);
       -moz-transform: rotate(26.5deg);
        -ms-transform: rotate(26.5deg);
         -o-transform: rotate(26.5deg);
            transform: rotate(26.5deg);

Thursday, 4 June 2015

HashMap with multiple values under the same key

  1. Use a map that has a list as the value. Map<KeyType, List<ValueType>>.
  2. Create a new wrapper class and place instances of this wrapper in the map. Map<KeyType, WrapperType>.
  3. Use a tuple like class (saves creating lots of wrappers). Map<KeyType, Tuple<Value1Type, Value2Type>>.
  4. Use mulitple maps side-by-side.


1. Map with list as the value
// create our map
Map<string, List<Person>> peopleByForename = new HashMap<string, List<Person>>();    

// populate it
List<Person> people = new ArrayList<Person>();
people.Add(new Person("Bob Smith"));
people.Add(new Person("Bob Jones"));
peopleByForename.Add("Bob", people);

// read from it
List<Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs[0];
Person bob2 = bobs[1];
2. Using wrapper class
// define our wrapper
class Wrapper {
    public Wrapper(Person person1, Person person2) {
       this.person1 = person1;
       this.person2 = person2;

    public Person getPerson1 { return this.person1; }
    public Person getPerson2 { return this.person2; }

    private Person person1;
    private Person person2;

// create our map
Map<string, Wrapper> peopleByForename = new HashMap<string, Wrapper>();

// populate it
Wrapper people = new Wrapper()
peopleByForename.Add("Bob", new Wrapper(new Person("Bob Smith"),
                                        new Person("Bob Jones"));

// read from it
Wrapper bobs = peopleByForename["Bob"];
Person bob1 = bobs.Person1;
Person bob2 = bobs.Person2;
3. Using a tuple
// you'll have to write or download a Tuple class in Java, (.NET ships with one)

// create our map
Map<string, Tuple2<Person, Person> peopleByForename = new HashMap<string, Tuple2<Person, Person>>();

// populate it
peopleByForename.Add("Bob", new Tuple2(new Person("Bob Smith",
                                       new Person("Bob Jones"));

// read from it
Tuple<Person, Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs.Item1;
Person bob2 = bobs.Item2;
4. Multiple maps
// create our maps
Map<string, Person> firstPersonByForename = new HashMap<string, Person>();
Map<string, Person> secondPersonByForename = new HashMap<string, Person>();

// populate them
firstPersonByForename.Add("Bob", new Person("Bob Smith"));
secondPersonByForename.Add("Bob", new Person("Bob Jones"));

// read from them
Person bob1 = firstPersonByForename["Bob"];
Person bob2 = secondPersonByForename["Bob"];