Make delicious recipes!


Difference between CLASSPATH and PATH


PATH is a list of directories used by any application/OS to look-up the specified executable.
This is same across Linux, Windows etc. and is typically composed of paths each of which ends in bin/

CLASSPATH is a list of directories used only by Java compiler to lookup classes/jars required for compiling programs.
Paths in this variable typically end in jar/ or class/ or lib/

Packages

Naming Conventions:

  1. Packages are always named in lower case to avoid conflict with classes and Interfaces.
  2. Companies use their reversed Internet domain to begin package names.

Ambiguous Package Hierarchies

At first, packages appear to be hierarchical, but they are not.
For example, the Java API includes some packages like:
  1. java.awt package,
  2. java.awt.color package,
  3. java.awt.font package, and
  4. Many others that begin with java.awt.
However, all these java.awt.xxxx packages are not included in the java.awt package.
The prefix java.awt is used for a number of related packages to make the relationship evident, but not to show inclusion.

Importing java.awt.* imports all of the types in the java.awt package, but itdoes not import any other java.awt.xxxx packages.
If you plan to use the classes and other types in java.awt.color as well as those in java.awt, you must import both packages with all their files:

    import java.awt.*;
    import java.awt.color.*;


Difference between Integer.parseInt(String s) and Integer.valueOf(String s)?


parseInt returns primitive "int" while valueOf returns the object Integer.
In fact, valueOf internally does new Integer(Integer.parseInt(s))


An interesting function here is Integer.valueOf(int i) which converts a primitive into the corresponding object.
This method should be preferred for creating objects from primitive integers (instead of new Integer (i)) because it caches the object corresponding to the primitive
Not all numbers are guaranteed to be cached, but the frequently used ones are cached.
This can result in significant savings in object creation.


Useful methods in class Runtime

  1. public void addShutdownHook(Thread hook) This method provides a way to execute a thread before the JVM halts.
    This method can be called more than one time to add more than one thread.
    When the JVM is about to exit, it will run all such threads in an unspecified order.
    When all the threads have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled.

    Note: It is recommended for the shutdown hook to finish its work in a short period of time because when the JVM is about to shut down, it may not guarantee all shutdown hooks the time necessary for their completion. For example, when an OS is shutting down, it gives all processes only a fixed time to finish their pending work.

  2. removeShutdownHook(Thread hook) This is opposite of above method and can be used to remove a registered hook.

  3. public void exit(int status) This method does not return. It causes the JVM to exit with the specified status.
    The JVM does run the shutdown hooks and any finalizers (i.e. run finalize() methods on objects which have been found eligible for garbage collection)



Using ClassLoader


If a class is loaded using the ClassLoader, then it is not possible to access the methods of such a class normally because the type of the dynamically loaded class is not visible in the thread which loaded it (If it were visible, then there was no need to load the class dynamically in the first place).

Such dynamically loaded classes can be worked upon by using the following three methods:

1) Using base-class of the loaded class, if base-class is visible in the loading thread.
2) Using an Interface implemented by the loaded class, if the interface is visible in the loading thread.
3) Using reflection (if there is no visibility at all in the loading thread).



This loading is usually done "on demand", which means that a class is loaded only when it is actually used by the program.
This happens when one of the two cases arise:

1) When new SomeClass() is called.
2) When SomeClass.staticFunction() is called.

A class with a given name can only be loaded once by a given classloader.

At startup, three class loaders are used:

1) Bootstrap class loader
2) Extensions class loader
3) System class loader

The bootstrap class loader (written in native code) loads the core Java libraries located in the /jre/lib directory.

The extensions class loader loads the code in the extensions directories (/jre/lib/ext, or other directory specified by the java.ext.dirs system property).

The system class loader loads code found on java.class.path, which maps to the system CLASSPATH variable.

A typical class loader has to extend the ClassLoader class which mandates the implementation of function:
    Class loadClass (String className, boolean resolve) throws ClassNotFoundException

Example implementation of the class-loader:
public class MyClassLoader extends ClassLoader {
    private static final int BUFSIZE = 8192;

    protected synchronized Class loadClass (String className, boolean resolve) throws ClassNotFoundException 
	{
        // 1) Check the cache if the class is loaded already
        Class clazz = findLoadedClass(className);
        if (clazz != null)
            return clazz;

        // 2) get class file name from class name
        String classFile = className.replace('.', '/') + ".class";
        
        // 3) Read the class file to get bytes for class
        byte[] classBytes = null;
        try {
            InputStream in = getResourceAsStream(classFile);
            byte[] buffer = new byte[BUFSIZE];
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int n = -1;
            while ((n = in.read(buffer, 0, BUFSIZE)) != -1) {
                out.write(buffer, 0, n);
            }
            classBytes = out.toByteArray();
        }
        catch (IOException e) {
        }

        if (classBytes == null) {
            throw new ClassNotFoundException("Unable to load class: " + className);
        }

        // 4) Convert the bytes into a Class
        try {
            clazz = defineClass(className, classBytes, 0, classBytes.length);
            if (resolve) {
                resolveClass(clazz);
            }
        }
        catch (SecurityException e) { 
            // Core java classes cannot be loaded.
            // Doing so throws java.lang.SecurityException.
            // In such a case, delegate to parent class loader.
            clazz = super.loadClass(className, resolve);
        }

        return clazz;
    }
}


JAR hell

Jar hell is a term used to describe the various pitfalls of using class loaders.

1) If two parts of the code require different versions of a library, they cannot load the two version in the same class loader.
2) If the developer forgets to delete the older version of library while putting a new one, then it is possible that the JVM quitely loads the older one, leading to problems in deployed code or in production.
3) Identical classes loaded by different class-loaders are not considered equal.




Difference between StringBuilder and StringBuffer

Strings are immutable in Java meaning that the contents of a String cannot be changed.
When str1 += str2 is done, a new String object is created into which contents of str1 and str2 are created.
The new object is then assigned to str1.

To overcome this problem, StringBuffer is used.
It has an underlying list of short arrays which allow modification and updation without the need to allocate new objects.
StringBuffer is synchronized while StringBuilder is not.
Both are meant to provide mutable behavior for String objects.






Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal