Thursday, May 29, 2014

About Final

Know about basics of final , where to use and when compiler sees final keyword then how it reacts?


How final is used inside a method for local variables and as parameter of any methods ?


Can we use final with class definition? if yes how it will affect the relationship between the classes? can we use final with the instance methods, if yes then what the restriction it can impose?

ENUM - Part 2

What is correct syntax to write an enum in java?
package in.technoscience.first;

public enum Work {
Tough,Easy,VeryEasy;
}

1) Use the keyword enum which will tell that type being created is an enum.
2) Inside the curly braces, put in constant that you want to use in your application.

How compiler deal with the enum created?
First thing to remember is as it is a type in java so compiler will generate .class file with the name enum means here we will can find Work.class file.

The code generated by the compiler:
 // the enum user has defined is treated as class by compiler.
// compiler attach final with class so it means it can not be subclassed 
public final class Work extends Enum { //user defined enum extends java.lang.Enum
//enum value that user used in enum is considered as the constant of type Work(class name)
 public static final Work Tough;
 public static final Work Easy;
 public static final Work VeryEasy;
 private static final Work ENUM$VALUES[];// an array to store enum values
//compiler provide private constructor, another reason it can not be subclassed
 private Work(String s, int i) {
  super(s, i);
 }
 // values method is put by compiler which plays great role in iterating through enum
 public static Work[] values() {
  Work awork[];
  int i;
  Work awork1[];
  System.arraycopy(awork = ENUM$VALUES, 0,
    awork1 = new Work[i = awork.length], 0, i);
  return awork1;
 }

 public static Work valueOf(String s) {
  return (Work) Enum.valueOf(in / technoscience / first / Work, s);
 }
//a static block is used where each value is instantiated with enum value name and index no.
   static {
  Tough = new Work("Tough", 0); // it represents every enum value is an instance of user defined enum type
  Easy = new Work("Easy", 1);
  VeryEasy = new Work("VeryEasy", 2);
  ENUM$VALUES = (new Work[] { Tough, Easy, VeryEasy }); //anonymous array
 }
}

Here you can visualize , for 3 lines of code you have written, how compiler deals with that ! 

Can we write an enum inside a class?
yes we can write an enum inside a class also. 
package in.technoscience.first;
public class Uploader {

  public enum UploadStatus { INITIALIZING, IN_PROGRESS, COMPLETE };

  // Class body

}
Here compiler will generate two .class file
1st : Uploader.class 
2nd: Uploader$UploadStatus.class file

code generated by compiler :
ackage in.technoscience.first;

// user defined enum as inner class inside the class where it has been defined
public class Uploader
{
    public static final class UploadStatus extends Enum
    {

        public static final UploadStatus INITIALIZING;
        public static final UploadStatus IN_PROGRESS;
        public static final UploadStatus COMPLETE;
        private static final UploadStatus ENUM$VALUES[];

        public static UploadStatus[] values()
        {
            UploadStatus auploadstatus[];
            int i;
            UploadStatus auploadstatus1[];
            System.arraycopy(auploadstatus = ENUM$VALUES, 0, auploadstatus1 = new UploadStatus[i = auploadstatus.length], 0, i);
            return auploadstatus1;
        }

        public static UploadStatus valueOf(String s)
        {
            return (UploadStatus)Enum.valueOf(in/technoscience/first/Uploader$UploadStatus, s);
        }

        static 
        {
            INITIALIZING = new UploadStatus("INITIALIZING", 0);
            IN_PROGRESS = new UploadStatus("IN_PROGRESS", 1);
            COMPLETE = new UploadStatus("COMPLETE", 2);
            ENUM$VALUES = (new UploadStatus[] {
                INITIALIZING, IN_PROGRESS, COMPLETE
            });
        }

        private UploadStatus(String s, int i)
        {
            super(s, i);
        }
    }


    public Uploader()
    {
    }
}


Saturday, May 17, 2014

Enum - Part1

Some points about Enumerated type in java :

Enums

  • Enums were introduced as new type in java in jdk1.5. prior to that there was concept of classes and interfaces(as type) only. But these were not sufficient when we need to define a finite set of allowed values for a specific data type. So enumerated type concept was introduced and it was known by the name enum. 
  • Enums allow you to dump most of your "public static final" variable declarations.
  • Enums are type, like class : As a result, we get type-safety, compile-time checking, and the ability to use them in variable declarations. This overcome the problems that we have faced while using public static final integer or String constant.
  • Enums extend java.lang.Enum : java.lang.Enum was a new class in jdk1.5, and is not itself an enumerated type. All enumerated types implicitly extend Enum.
  • Enumerated types aren't integers :Each declared value is an instance of the enum class itself; this ensures type-safety and allows for even more compile-time checking.
  • Enums have no public constructor :This removes the ability to create additional instances of the enum not defined at compile-time. Only those instances defined by the enum are available. It has only protected constructor.
  • Enum values are public, static, and final :Values cannot be overwritten, changed, or otherwise messed with in ways that affect your programming logic. The enum itself is effectively final, as it cannot be subclassed.
  • Enum values can be compared with == or equals( ) :Because enums are effectively final, and there is a distinct set of values, you can use—for comparison. Additionally, enumerated types have a working equals( ), for use in collection classes.
  • Enums implements java.lang.Comparable :As a result, enum values can be compared with compareTo( ), and ordering occurs in the same order as values are declared in the enum declaration.
  • Enums override toString( ) :The toString( ) method on an enumerated type returns the name of the value.
  • Enums provide a valueOf( ) method :The static valueOf( ) method complements toString( ). If you change the behavior of toString( ), you need to also change the behavior of valueOf( ). These two methods should always be mirror images of each other.
  • Enums define a final instance method named ordinal( ) :oridinal( ) returns the integer position of each enumerated value, starting at zero, based on the declaration order in the enum. Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such java.util.EnumSet and java.util.EnumMap
  • Enums define a values( ) method : values( ) allows for iteration over the values of an enum.

Sunday, May 11, 2014

OOPs , Part 9 : A use case to understand advantage of interface and composition over inheritance.

In my last post understanding interface best way  i have put a scenario and solution code to understand the use of two mantras of design pattern.

Here in this post I will be improving my code and Adopt the best practices to use the Interface and composition while coding.

Point to focus :
  1. From the given scenario we can visualize , there is common functionality of calculating the salary which is provided my every category class. Just every category class provides its logic in its own way.
  2. So what we can do, the common services offered by different service provider classes(different Category class) can be abstracted out and declared as a separate interface. 
  3. Each of the service provider classes can be designed as implementers of this common interface. 
Advantage :
  1. Objects of different service provider classes can be treated as objects of the interface type.
  2. This will enables the client to use different types of service provider objects in a loosely manner without requiring any changes. 
  3. The client does not need to be altered even when a new service provider is designed as part of the class hierarchy.
Example with code :

here our first type is an interface :SalaryCalculator.java
package in.technoscience.best;
public interface SalaryCalculator {
  public double getSalary();
}

second class is : CategoryA . java implementing SalaryCalculator interface

package in.technoscience.best;

public class CategoryA implements SalaryCalculator {
 double baseSalary;
 double overTime;

 public CategoryA(double base, double overTime) {
  baseSalary = base;
  overTime = this.overTime;
 }

 public double getSalary() {
  return (baseSalary + overTime);
 }
}

third class will be : CategoryB. java implementing the SalaryCalculator interface

package in.technoscience.best;

public class CategoryB implements SalaryCalculator {
 double salesAmount;
 double baseSalary;
 final static double commission = 0.02;

 public CategoryB(double sa, double base) {
  baseSalary = base;
  salesAmount = sa;
 }

 public double getSalary() {
  return (baseSalary + (commission * salesAmount));
 }
}

fourth class will be : Employee class

package in.technoscience.best;
public class Employee {
  SalaryCalculator empType; // interface type 
  String name;

  public Employee(String s, SalaryCalculator c) {
    name = s;
    empType = c;
  }

  public void display() {
    System.out.println("Name=" + name);
    System.out.println("salary= " + empType.getSalary());
  }
}

Now a class to test the application : MainApp.java

package in.technoscience.best;

public class MainApp {
  public static void main(String [] args) {
    SalaryCalculator cA = new CategoryA(10000, 200); // runtime polymorphism
    Employee emp = new Employee ("technoscience",cA);
    emp.display();

    cA = new CategoryB(20000, 800);
    emp = new Employee ("technoscience2",cA);
    emp.display();
  }
}

Explanation: 
The changes I have made in this code :
  1. The common salary calculating service provided by different objects has been abstracted out to a separate SalaryCalculator interface.
  2. Each of the CategoryA and the CategoryB classes has been designed as implementers of the SalaryCalculator interface.
  3. The Employee class implementation needs to be changed to accept a salary calculator service provider of type SalaryCalculator.
Advantage :
  1. With these changes, the main application object MainApp can now create objects of different types of salary calculator classes and use them to configure different Employee objects. 
  2. Because the Employee class, accepts objects of the SalaryCalculator type, it can be used with an instance of any SalaryCalculator implementer class (or its subclass).
  3. In the future if we want to add any new category then we can write a new class implementing that interface and then in MainApp. java we can deal accordingly and we will be getting proper result.
you can download the source code from my git repository : My Git

OOPs 8 - A use case to understand advantage of interface and composition over inheritance.

Here I will be posting a scenario through which you can understand why and where first two mantras of design patterns fits well:
1) Always code on basic of interface instead of implementation. 
2) consider composition over inheritance.

consider a scenario :
suppose there are different employee in your company and they are categorized on the basis of their designation like :
architect, tech lead ----> category A.
senior developer, junior developer -- > category B
sales manager, Hr ------> category c

Now your application needs to display the display the salary of employee of different category
.  

solution :
how you will approach for the solution:

1st way : Following the inheritance concept And relying on Implementation class

i have my first class as :CategoryA . java for employee of categoryA
package in.technoscience.first;

public class CategoryA {
 double baseSalary;
 double overTime;

 public CategoryA(double base, double overTime) {
  baseSalary = base;
  overTime = this.overTime;
 }

 public double getSalary() {
  return (baseSalary + overTime);
 }
}

Now my second class : CategoryB . java for employee of CategoryB


package in.technoscience.first;
public class CategoryB {
  double salesAmount;
  double baseSalary;
  final static double commission = 0.02;
  public CategoryB(double sa, double base) {
    baseSalary = base;
    salesAmount = sa;
  }

  public double getSalary() {
    return (baseSalary + (commission * salesAmount));
  }
}

Now a class to represent Employee : Employee.java

package in.technoscience.first;

public class Employee {
 CategoryA salaryCalculator;
 String name;

 public Employee(String s, CategoryA c) {
  name = s;
  salaryCalculator = c;
 }

 public void display() {
  System.out.println("Name=" + name);
  System.out.println("salary= " + salaryCalculator.getSalary());
 }
}

 A class to test our application: MainApp.java

 
package in.technoscience.first;
public class MainApp {
  public static void main(String [] args) {
    CategoryA cA = new CategoryA(10000, 200);
    Employee emp = new Employee ("technoscience",cA);
    emp.display();
  }
}

Explanation: 
  1. A client object can use an Employee object with values for the name and the category type attributes at the time of invoking its constructor. 
  2. here our testing class(MainApp.java),Creates an instance of the CategoryA class by passing appropriate details required for the salary calculation.
  3. Creates an Employee object and uses it with the CategoryA object inside constructor.
  4. Invokes the display method on the Employee object to display the name and salary for the employee.
  5. The Employeeobject makes use of the services of the CategoryA object in calculating the salary of the employee it represents. In this aspect, Employee object acts as a client to the CategoryA object
Limitations :
  1. This design works fine as long as application needs to calculate the salary for
    Category-A employee only.
  2. This design also works fine when we have only one class of objects that provides this service.
  3. Here from the above code Employee object expects the salary calculation service provider object to be always of the CategoryA class type . And this tight coupling will affects the maintainability and results in an application design that will be restrictive in terms of its future enhancement.
  4. As per above code, suppose application also needs to calculate the salary of employees who are part of Category-B.
  5. The main application object (testing class) MainApp.java will be able to create an instance of the CategoryB class but will not be able to use the Employee object with CategoryB instance.
  6. This is because the Employee object expects the salary calculator to be always of the CategoryA type. 
  7. Due to above reason, the main application will not be able to reuse the existing Employee class to represent different category of employees.
  8. Still if you want to stick with this code then you have make modification in different class at different places and that will introduce maintenance problem.
Solution:
  1. so to overcome this problem we can adopt the interface based coding and use the different concepts like runtime polymorphism 
  2. Apart from using runtime polymorphism we can use the concept of composition over inheritance.
  3. Adopting to interface based coding style will make our classes loosly coupled
  4. And once it is loosely coupled then it can solve the maintenance problem and code will be more adaptable.
I will explain approach to make this code better in my Next Post, Keep visiting.
 

Saturday, May 10, 2014

JVM, Part 5- Runtime data areas ( Method Area)

In this post I will explain about the runtime data areas of JVM.
When a Java virtual machine runs a program, it needs memory to store many things, including bytecodes and other information, it extracts from loaded class files, objects instantiated, parameters to methods, return values, local variables, and intermediate results of computations. The Java virtual machine organizes the memory it needs to execute a program into several runtime data areas.
 
METHOD AREA:
  1. Information about loaded types are stored in the method area. 
  2. when the types are loaded then class loader reads the required file and then that is passed to the JVM and then JVM extract the information and store those in method area.
  3. Memory for static variables declared in the class is also taken from the method area.
  4. All threads share the same method area, so access to the method area's data structures must be designed to be thread-safe. 
  5. The size of the method area need not be fixed,it can expand and contract the method area to fit the application's needs. Also, the memory of the method area need not be contiguous. 
  6. The method area can also be garbage collected.As Java programs can be dynamically extended via user-defined class loaders, classes can become "unreferenced" by the application. If a class becomes unreferenced, a Java virtual machine can unload the class (garbage collect it) to keep the memory occupied by the method area minimum.
About loaded types, what kind of information is stored in method area?
 
About loaded types jvm stores following information:
  1. full qualified name of the type.
  2. full qualified name of type's direct superclass (except java.lang.Object and interface)
  3. type that is loaded, is that class or interface?
  4. modifiers that is used with class 
  5. constant pool for this type.
  6. all information about static variables except constant.
  7. field information as well as method information.
  8. reference to class ClassLoader and class Class.
Constant Pool
  1. A constant pool is an ordered set of constants used by the type, including literals (string, integer, and floating point constants) and symbolic references to types, fields, and methods. 
  2. Entries in the constant pool are referenced by index, much like the elements of an array. 
  3. As it holds symbolic references to all types, fields, and methods used by a type, the constant pool plays a central role in the dynamic linking of Java programs.
Field Information
  1. The field's name
  2. The field's type
  3. The modifiers being used ( public, private, protected, static, final, volatile, transient) 
  4. It also store the information about the order in which fields are declared inside the class or interface.
Method Information
  1. The method's name
  2. The method's return type ( or void)
  3. The number and type of method's parameters.
  4. The method's modifiers.
  5. In case of non-abstract methods and non-native methods , it also stores method's bytecodes
  6. The sizes of the operand stack and local variables sections of the method's stack frame.
  7. The Exception table. 
Class variables
  1. Before a Java virtual machine uses a class, it must allocate memory from the method area for each non-final class variable declared in the class.
  2. Constants (class variables declared final) are not treated in the same way as non-final class variables. 
  3. Every type that uses a final class variable gets a copy of the constant value in its own constant pool.
  4. As part of the constant pool, final class variables are stored in the method area--just like non-final class variables. But whereas non-final class variables are stored as part of the data for the type that declares them, final class variables are stored as part of the data for any type that uses them.
A reference to Class ClassLoader
  1.  Java virtual machine  keep track of how type was loaded weather via the bootstrap class loader or a user-defined class loader. For those types loaded via a user-defined class loader, the virtual machine must store a reference to the user-defined class loader that loaded the type
  2. The virtual machine uses this information during dynamic linking.When one type refers to another type, the virtual machine requests the referenced type from the same class loader that loaded the referencing type.
  3. This process of dynamic linking is also central to the way the virtual machine forms separate name spaces
A reference to class Class
  1. An instance of class java.lang.Class is created by the Java virtual machine for every type it loads. 
  2. The virtual machine must in some way associate a reference to the Class instance for a type with the type's data in the method area.  
  3. Your Java programs can obtain and use references to Class objects. One static method in class Class, allows you to get a reference to the Class instance for any loaded class: public static Class forName(String className);
  4. You can use forName() to get a Class reference for any loaded type from any package, so long as the type can be (or already has been) loaded into the current name space. If the virtual machine is unable to load the requested type into the current name space, forName() will throw ClassNotFoundException.  
  5. After getting reference to a Class object, you can find out information about the type by invoking methods declared in class Class. If you look at these methods, you will quickly realize that class Class gives the running application access to the information stored in the method area.
  6. Some of the other useful methods that can be useful at this level to introspect about the loaded classes are as follows:
  7. public String getName();
    public Class getSuperClass();
    public boolean isInterface();
    public Class[] getInterfaces();
    public ClassLoader getClassLoader();
      
----  NEXT POST WILL BE ABOUT HEAP AREA OF JVM, 
---KEEP VISITING
 

Tuesday, May 6, 2014

JVM Part4

... continuation of last post
TO understand the working of class loader , the following method is an important an important method.

protected synchronized Class<?>loadClass(String name,boolean resolve) throws ClassNotFoundException :
This method loads the class with the specified binary name. It has default implementation which searches for the class in following order:
  • It invokes findLoadedClass(String) to check if class has been already loaded.
  • Invoke loadClass(String) method on parent classloader, if parent classloader is null then classloader built in jvm is used.
  • Invoke findClass(String) method to find the class.
To set the parent class loader, we have two ways to do so in the ClassLoader constructor:

public class MyClassLoader extends ClassLoader{

    public MyClassLoader(){
        super(MyClassLoader.class.getClassLoader());
    }
}
or

public class MyClassLoader extends ClassLoader{

    public MyClassLoader(){
        super(getClass().getClassLoader());
    }
}
The reason to write a custom class loader in java:
  • It is required when we want to load the class from alternative repositories: This is the most common case, in which an application developer might want to load classes from other locations, for example, over a network connection.
  • It is required when we want to partition the user code:This case is not frequently used by application developers, but widely used in servlet engines.
  • It allows unloading of classes: As classloader maintains a cache of the classes that it has loaded, so these classes can not be unloaded until the classloader itself has been dereference. due to this reason ,system and extension classes are never unloaded, but application classes can be unloaded when there classloader is derefernce.
  • It helps to create the namespace: As jvm recognizes the class by the class name + name of classloader, so we can have have multiple copies of the same class across different classloaders .
How to write custom class loader ?
  1. In this case there has been variation with the release of jdk version, with java1, we need to subclass the ClassLoader class as it is abstract class and the =n override the loadClass() method.
  2. Then loadClass() has to fulfill various requirements like :
  • check weather class has been previously loaded.
  • check weather class has been loaded by system class loader.
  • loading the class.
  • linking the class.
  • resolving the class.
  • returning the class to the caller
Now in Java2 this scenario has changed 
  1.  In Java2 the ClassLoader class has been given a new constructor that takes parent class loader as a parameter .
  2. the parent classloader parameter can be application classloader or can be any user-defined class loader.
  3. Having this changes helps to follow delegation model very well .
  4. Under the delegation model, the loadClass() method is no longer abstract, and as such does not need to be overridden. The loadClass() method handles the delegation class loader mechanism and should not be overridden.
  5. custom class loaders should override only the new findClass() method, in which the code to access the new class repository should be placed. The findClass() method is responsible only for loading the class bytes and returning a defined class. The method defineClass() can be used to convert class bytes into a Java class:  
  example :    
   class NetworkClassLoader extends ClassLoader {
         String host;
         int port;

         public Class findClass(String name) {
             byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         }
         private byte[] loadClassData(String name) {
             // load the class data from the connection
         }
    }
 
 NameSpace:
  1. In java each classloader has its own namespace, means a single application can load multiple types with same fully qualified name.
  2. But some times full qualified name is not enough to identify the class inside the jvm, so in that case namespace comes into existence.
  3. If multiple types of that same name have been loaded into different name spaces, the identity of the classloader that loaded the type (the identity of the name space it is in) will also be needed to uniquely identify that type.
  4. Inside the jvm namespace arise as a result of resolution phase.
  5. As part of the data for each loaded type, the Java virtual machine keeps track of the class loader that imported the type.  
  6. When the virtual machine needs to resolve a symbolic reference from one class to another, it requests the referenced class from the same class loader that loaded the referencing class.
Important to improve the performance of classloading: 
If the parents fail to load the class, it will come down to the current ClassLoader itself. If it finds the class, it goes and stores it in its cache.

So the next time a classload is requested, and say , you found it in the cache - you can use it because you are assured that a parent delegation had occurred sometime in the past for this class .
So, its handy you remember this when you write your own classloader Lookup sequence:
CACHE (this.findLoadedClass()) >>> PARENT(super.loadClass()) >>> DISK(this.findClass() and then this.loadClass()).