Monday 6 January 2014

Prototype Language

Most of us are thinking that JavaScript is object oriented programming language.Actually it is not. we will get confuse when we say Java is object oriented programming language and JavaScript is prototype based language. lets see the difference between them.

In Object Oriented Programming language everything will be represented as classes and Instances. Prototype based language is in which behaviour reuse (known as inheritance) is performed via a process of cloning existing objects that serve as prototypes.

For example "Fruit" is an object. It represents the properties and general functionalities of fruit. Another object "Strawberry" would be cloned from "fruit" object  and would also be extended to include general properties specific to bananas.
In prototype-based languages there are no explicit classes and objects inherit directly from other objects with which they are linked through a property, often called prototype as in the case of Javascript.

Equally equals the equal() method !!

Equals and hashcode are very important in Java. Its better to know about equals method in detail so that we can make use of it properly.I have shared here some details about equals in java that I have known. Please do read other websites also for further clarification.
Equals is the method which is implemented by Object class(Super class of all classes). Equals will compare the object reference. If equals method is not overidden then it will compare the reference of object. The following are some comparison concepts

-- Lets consider a and b as an object of some class.

Reflexive : Object must be equal to itself.
Symmetric : a.equlas(b) - return true then b.equals(a)// if a object refernce is same as the b object reference
Transitive : a.equals(b) - return true, b.equals(c) - return true then a.equals(c) will return true. // a,b,c object refernce are same
Consistent : If two object reference are equal then it will be equal until any of their properties are changed.
Null comparison: a.equals(null) -return false && null.equals(a) -null pointer exception // If object is compared with null then it will return false.If null is compared with object then it will throw nullpointerexception.

EQUALS AND HASHCODE :
--------------------------------
* If two obecjts are equal then Hashcode must be same of those objects.
* If two objects are not equal then Hashcode may be same or may be not.
-------------------------------------------------------------------------------------------------------
Always override equals method is advisable
-------------------------------------------------------------------------------------------------------

So this was the basic theory about equals method in Java now we are going to discuss the approach on how to override equals() method
Overriding Equals Method: This is the standard overriding equals method which is followed by most of Java programmers.
Before Overriding equals method its better to check the following conditions

1) Check if object is Null
2) Check this is equal to object if yes return true
3) instanceof method will return true though subclass object is given for comparison. So better go for getclass() method.
-----------------------------------------------------------------
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
-----------------------------------------------------------------
Once you checked all conditions then type cast object into your class.Then compare each instance variable of the object are or not. Here is the example of overriding equals method.

-------------------------------------------------------------------------------------
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}

Person guest = (Person) obj;
return id == guest.id
&& (firstName == guest.firstName
|| (firstName != null && firstName.equals(guest.getFirstName())))
&& (lastName == guest.lastName
|| (lastName != null && lastName .equals(guest.getLastName())));
}
--------------------------------------------------------------------------------------

Errors we can expect while overriding:
1) Instead of overriding,most of people will do overload. Equals method takes an argument as an Object datatype. While overriding there are chances of giving parameter type as direct class name. For example, public boolean equals(Person obj).
2) Some times we will forget to do casting and we will start comparing the instance variable. For Example, we may forget to do person guest=(Person)obj.
3) Its not enough to check only object is null or not. We also need to check instance variable is null or not. If any instance variable is null then there is a chance of null pointer exception. For example,
firstname == guest.firstname || (firstname != null && firstname.equals(guest.firstname)));
4) If equals method is overriden then hashcode method is also to be override. Else Hashmap will not function properly. Hashmap is based on key pair value. Hashmap works on both equals and hashcode method.

TIPS :

1) If your class has any unique instance variable then in equals method its enough to compare that unique instance variable. For example, In person class all names are unique then its enough to compare personName variable in equals method.
2) equals method are safe in Immutable class than in mutable class.
3) Wrapper classess such as String, Integer, Float etc equals method can be overriden but equals method of StringBuffer class can't be overriden

Thursday 26 December 2013

Expect the EXPECTION and handle it !!

Its always better to handle an exception in java program.Exception will interrupt the program flow and affect robustness of program.Once exception occurs it will stop the further execution. So better handle exception and dont scared users by not handling exceptions:p Please go through below for exceptions and also refer other sites too.

What is an Exception?
*************************
It’s a non functional requirement for any application, to gracefully handle any erroneous condition like resource not available, invalid input, null input, index not available and so on.Java Exception are divided into two categories as checked Exception and unchecked exception.
Checked Exception: Exception that can be identified during compile time. Basically Exception will throw compilation error.
UnChecked Exception: Exception which can't be predicted during compile time is unchecked exception. Unchecked exception is the exception which will occur during runtime.
Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking method with illegal arguments. Unchecked exceptions are the direct subclass of RuntimeException.
Errors:Errors are serious runtime environment problems that are almost certainly not recoverable. Some examples are OutOfMemoryError, LinkageError, and StackOverflowError. They generally crash you program or part of program. Only a good logging practice will help you in determining the exact causes of errors.

Implementation of Exception:
******************************
Checked exceptions can be handled by throws keyword. Throws will be declared on the method. Throws will not be used inside of any method. Checked exceptions such as IOException, Sql Exception can be throwed by throws. Throws can be able to throw more than one exception at a time using comma operator. syntax are as folows.
---------------------------------------------------------------------------------------
public static void main(String[] args) throws IOException,SQLException{
// body of function
}
---------------------------------------------------------------------------------------

Unchecked exceptions can be handle by try catch block. Block of code which may throw exceptions during runtime will be declared inside try block.Try block could state that code which is there inside of me may or may not throw exception. If its standard exception such as Nullpointer exception, Indexoutofexception etc then compiler will throw an exception. If its custom exception then programmer has to throw that exception explicitly.For Example, you want to throw an exception of below age if age is less than 18.This is custom exception and not standard exception.

-------------------------------------------------------------
public void method1()
{
String[] firstName= new firstName[2] ;
int age;
// getting input of age and first name here
try{
if(age is < 18)
{
throw new outOfAgeException("Below age");
}
System.Out.println(firstName[2]);
} System.out.println(null);
}
-------------------------------------------------------------
In the above example custom exception is "below age" and standard exception is " IndexoutofException". Exception will be handled for the codes is there inside the try block.So null pointer will not be able handle but it will be thrown. Catch block will be used for handling an exceptions. More than one catch block can also be declared. If you are declaring more than one catch block for handling an exceptions then it should be in an order of specific to generic. Suppose you are declaring catch for Arrayindexoutofexception and exception. Then catch block with arrayindexbound should come first and catch block with General exception should come next.Lets see what will happen if we declared general exception first. If we declare catch block with general exception first, then all exceptions will be caught by catch block with general exception. Even arrayindexbound exception will also be caught by catch block with general exception and it cant be catch by catch block with arrayindexbound exception. Here is an Example.
------------------------------------------------
catch(arrayindexboundException arr)
{ LOGGER.error("Checkout your array index", arr);
} catch(Exception e)
{
LOGGER.error("Some information", e);
}
------------------------------------------------

Stacktrace: Stackrace is use to find root cause of an exception. Once function is called its reference will be saved in stack. If that function throws any exception then pointer of stack will go back to find the root cause of an exception.Mainly stacktrace will be useful debugging and tracing your code.

Tips for handling an Exception:
*****************************************
1) Always use Finally block if you are handling an exception. There some situations where we need to close database connection, file connection etc. Such statements can be written in finally block. Once exception is occurred, your application will be stopped abtruptly but statements which has been declared inside finally block will be executed.Code inside the finally block will be executed though exceptions are thrown or not.Always clean up after handling the exception.
2)In catch block don't do return null. In that case, exception could be swallowed and stacktrace couldn't find root cause.

-----------------------------------------
catch (NoSuchMethodException e) {
return null;
}
-----------------------------------------

3) use always standard exception so that other programmers can also understand about that exception. If you are using custom exceptions then document all exceptions in your application in javadoc
4) Don't throw any exceptions from finally block.
5)Validate user input to catch adverse conditions very early in request processing.
6)Always include all information about an exception in single log message.
-----------------------------------------
LOGGER.debug(“Using cache sector A”);
LOGGER.debug(“Using retry sector B”);
-----------------------------------------
Don’t do this.

Happy Learning !!



Monday 23 December 2013

Show Encapsulation by hiding data!!

One of the most important feature in Java is Encapsulation. Here I am going to brief about encapsulation.Hope it will be useful for you.Don't come into the conclusion only with this blog.Dig other site also to get more information about encapsulation.

There will be some situations where we required to show only some information not all.How can we implement that ? For example,Its enough to show overall attendance percentage to students. But when it comes faculty, all details need to be displayed.Here students will be the class and Faculty will be the class. Attendance here is the data. What we are doing here is we are protecting and hiding data from student class.How can we acheive this? The solution for this question is Encapsulation. Encapsulation is about to protect the data(varaibles), information(methods) etc.By using access modifiers such as public, protect, default and private we can implement encapsulation.

Encapsulation is also for protect information which are prone to change. Encapsulation is used to maintain code just in one place. not scattered around code is easy to change.This can be better explained with an example.There a class called loan and it has a parametrized constructor.Other class have an instance using this constructor. Now requirements have changed to add another parameter in constructor. So you need to change everywhere you are calling this constructor. This is what code is scattered and encapsulation can handle it by access specifier.

Example of Encapsulation in Java
*********************************
class Loan{
private int duration; //private variables examples of encapsulation
private String loan;
private String borrower;
private String salary;

//public constructor can break encapsulation instead use factory method
private Loan(int duration, String loan, String borrower, String salary){
this.duration = duration;
this.loan = loan;
this.borrower = borrower;
this.salary = salary;
}

//no argument consustructor omitted here

// create loan can encapsulate loan creation logic
public Loan createLoan(String loanType){

//processing based on loan type and than returning loan object
return loan;
}

}