Monday, September 19, 2011

Java String Concatenation

ref:http://javapapers.com/core-java/java-string-concatenation/

You have been told many times, don’t use + (java plus operator) to concatenate Strings. We all know that it is not good for performance. Have you researched it? Do you know what is happening behind the hood? Lets explore all about String concatenation now.
In the initial ages of java around jdk 1.2 every body used + to concatenate two String literals. When I say literal I mean it. Strings are immutable. That is, a String cannot be modified. Then what happens when we do
String fruit = "Apple"; fruit = fruit + "World";
In the above java code snippet for String concatenation, it looks like the String is modified. It is not happening. Until JDK 1.4 StringBuffer is used internally and from JDK 1.5 StringBuilder is used to concatenate. After concatenation the resultant StringBuffer or StringBuilder is changed to String.
When java experts say, “don’t use + but use StringBuffer”. If + is going to use StringBuffer internally what big difference it is going to make in String concatenation? Look at the following example. I have used both + and StringBuffer as two different cases. In case 1, I am just using + to concatenate. In case 2, I am changing the String to StringBuffer and then doing the concatenation. Then finally changing it back to String. I used a timer to record the time taken for an example String concatenation.
Look at the output (if you run this java program the result numbers might slightly vary based on your hardware / software configuration). The difference between the two cases is astonishing.
My argument is, if + is using StringBuffer internally for concatenation, then why is this huge difference in time? Let me explain that, when a + is used for concatenation see how many steps are involved:
  1. A StringBuffer object is created
  2. string1 is copied to the newly created StringBuffer object
  3. The “*” is appended to the StringBuffer (concatenation)
  4. The result is converted to back to a String object.
  5. The string1 reference is made to point at that new String.
  6. The old String that string1 previously referenced is then made null.
Hope you understand the serious performance issues and why it is important to use StringBuffer or StringBuilder (from java 1.5) to concatenate Strings.
Therefore you can see initially it was +, then StringBuffer came and now StringBuilder. Surely Java is improving release by release!

Example Java Source Code For String Concatenation

class Clock {
 
  private final long startTime;
 
  public Clock() {
    startTime = System.currentTimeMillis();
  }
 
  public long getElapsedTime() {
    return System.currentTimeMillis() - startTime;
  }
}
 
public class StringConcatenationExample {
 
  static final int N = 47500;
 
  public static void main(String args[]) {
 
    Clock clock = new Clock();
 
    //String to be used for concatenation
    String string1 = "";
    for (int i = 1; i <= N; i++) {
 
      //String concatenation using +
      string1 = string1 + "*";
    }
    //Recording the time taken to concatenate
    System.out.println("Using + Elapsed time: " + clock.getElapsedTime());
 
    clock = new Clock();
    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 1; i <= N; i++) {
 
      //String concatenation using StringBuffer
      stringBuffer.append("*");
    }
    String string2 = stringBuffer.toString();
    System.out.println("Using StringBuffer Elapsed time: " + clock.getElapsedTime());
 
  }
}

Output For The Above Example Program For String Concatenation

Using + Elapsed time: 3687
Using StringBuffer Elapsed time: 16

Very good blog for JAVA --http://javapapers.com/


Tuesday, September 13, 2011

Fibonacci series in JAVA


*************************************************************************
 *  Compilation:  javac Fibonacci.java
 *  Execution:    java Fibonacci N
 *
 *  Computes and prints the first N Fibonacci numbers.
 *
 *  WARNING:  this program is spectacularly inefficient and is meant
 *            to illustrate a performance bug, e.g., set N = 45.
 *
 *
 *   % java Fibonacci 7
 *   1: 1
 *   2: 1
 *   3: 2
 *   4: 3
 *   5: 5
 *   6: 8
 *   7: 13
 *
 *   Remarks
 *   -------
 *    - The 93rd Fibonacci number would overflow a long, but this
 *      will take so long to compute with this function that we
 *      don't bother to check for overflow.
 *
 *************************************************************************/

public class Fibonacci {
    public static long fib(int n) {
        if (n <= 1) return n;
        else return fib(n-1) + fib(n-2);
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        for (int i = 1; i <= N; i++)
            System.out.println(i + ": " + fib(i));
    }

}
*************************************************************************
 *  Compilation:  javac Fibonacci.java
 *  Execution:    java Fibonacci N
 *
 *  Computes and prints the first N Fibonacci numbers.
 *
 *  WARNING:  this program is spectacularly inefficient and is meant
 *            to illustrate a performance bug, e.g., set N = 45.
 *
 *
 *   % java Fibonacci 7
 *   1: 1
 *   2: 1
 *   3: 2
 *   4: 3
 *   5: 5
 *   6: 8
 *   7: 13
 *
 *   Remarks
 *   -------
 *    - The 93rd Fibonacci number would overflow a long, but this
 *      will take so long to compute with this function that we
 *      don't bother to check for overflow.
 *
 *************************************************************************/

public class Fibonacci {
    public static long fib(int n) {
        if (n <= 1) return n;
        else return fib(n-1) + fib(n-2);
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        for (int i = 1; i <= N; i++)
            System.out.println(i + ": " + fib(i));
    }

}

Friday, July 15, 2011

A 04: Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that
is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with
the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the
classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one
class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at
non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of
primordial class loader. Let us look at the class loaders created by the JVM.
CLASS LOADER reloadable? Explanation
Bootstrap
(primordial)
No Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path
system property, typically loads rt.jar and i18n.jar)
Extensions No Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system
property – usually lib/ext directory of the JRE)
System No Loads classes from system classpath (as defined by the java.class.path property, which
is set by the CLASSPATH environment variable or –classpath or –cp command line
options)
Bootstrap
(primordial)
(rt.jar, i18.jar)
Extensions
(lib/ext)
System
(-classpath)
Sibling1
classloader
Sibling2
classloader
JVM class loaders
Classes loaded by Bootstrap class loader have no visibility into classes
loaded by its descendants (ie Extensions and Systems class loaders).
The classes loaded by system class loader have visibility into classes loaded
by its parents (ie Extensions and Bootstrap class loaders).
If there were any sibling class loaders they cannot see classes loaded by
each other. They can only see the classes loaded by their parent class
loader. For example Sibling1 class loader cannot see classes loaded by
Sibling2 class loader
Both Sibling1 and Sibling2 class loaders have visibilty into classes loaded
by their parent class loaders (eg: System, Extensions, and Bootstrap)
Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their
parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child
class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded
by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true
as explained in the above diagram.
Important: Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a
class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class
loader will have its own singleton. [Refer Q45 in Java section for singleton design pattern]
Explain static vs. dynamic class loading?
Static class loading Dynamic class loading
Classes are statically loaded with Java’s
“new” operator.
class MyClass {
public static void main(String args[]) {
Car c = new Car();
}
}
Dynamic loading is a technique for programmatically invoking the functions of a
class loader at run time. Let us look at how to load classes dynamically.
Class.forName (String className); //static method which returns a Class
The above static method returns the class object associated with the class
name. The string className can be supplied dynamically at run time. Unlike the
static loading, the dynamic loading will decide whether to load the class Car or
the class Jeep at runtime based on a properties file and/or other runtime
Java
14
conditions. Once the class is dynamically loaded the following method returns an
instance of the loaded class. It’s just like creating a class object with no
arguments.
class.newInstance (); //A non-static method, which creates an instance of a
class (i.e. creates an object).
Jeep myJeep = null ;
//myClassName should be read from a properties file or Constants interface.
//stay away from hard coding values in your program. CO
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);
A NoClassDefFoundException is
thrown if a class is referenced with
Java’s “new” operator (i.e. static loading)
but the runtime system cannot find the
referenced class.
A ClassNotFoundException is thrown when an application tries to load in a
class through its string name using the following methods but no definition for the
class with the specified name could be found:
􀂃 The forName(..) method in class - Class.
􀂃 The findSystemClass(..) method in class - ClassLoader.
􀂃 The loadClass(..) method in class - ClassLoader.