Class Loaders, Strings

Class loaders offer a very powerful mechanism by which classes can be loaded at runtime. In a Java Virtual Machine (JVM), each and every class is loaded by some instance of a java.lang.ClassLoader. The very first class is especially 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.

  • Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.
  • Extensions Class Loader loads jar files from Java extension directory (%JavaHome/jre(jdk)/lib/ext).
  • System Class Loader loads classes from system classpath (as set by CLASSPATH env variable or -classpath or -cp command line option)

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.

class_loader_hierarchy

Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true. Classes loaded by Bootstrap class loader have no visibility into classes loaded by its descendents (i.e Ext and Sys). The classes loaded by system class loader have visibility into classes loaded by its parents. Same goes for user define classloaders, they paralley cannot see what class are loaded by other, but can see classes loded by its to heirarchy.

Static class loading:

  • Classes are statically loaded with ‘new‘ operator.
    Car c=new Car();
  • A NoClassDefFoundException is thrown if a class is referenced with new operator but the runtime system cannot find the reference class.

Dynamic class loading:

  • Dynamic loading is a technique for programmatically invoking of a class loader at run time.
    Class.forName(String classname)//static method which return class
    class.newInstance(); //a non static method which creats a object
  • A ClassNotFoundException is thrown if something goes wrong here. 

STRING

String is a Class in java and defined in java.lang package. String is immutable means that you cannot change the object itself, but you can change the reference ofcourse.


String s1 = "some text";
 s1.substring(0,4);//new string created but reference lost
 System.out.println(s1); // still printing "some text"
 String s2 = s1.substring(0,4);
 System.out.println(s2); // prints "some"
 // 2 new object "more" and "text" were created but their references were lost,
 //another new object "more text" was created and its reference assigned to s3
 String s3 = "more" +"text";
 System.out.println(s3); //prints "more text"

We can create String object using new operator like any normal java class or we can use double quotes to create a String object. There are several constructors available in String class to get String from char array, byte array etc.

</pre>
String str1 ="abc";
 String str2 ="abc";
 String str3 =new String("abc");
 String str4 = new String("abc").intern();
 System.out.println("str1==str2 ==>"+(str1==str2));
 System.out.println("str1==str3 ==>"+(str1==str3));
 System.out.println("str1==str3.intern() ==>"+(str1==str3.intern()));
 System.out.println("str1==str4 ==>"+(str1==str4));
<pre>

Output:


</pre>
str1==str2 ==>true
str1==str3 ==>false
str1==str3.intern() ==>true
str1==str4 ==>true
<pre>

When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool. Thats why str1 and str2 point to the same string in pool and returns true when compared.

When we use new operator, JVM creates the String object (HEAP) but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.

String vs StringBuffer vs StringBuilder

  • String is immutable whereas StringBuffer and StringBuider are mutable classes.
  • StringBuffer is thread safe and synchronized whereas StringBuilder is not, thats why StringBuilder is more faster than StringBuffer.
  • String concat + operator internally uses StringBuffer or StringBuilder class

How to compare strings? Use “==” or use equals()?

In brief, “==” tests if references are equal and equals() tests if values are equal. Unless you want to check if two strings are the same object, you should always use equals().

Can we use string for switch statement?

Yes to version 7. From JDK 7, we can use string as switch condition. Before version 6, we can not use string as switch condition.


// java 7 only!
 switch (str.toLowerCase()) {
 case "a":
 value = 1;
 break;
 case "b":
 value = 2;
 break;
 }

Why Char array is preferred over String for storing password?

String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.
If we use char array to store password, we can set it to blank once we are done with it. So we can control for how long it’s available in memory that avoids the security threat with String.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: