Why we call start() method which in turns calls run method in java, why not we directly call run method ?

In both the above examples, the run() method is the most important method in the thread classes, it is also the only method that we need to implement in both cases. Why it's only proper to call the start() method to start the thread instead of calling the run() method directly? Because the run() method is not a regular class method. It should only be called by the JVM. Writing thread classes is not about a single sequential thread, it's about the use of multiple threads running at the same time and performing different tasks in a single program. The JVM needs to work closely with the underneath operating system for the actual implementation of concurrent operations. This is how the performance can be improved, and all other benefits mentioned above can be achieved.

You should not invoke the run() method directly. If you call the run() method directly, it will simply execute in the caller's thread instead of as its own thread. Instead, you need to call the start() method, which schedules the thread with the JVM. The JVM will call the corresponding run() method when the resources and CPU is ready. The JVM is not guaranteed to call the run() method right way when the start() method is called, or in the order that the start() methods are called. Especially for the computers have a single processor, it is impossible to run all running threads at the same time. The JVM must implement a scheduling scheme that shares the processor among all running threads. This is why when you call the start() methods from more than one thread, the sequence of execution of the corresponding run() methods is random, controlled only by the JVM.

Java serailization , transient , static concept in core java | core java interview questions

In core java interview questions, Serialization is one of the important topic in which we come across various questions like
What is Transient, Explain Serailization, What is serialversionUID, What is use of serialVersionUID, what is Serilization. (interface, class).
I have gone through various technical interview question websites and found that all answers are very short and dosent give idea of interrelated questions.

This tutorial will help beginners to understand everything related to serialization in one go.

Will first start with basic key points.
All objects in memory are exist only as long as java virtual machine running.
Serialization is process of writing objects to a stream and read from stream. Writing to a stream will make your object persistable. We can save object state on physical file system. and read it later whenever required and restore object state.
Using serialization we can maintain object state beyond java virtual machine lifetime.

Java provides mechnisam to persist the object.
Key points to use this mechanisam is. Your object should be serializable.
How can we make our object serializable? by implementing java.io.Serializble.
What about java library, system classes. Are all of them are serializable? No.
Most of the classes which makes sense to serialize are by default implementing Serializable. But some classes dosent make sense are not.
for E.g : String, Swing, AWT, Class implements Serializable.
Thread, ClassLoader, Socket, OutputStream ..dosent implement Serializable.

Key point to remember is why we need to implement Serializable explicitely? Because java.lang.Object dosent implement serializable. This facility is given to implementer.
What happens if your class is using one of the system class which is not serilizable..for e.g Thread, OutputStream?
Java provides transient keyword. (As mentioned earlier ..Making Thread serializable dosent make sense) so we can mark this member as transient and Serialization process will exclude this member from serialization.

What will be the value of transient variable when we read it back? it will be default value.. for string null.

Now we understood the concept of serialization, and what is use of transient.
Lets do simple example.
Create simple class.

package transientTest;

import java.io.Serializable;

public class TestClass implements Serializable{
 private String fName;
 public String getfName() {
  return fName;
 }
 public void setfName(String fName) {
  this.fName = fName;
 }
 public String getlName() {
  return lName;
 }
 public void setlName(String lName) {
  this.lName = lName;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 private String lName;
 private transient String  password;
}
Test the class. Write to file and read from file.
package transientTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestSerialization {
 public static void main(String... st) throws Exception{
  ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
  TestClass ts= new TestClass();
  ts.setfName("Shashi");
  ts.setlName("Jadhav");
  ts.setPassword("pass");
  obj.writeObject(ts);
  obj.close();
  ObjectInputStream objin= new ObjectInputStream(new FileInputStream(new File("Test.out")));
  TestClass ts1=(TestClass)objin.readObject();
  objin.close();
  System.out.println("ts.getfName():"+ts1.getfName());
  System.out.println("ts.getlName():"+ ts1.getlName());
  // returns null: because TestClass.password is transient.
  System.out.println("ts.getPassword():"+ ts1.getPassword());
  TestClass1 ts12= (TestClass1)ts1.getTestcls();
  System.out.println("test12:"+ts12.mname);
 }
}
Looks very simple .. yes!
But we need to look at the few real time scenario.
Suppose you create the object, set the state and write to stream. In same execution you change the state of the object and try to write it again. What will be the behavior... ?
TestClass ts= new TestClass();
  ts.setfName("Shashi");
  ts.setlName("Jadhav");
  ts.setPassword("pass");
  obj.writeObject(ts);
  ts.setlName("-----");
  obj.writeObject(ts);
  obj.close();
 In above code, you have changed the lName to ---- and again wrote the same object to stream..
Key point to remember.. ObjectOutputStream maintain a reference to an object written to it. That means if the state of the object is written and then written again. the new state will not be saved.
There are two ways to do it.
use reset().
close the stream and write it once again.
obj.reset();
obj = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
obj.writeObject(ts);
obj.close();

There are few other points you need to consider is about GC. once object is written to stream. make sure that object is availble for GC.

One more key point to remember ...or consider scenario..
You have a class which is persisted, and when you try to read it ... by that time class is modified (added new member..). What will happen?
By default if your class is changed after write.. you will not be able to read it.. because your class is modified. serialization will throw exception java.io.invalidClassException().
How serialization identifies that class is modified.. ?
Best answer is ..all persistent capable classes (Implements Serializable) are automatically given a unique identifier. if the identifier of the class is \not equal to the identifier of saved object.
How to resolve this issue... ? answer is serialVersionUID.
You assign the serialVersionUID to the class which will remain same before and after modification.

Eg: Create a class using serialVersionUID.
package transientTest.readwritemodify;

import java.io.Serializable;

public class TestClass implements Serializable{
 static final long serialVersionUID= 1l;
 
 private String name;
 private String lname;
 public String getLname() {
  return lname;
 }

 public void setLname(String lname) {
  this.lname = lname;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
}
Now.. even if your class is modified but the serialversionUID remains the same.. you will be able to read and write. only additioanl state you have added after modification will be set to null

How can you get serialVersionUID runtime?
use :
ObjectStreamClass.getSerialVersionUID(o.getClass());
serialver is one more utility can be used to get the class version.

What if a super class/interface implements a serializable and you dont want your implementing/extending class to provide this facility.
you can override 2 methods and throw exception.

private void writeObject(ObjectOutputStream out)throws IOException{
  throw new NotSerializableException("");
 }
 
 private void readObject(ObjectInputStream in) throws IOException{
  throw new NotSerializableException("");
 }

Binary Tree, Heap Concept Used in Java collection

A Binary Tree is made of nodes.
Each node contains left pointer and right pointer and a data element.





The root pointer points to the top most node in the tree.
Binary Search Tree (BST) or "Ordered Binary Tree" is a type of binary tree where the nodes are arranged in order for each node.
Elements in left sub tree are less ot equal to the node.
Elements in the right are greater that the node.


Binary tree has two possible branches. left and right.


Heap is complete binary tree. It is tree based datastructure.
There are two types of heap
Max Heap: Element with greatest key (value) is always in the root node.
Min Heap: Element with smallest key (value) is always in the root node.


Java 2 platform provides binary heap implementation with class PriorityQueue java collection framework.


In Java virtual machine heap (heap described above and JVM heap could be different, jvm specification does not provide such details. However the term used is same.) is the runtime data area from which memory for all class instances and array is allocated.
  • Heap is created on virtual machine startup.
  • Heap storage for objects is reclaimed by a automatic storage management system know as GC.
  • Heap is shared among all java virtual machine thread.
  • Heap is split up in to "generations"
  • "Young Generation" stores short lived objects.
  • "Old Generation" objects persist longer are stored in old generation.
  • "Permanent Generation" is used to store class definition and reflection related information and used by virtual machine itself.
  • -Xms (minimum) and -Xmx (Max) parameters are used to specify heap size.
Create Binary tree data structure in java.
package BinaryTree;

public class BinaryTreeExample {
 static class Node
 {
  Node left;
  Node right;
  int value;
  public Node(int value) {
   this.value = value;
  }
 }
 
 public void insert(Node node, int value){
  if (value < node.value) {
            if (node.left != null) {
                insert(node.left, value);
            } else {
                System.out.println("  Inserted " + value + " to left of node " + node.value);
                node.left = new Node(value);
            }
        } else if (value > node.value) {
            if (node.right != null) {
                insert(node.right, value);
            } else {
                System.out.println("  Inserted " + value + " to right of node " + node.value);
                node.right = new Node(value);
            }
        }

 }
 
 public void printInOrder(Node node) {
        if (node != null) {
            printInOrder(node.left);
            System.out.println("  Traversed " + node.value);
            printInOrder(node.right);
        }
    }

}


-----------------------------------

package BinaryTree;

public class Main {
 public static void main(String... str){
  BinaryTreeExample bnary= new BinaryTreeExample();
  BinaryTreeExample.Node node = new BinaryTreeExample.Node(50);
  bnary.insert(node, 6);
  bnary.insert(node, 20);
  bnary.insert(node, 9);
  bnary.insert(node, 9);
  bnary.insert(node, 20);
  bnary.insert(node, 14);
  bnary.insert(node, 15);
  bnary.insert(node, 22);
  bnary.printInOrder(node);
 }
}

Java Classloader concept | java class loader tutorial

Java ClassLoader

  1.     Java classloader is part of java runtime environment that dynamically loads java class in to java virtual machine.
  2.   Usually classes are loaded on demand.
  3. Java provides ClassLoader abstract class to extend class loading function.
  4.   User defined class loader should do basic functions as: Given the name of the class, a class loader attempt to locate or generate data that constitutes a definition for a class.
  5. Every class object contains reference to the classloader.

        TestLoad.class.getClassLoader()

 Class objects for Array classes are not created by class loader, but are created automatically by java runtime.
    ClassLoader uses delegation model to search for classes and resources.
    Method defineClass() converts an array of bytes in to instance of class.

cls = defineClass(className, classBytes, 0, classBytes.length);

    Various class loaders

Bootstrap Class Loader : Loads classes from JAVA_HOME/lib
Extension Class Loader (sun.misc.launcher$ExtClassLoader): Loads classes from extension directory.
System Class Loader (sun.misc.launcher$AppClassLoader): Loads classes from java.class.path.

    Methods to remember:

findClass(String name) : finds specified class
getParent(): Returns parent class loader for delegation.
getSystemClassLoader(): returns system classloader for delegation.
loadClass(): loads class with specified name.
resolveClass().

     User defined classloader needs permission to load system classes.

method to use defineClass(String name, byte[] b, int off, int len, ProtectionDomain domain).

Write custom class loader.
1) Create class which extends ClassLoader.
2) Override protected synchronized method LoadClass().
3) Use findLoadedClass() to identify if class is already loaded.
4) Handle security exception. for the system classes.
5) In case of security exception, call super.loadClass(). delegate to super classloader.
4) Create test class file.
5) Read the file as byte array.
6) Call define class method.

package classLoader;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {
 private static final int BUFFER_SIZE = 8192;

 protected synchronized Class loadClass(String className, boolean resolve)
   throws ClassNotFoundException {

  // 1. is this class already loaded?
  Class cls = findLoadedClass(className);
  if (cls != null) {
   System.out.println("Class is already available..");
   return cls;
  }

  // 2. get class file name from class name
  String clsFile = className.replace('.', '/') + ".class";

  // 3. get bytes for class
  byte[] classBytes = null;
  try {
   InputStream in = getResourceAsStream(clsFile);
   byte[] buffer = new byte[BUFFER_SIZE];
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   int n = -1;
   while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
    out.write(buffer, 0, n);
   }
   classBytes = out.toByteArray();
  } catch (IOException e) {
   System.out.println("ERROR loading class file: " + e);
  }

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

  // 4. turn the byte array into a Class
  try {
  
   cls = defineClass(className, classBytes, 0, classBytes.length);
   if (resolve) {
    resolveClass(cls);
   }
   System.out.println("Loaded using CUSTOM class loader..:"+cls);
  } catch (SecurityException e) {
   cls = super.loadClass(className, resolve);
   System.out.println("Loaded using SYSTEM class loader..:"+cls);
  }

  return cls;
 }
}



package classLoader;

public class TestClassLoader {
 public static void main(String[] args) throws Exception {
        MyClassLoader loader1 = new MyClassLoader();
        Class testLoad = Class.forName("classLoader.TestLoad", true, loader1);
        System.out.println("TestLoad class: " + testLoad);
        if (TestLoad.class.equals(testLoad)) {
            System.out.println("TestLoad loaded through custom loader is the same as that loaded by System loader.");
        }
        else {
            System.out.println("TestLoad loaded through custom loader is NOT same as that loaded by System loader.");
        }
        java.lang.reflect.Method main = testLoad.getMethod("main",
                                                new Class[] {String[].class});
        main.invoke(null, new Object[]{ new String[]{} });
    }
}

Can you synchronize the constructor of object in Java

According to the Java language specification you can not use java synchronized keyword with constructor it’s illegal and result in compilation error. So you can not synchronized constructor in Java which seems logical because other threads cannot see the object being created until the thread creating it has finished it.

How many way we can break Singleton Class in java | Singleton design concept in java

Singleton Pattern ensures a class has only one instance and provides a global point of access to it.

The default constructor of the class is made private, which prevents the direct instantiation of the object by other classes.

A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.


public class BookingFactory {
 
 private static BookingFactory instance;
 
 // An instance attribute.
 private int data = 0;
 
 
 private BookingFactory() {
  //initiate any other attributes if needed.
 }
 
 public static BookingFactory getInstance(){
  if(instance == null)
      instance = new BookingFactory();
  return instance;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }
 
 // other methods....
 
}



In future if you get a requirement for having more than one instance then singleton allows multiple instances without affecting a singleton class's clients. Just you need to do is make a small change in Singleton Class, which doesn't effect the client's code.

Note that the singleton instance is only created when needed. This is called lazy instantiation.


public class SingletonDemo {
 
 public static void main(String args[]) {
   
 // Get a reference to the single instance of Singleton.
 BookingFactory bookingFactory = BookingFactory.getInstance();
 
 // Set the data value.
 bookingFactory.setData(34);
 
 System.out.println("First reference: " + bookingFactory);
 System.out.println("Singleton data value is: " +bookingFactory.getData());
 }
 
}



How can we break Singleton:

1. It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle.

Solution :

In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration.

Make the Instance access method Synchronized to prevent concurrent thread access.



public static synchronized BookingFactory getInstance()




Synchronization is expensive, however, and is really only needed the first time the unique instance is created.

Do an eager instantiation of the instance rather than a lazy instantiation.

You can also instantiate the Singleton as soon as the class loads. i.e You can place it in static block to ensure that it happens only once.


public class BookingFactory {
 
 private static BookingFactory instance;
 
 // An instance attribute.
 private int data = 0;
 
 static {
  instance = new BookingFactory();
 }
 
 private BookingFactory() {
  //initiate any other attributes if needed.
 }
 
 public static BookingFactory getInstance()
 {
  return instance;
 }

 public int getData() {
  return data;
 }

 public void setData(int data) {
  this.data = data;
 }
 
 // other methods....
 
}



Instead of synchronizing the whole method you can also make the instance variable as static final. It is thread-safe because static member variables created when declared are guaranteed to be created the first time they are accessed. You get a thread-safe implementation that automatically employs lazy instantiation.



public class BookingFactory {

   private final static BookingFactory instance = new BookingFactory();

   private BookingFactory() {
         // Exists only to defeat instantiation.
      }
}




But you loose the flexibility of having more than one instance in future without changing client's code.



2. if you are using multiple classloaders, this could defeat the Singleton implementation and result in multiple instances.

Solution:

Because multiple classloaders are commonly used in many situations—including servlet containers—you can wind up with multiple singleton instances no
matter how carefully you've implemented your singleton classes. If you want to make sure the same classloader loads your singletons, you must specify the
classloader yourself; for example:


private static Class getClass(String classname)
                                         throws ClassNotFoundException {
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      if(classLoader == null)
         classLoader = Singleton.class.getClassLoader();
      return (classLoader.loadClass(classname));
   }
}



The preceding method tries to associate the classloader with the current thread; if that classloader is null, the method uses the same classloader that loaded a singleton base class. The preceding method can be used instead of Class.forName().



3. If SingletonClass implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.

Solution:

To avoid the above you need to implement readResolve() method.


private Object readResolve() {
    return INSTANCE;
}



The previous singleton implementation returns the lone singleton instance from the readResolve() method; therefore, whenever the Singleton class is deserialized, it will return the same singleton instance.


4. We will be able to create a copy of the Object by cloning it using the Object’s clone method.

Solution:

Override the Object clone method to prevent cloning

This can be done as shown below


SingletonDemo clonedObject = (SingletonDemo) obj.clone();



This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.


public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}



When to use:
We can use this while creating objects of thread pools, caches etc to avoid wasting resources.

will static keywords tell one per JVM in Java ?

It is very good question during interview
so it wrong to say that static keyword say One per JVM , bcz class can be loaded in more than one classloader. And thus, static fields are not per-VM (as you might initially conclude), but per-classloader. Working in an app server or plugin environment using post-delegation classloaders, this comes up a lot

Chain of responsibility Design pattern Concept with Example

Chain Of Responsibility Pattern creates a chain of objects that examine a request. Each object in turn examines the request and handles it if it can, otherwise passes it on to the next object in the chain. So each object in the chain acts as a handler.

The object that ultimately handles the request is unknown explicitly to the sender object that sends the request. By this way we are using chain of responsibility pattern to decouple the sender of the request and its receivers.

Each object on the chain shares a common interface for handling requests and for accessing its successor on the chain.

Receipt is not guaranteed - a request could fall off the end of the chain without being handled.

The Java Servlet filter framework is an example of chain of resposibility design. Note that the chain.doFilter() is the method that should be called to make the chain roll. If the subclass missed it, the whole chain would be stopped or blocked.

Java exception handling is another example of chain of responsibility design. When an error occurs, the exception call will look for a handling class. If there is no handler, the super Exception class will be called to throw the exception. Otherwise, the handler class will handle it. Processing stops after an event is handled.

Chain of responsibility simplifies object interconnections.Instead of senders and receivers maintaining references to all candidate receivers,each sender keeps a single reference to the head of the chain,and each receiver keeps a single reference to the immediate successor in the chain.

Chain Of Responsibility uses Command Pattern to represent requests as objects
Chain of Responsibility is often applied in conjunction with CompositePattern.There,a component's parent act as its successor.

package cop;

abstract class Car {
 
 public double price = 5.5;
 public String color = "Silver";
 public String size = "Small";
 
 
 // The Next Element in the Chain of Responsibility
 protected Car next; 
 
 protected Car searchNext(Car car) { 
  next=car; 
  return this;
 } 
 
 public void trail(String performance) {
  if(price < 10 && performance.equalsIgnoreCase("Satisfactory")){   
   buyCar(performance);
  }
  else{
   if(next!=null)
    next.trail(performance);
  }
 }  
 
 abstract protected void buyCar(String performance);
}





package cop;

public class Innova extends Car{
 
 public Innova(double price,String color,String size) {
  this.price = price;
  this.color = color;
  this.size = size;
 }
 
 protected void buyCar(String performance) {
  System.out.println("Liked Innova ...  performance... "+performance);
 }
}





package cop;

public class Toyota extends Car{
 
 public Toyota(double price,String color,String size) {
  this.price = price;
  this.color = color;
  this.size = size;
 }
 
 protected void buyCar(String performance) {
  System.out.println(" Liked Toyota ... performance... "+performance);
 }
}





package cop;

public class SearchCars {

 public static void main(String[] args) {
  Car car=new Toyota(10.5,"black","big").searchNext(new Innova(8.5,"silver","medium"));
  car.trail("Satisfactory"); 
 }

}




When To Use:
1. Use Chain Of Responsibility Pattern when you want to give more than one object a chance to handle a request and the actual handler is not known in advance.
2. Commonly used in windows systems to handle events like mouse clicks and keyboard events.
3. When you want to avoid coupling the sender of a request to its receiver.

Advantages:
1. Decouples the sender of the request and its receivers.
2. Simplifies your object as it doesn't have to know about the chain structure and keep direct references to its members.
3. Allows you to add or remove responsibilities dynamically by changing the members or order of the chain.


Disadvantage:
1. Hard to observe the runtime characteristics and debug.

Java classloader concept | bootstrap , system, user classloader in java

The Class loader concept, one of the cornerstones of the Java virtual machine, describes the behavior of converting a named class into the bits responsible for implementing that class. Because class loaders exist, the Java run time does not need to know anything about files and file systems when running Java programs.

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. It is somewhat special because the virtual machine assumes that it has access to a repository of trusted classes which can be run by the VM without verification.

When a new JVM instance is started , the bootstrap class loader is responsible for loading key java classes like java.lang.Object and other runtime code into memory. The runtime classes are packaged inside jre/lib/rt.jar file. We cannot find the details of the bootstrap class loader in the java language specification, since this is a native implementation. For this reason the behavior of the bootstrap class loader will differ across JVMs.

Java can change its class storage model simply by changing the set of functions that implements the 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.

ex : Bootstrap (primordial) Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar) and is the parent in the Class loaders hierarchy.

next comes the Extensions (Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE) and then System (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) ClassLoaders.

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


Note : 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.

At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name. The method definition is:

Class r = loadClass(String className, boolean resolveIt);

The variable className contains a string that is understood by the class loader and is used to uniquely identify a class implementation. The variable resolveIt is a flag to tell the class loader that classes referenced by this class name should be resolved (that is, any referenced class should be loaded as well).

We can build our own ClassLoader by being a subclass of java.lang.ClassLoader. The only abstract method that must be implemented is loadClass().

Static Class Loading :

Classes are statically loaded with Java’s 'new' operator.


class MyClass {
 public static void main(String args[]) {
  Car c = new Car();
 }
}




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.

Dynamic class loading:

Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.

we can load classes dynamically by...


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 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.
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);



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:
1. The forName(..) method in class - Class.
2. The findSystemClass(..) method in class - ClassLoader.
3. The loadClass(..) method in class - ClassLoader.

The Java virtual machine has hooks in it to allow a user-defined class loader to be used in place of the primordial one. Furthermore, since the user class loader gets first crack at the class name, the user is able to implement any number of interesting class repositories, not the least of which is HTTP servers -- which got Java off the ground in the first place.

There is a cost, however, because the class loader is so powerful (for example, it can replace java.lang.Object with its own version), Java classes like applets are not allowed to instantiate their own loaders. (This is enforced by the class loader, by the way.) This column will not be useful if you are trying to do this stuff with an applet, only with an application running from the trusted class repository (such as local files).

How to create Proxy object in java | creation of proxy object concept in spring AOP

J2SE v1.3 has introduced a dynamic proxy class in the Java Reflection package.
A dynamic proxy class implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.
 Proxy classes and instances are created using static methods of the java.lang.reflect.Proxy class.Each proxy class has one public constructor that takes one argument, an implementation of the java.lang.reflect.InvocationHandler interface.


package com.prox;

public interface Showable {
   
public void show();
}





-------------------------------------


package com.prox;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyHandler implements InvocationHandler{
   
    Showable target;
    public  MyHandler(Showable target)
    {
        this.target=target;
    }
    public Object invoke(Object proxy, Method m, Object [] args)throws Throwable
    {
        Object o= m.invoke(target, args);
        return o;
    }

}


------------------------------------------

package com.prox;

public class A implements Showable{
   
    public void show()
    {
       
        System.out.println("Inside the Class A");
    }

}


---------------------------------------------


package com.prox;


import java.lang.reflect.Proxy;

public class ProxyTest {
   
    public static void main(String [] args)
    {
       
        System.out.println("Inside the main method");
        A  target = new  A();
        B  target1 = new  B();
        MyHandler handler= new MyHandler(target1);
        try {
         System.out.println("creating Proxy object");
         Showable pr=(Showable)Proxy.newProxyInstance(B.class.getClassLoader(),new
                Class[]{Showable.class}, handler);
       
        System.out.println("The Invoking show method on proxy object");
        pr.show();
        System.out.println("the proxy object"+pr.getClass().getName());
        //B b=(B)pr;
        //b.notShow();
        }
       
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }

}


-------------------------------------------

In above code we have created a proxy object concept

Drawback of proxy object

  • One limitation is that the method must be called through an instance of the proxy class. So nested methods calls, for instance, would not be intercepted.
  • Another limitation is that the method must have been defined in an Interface that is implemented by the object being proxied. It can not be called through an instance of a class that does not implement an interface.

can we override init(ServletConfig config) method in servlet class in J2ee ?

Yes , we can override init(ServletConfig config) into servlet , but when you retrive ServletCofig object into inside servlet give Nullpointer Exception .

Code:
package com.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class servlettest extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
   
    public void init(ServletConfig config) throws ServletException
    {
    }
/**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("first_name");
        System.out.println("The name is"+name);
        try {
         ServletConfig config=getServletConfig();
        System.out.println("The get Servlet config is"+config.getServletContext());
        System.out.println("The servlet name is"+config.getServletName());
        }
        catch(Exception ex)
        {
            System.out.println("The exception is"+ex);
        }
        RequestDispatcher rd= request.getRequestDispatcher("success.jsp");
        rd.forward(request, response);
       
    //    super.doGet(request, response);
    }

   

}


OUTPT:

The name is
The exception isjava.lang.NullPointerException



In above code it will clear that Servlet container intstantiate servlet and give server and enviornment information to particular servlet
through init(ServletConfig config) . 

Can we give constructor with arguments in servlet in Java ?

Ans- No, we cannot give a constructor with arguments in servlet in java because servlet container responsible for creating servlet instance so it call no arguments constructor in servley if you give constructor with arguments then it will give error at time of instantiating

 Incorrect Way

package com.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class servlettest
 */
public class servlettest extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */

    public servlettest(int a) {
       System.out.println("Inside the constructor"+a);
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("first_name");
        System.out.println("The name is"+name);
       
        RequestDispatcher rd= request.getRequestDispatcher("success.jsp");
        rd.forward(request, response);
    //    super.doGet(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
 
Error will give at time of instantiating
javax.servlet.ServletException: Error instantiating servlet class com.servlet.servlettest org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:870) org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81) org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:685) java.lang.Thread.run(Thread.java:595)

First Program in spring framework using eclipse IDE


Spring is powerful framework also called mother of all Framework



First Program in Spring

1.  Calulator.java

package com.login;

public class calculator implements operation{

    public calculator()
    {
        System.out.println("Inside the calculator");
    }
public int sum()
{
    return 4;
   
}
public  int substraction()
{
    return 6;
}
}




2. operation.java

package com.login;

public interface operation {
    public int sum();
    public int substraction();
   

}



3. TestCal.java

package com.login;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class TestCal {
    public static void main(String[] args)
    {
        try{

BeanFactory factory = new XmlBeanFactory(new ClassPathResource("aplication.xml"));   

calculator cl=(calculator)factory.getBean("bean1");
int a=0;
a=cl.sum();
System.out.println("The value of sum is "+a);
        }
        catch(Exception e)
        {
            System.out.println("The exception is"+e.getMessage());
        }
       
    }

}


Outpt:

After the run this program Output will
  Inside the calculator
  The value of sum is 4

Here we bean class Calcultor is not directly instantiated , it has done through XMLBeanFactory i.e. configure into
application.xml file, so spring framework says that programmer to concentrate only on bussiness loging not on creation of object
i.e. Spring IOC take responsibility of creation of object

application.xml

<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.springframework.org/schema/beans    
              http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

  <bean id="bean1" class="com.login.calculator"/>
  <bean id="audi" class="com.aspec.Audience"/>
</beans> 

Import following highlighted jar file in lib directory