Translate

Search This Blog

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, 13 August 2011

Type casting - Implicit and explicit

The basics
Whenever you create a class in java, you create a new data type. You can create instances of these classes  which are referred to as objects. To work with the objects you would need a variable through which you refer the objects, these are called as the reference variable and the object that the variable refers to is called the referred object.

Creating a reference variable with the java statement
         Employee employee;  (In general ReferenceType reference)
will not create an object of Employee instead it will just mean that we have created a reference variable for an object of type Employee.
This reference can hold the value of null or an object of ReferenceType  or any object whose type is subclass of ReferenceType.The reference type could be a interface/abstract class/class. The type of the reference determines how the referenced object i.e the object that is the value of the reference can be used,(you can use the behavior of the referenced object or its superclasses if any).  However, the object type of the referred object determines the behavior of the variable at runtime (FYI, polymorphism).


So what is casting?
Type casting happens when one data type is converted to another data type or it simply means treating a variable of one type as though its another type. There are 2 ways a casting can happen 
  1. Upcasting - also called widening conversions. Its easy to convert a subclass to the superclass, reason a subclass object is also a superclass object. Ex casting a SavingAccount object to an Account class variable is automatic.
  2. Downcasting - also called narrowing conversions, this requires an explicit cast and also that the object that is casted is a legitimate instance of the class you are casting too. When you code for explicit casting you tell the compiler, that you understand/take responsibility that the reference variable will hold an object of the reference type or its subclass. The JVM will then check for the correctness of this at runtime.
You can also cast an object to an interface provided that the object's class or any one of it superclass   implement the interface .

Casting can be applied to primitives as well. The primitives are placed in the following hierarchy/order,

             byte--- short---int---long---float---double.  \
Upcasting happens automatically when you go from left to right, but if you go from right to left explicit casting is required. Ex: Casting a short to a byte is possible, however if the value of the variable of type short exceeds the permissible value that can be handled by byte, then this conversion can lead to an overflow condition at runtime. Remember java does not inform us with exceptions, about overflow or underflow conditions, so care should be taken to understand the overflow and underflow behavior for such numerical conversions and computations.

When is ClassCastException thrown?
ClassCastException is thrown when you attempt to cast an object to a class of which it is not an instance.
Ex You cannot assign an Account object to a SavingAccount variable.   Although you could get away with the compile time error or Type mismatch error by explicit casting; it would fail at runtime with ClassCastException. A Type mismatch error also occurs when you try to reference a object of a different hierarchy. (Ex. trying to assign an employee object to an Account class variable)

You can deal with incorrect casting in 2 ways
  1. Catching the ClassCastException with the try-catch block
  2. Before casting use to instanceof operator to check if the object being casted is an legitimate instance of the reference type else be sure to deal with it either through the else block or the exception being generated.
NOTE:
You could also get a ClassCastException when two different class loaders load the same class because they are treated as two different classes.

What happens when you assign a reference variable with value null to a specific type. Say,   Account acc = (Account) acc1;  where acc1 is null. Casting has nothing to do with the value of the referenced object it just lets the compiler know that you know what you are doing (refer, Downcasting)

However, thing to note is when you have overloaded methods Example, myMethod(String s) and myMethod(Integer i) and you want to pass null as a parameter, then you need to explicitly cast so that the compiler knows which method to call, else it cribs saying the invocation is ambiguous.

Sunday, 26 June 2011

Inheritance versus composition in Java

are two important concepts you should swear by. Both help us to relate classes and achieve code resuse. But which one do we use?
Comparing inheritance and composition.
  1. In inheritance, a change to the method interface/definition of the superclass ripples down to the sublasses (if the method is overriden) and also to the clients of the sublasses thus making the superclass very fragile. In case of composition the change is limited to the containing class and not the clients.
  2. With inheritance, you cannot change the overriden method in the subclass without changing the superclass; reason it wont compile. With composition, you can change the interface of the method in the containing class that uses the method/behaviour of the contained class without touching it.
  3. In case of inheritance the classes are bound statically at compile time or as soon as the subclass is defined and will remain with the subclass till its lifetime. where as in case of composition, the behaviour can be changed at runtime.
  4. Though, with inheritance you can add new subclasses without affecting the code. Where as this is not the case with composition, unless you use composition with interface.
Going by the definition of inheritance, one should use it only if there is a IS-A relationship between classes and should not be merely used to get code re-use or polymorphism.
If you want to reuse code and there is no IS-A relationship , use composition and if you need polymorphism, but there is no IS-A relationship, use composition with interfaces.

I will add examples to explain each comparison points, in my next iteration of this post.
Resources

Thursday, 23 June 2011

Class Loaders - simplified - part 1

As discussed in my previous post, class loaders is one of the components of JVM. It is responsible for finding and loading the class at run time.

Classes are loaded into the JVM as they are referenced by name in a class that is already running in JVM. The first class is loaded into memory by invoking the static void main method of the class. All subsequent classes are loaded by classes which are previously loaded and running.

The following class loaders are created by the JVM
  1. Bootstrap or primordial class loader: Is the default class loader which is associated with the JVM. You can hook your own custom class loader instead of the default. All the JDK internal classes java.* packages i.e the ones that belong to rt.jar or i18n.jar are loaded by this class loader. (as defined in the sun.boot.class.path system property)
  2. Extension class loader: loads classes that are part of the extensions directory typically the lib/ext directory of the JRE are loaded by this class loader. (as defined in the java.ext.dirs system property)
  3. System class loader: loads classes that are part of the system class path (as defined by the java.class.path system property which is set by the CLASSPATH environment property, or -classpath / -cp command line options)
Classes loaded by different class loaders are placed into separate name spaces inside the Java virtual machine.
Class Loaders not just loads but performs the following activities in sequence.
  1. Loading - finding and importing the binary data of the type in the .class file.
  2. Linking - involves verification, preparation and resolution.
    • Verification - involves ensurinNumbered Listg that the binary data is structurally valid, else will throw VerifyError.
    • Preparation - involves allocating memory for class variables and initializing the memory to the default values.
    • Resolution - is the process of transforming the symbolic references from the type into direct references.
  3. Initialization - invokes code that initializes class variables to their proper starting values.
Class loaders use delegation model to load classes. Whenever a class requires to be loaded, the class loaders will contact its parents to load the class before they themselves try. Once the class loaders loads the class, the child class loader in the hierarchy will never reload the class. Classes loaded by the child class loaders have visibility into the classes loaded by parent class loaders but the reverse is not true. If there are sibling class loaders, then the sibling class loaders do not see the classes loaded by each other.


More on class loaders in my next blog. I will cover scenarios when you would encounter NoClassDefFoundError and ClassNotFoundException.


Wednesday, 22 June 2011

JVM

Java Virtual machine -is an abstract computing machine. It is the component of java technology that gives it hardware and OS independence. It has its own instruction set and manipulates various memory areas at run time.

The architecture as defined in the specification makes it possible to have different JVM implementation for different hardware platforms.The architecture of the JVM as defined in the specification is shown in the diagram below

It consists of
  1. Class Loader subsystem
  2. Run time data areas
  3. Execution engine
  4. Native method interface
  5. Native method libraries.
Class loader subsystem - is responsible for loading types (classes and interfaces). The .class files adhere to fix format and it contains JVM instructions or byte codes, a symbol table and other ancillary information.
Execution engine - is responsible for the actual execution of the instructions contained in the method of the loaded classes.
Run time data areas - the JVM organizes the memory it needs to execute a programs into various data areas. These various data areas may be shared by all the threads in the program or some data areas may be thread specific
  • The method area and heap is shared by all the threads
  • where as the PC registers,java stack, native method stack are thread specific.
Each instance of JVM has one memory area and one heap.
  • Method area: holds the details of each class loaded by the class loader subsystem.
  • Heap: holds every object being created by the threads during execution, including the main thread.

As each thread executes in the JVM, it gets its own PC register and the java stack. They are not shared among threads.

  • PC registers: For any executing thread the register holds the address of the next instruction to execute.
  • Java Stack: the stack stores the state of the method invocation (state - includes the local variables, the method parameters, the return value if any and intermediate or temporary calculations) of the thread (in stack frames - current execution method stack frame is the topmost)
  • Native method stack : the state of the native method are stored in native method stacks in an implementation dependent way, so also possibly the registers or an other implementation dependent memory areas.

More on class loader subsystem in my next blog.

You can find useful references


Java Platform

is a platform for java development. It is a software only platform which is ported on hardware platforms It comprises of two major components
  1. JVM - Java virtual machine - it is the component which add portability aspect to Java. JVM understand byte codes (compiled .class files from .java classes). Byte codes are the machine language of the JVM. JVM then interprets byte codes to the actual underlying machine language. Compilation happens only once and interpretation happens each time the program is executed.
  2. Java API - a set of classes written using java and which runs on the JVM. It consists of lot of useful classes which help us in development of applications etc.
You can find useful references