Wednesday, November 18, 2015

Difference between Primitive and Reference variable in Java

There are two types of variables in Java, primitive and reference type. All the basic types e.g. int, boolean, char, short, float, long and double are known as primitive types. JVM treats them differently than reference types, which is used to point objects e.g. String, Thread, File and others. Reference variables are not pointers but a handle to the object which are created in heap memory. Main difference between primitive and reference type is that, primitive type always has a value, it can never be null but reference type can be null, which denotes absence of value. So if you create a primitive variable of type int and forget to initialize it then it's value would be 0, the default value of integral type in Java, but a reference variable by default has null value, which means no reference is assigned to it. If you try to access any field or invoke a method on null reference, you will be greeted with NullPointerException in Java. It's very important for every Java developer to understand difference between primitive and reference variable in different cases e.g. while assigning values, comparing values, passing them as method arguments and returning them from methods, to avoid nasty errors e.g. null pointer exception. In short, main difference between two types is that primitive types stores actual values but reference type stores handle to object in heap

Passing primitive and reference variable as method argument
 
When you pass primitive values to a method the values are passed to method, but when you pass reference variable, only handle is copied. which means for primitives, changing the formal parameter's value doesn't affect the actual parameter's value, while in case of reference types, changing the formal parameter's handle doesn't affect the actual parameter's address but changing the formal parameter's internal values does affect actual parameter's object, because they refer to same object in memory.

Tuesday, November 17, 2015

Does Java have pointers?

No, Java does not have pointers. This was an intentional decision by the creators of Java, because most people would agree that having pointers creates a lot of potential for bugs in the code – pointers can be quite confusing, especially to new programmers. Because arrays and strings are provided as class types in Java, there is no need for pointers to those constructs. By not allowing pointers, Java provides effectively provides another level of abstraction to the programmer.

Java has references, but not pointers

But, what Java does have is references, which are different from pointers. Here are some of the differences between references in Java and pointers in C++:


1. References store an address. That address is the address in memory of the object.
So, when a class is declared like so 

Test y = new Test();  
The "y" variable actually stores an address in memory. 
If you were to look at that address in  memory you would see the details of the Test object. 
Pointers in C++, however, point directly to the object.

2. You can not perform arithmetic operations on references. So, adding 1 to a pointer is not possible, but is possible in C++.

Diamond Problem



In the diagram above, we have 2 classes B and C that derive from the same class – which would be class A in the diagram above. We also have class D that derives from both B and C by using multiple inheritance. You can see in the figure above that the classes essentially form the shape of a diamond – which is why this problem is called the diamond problem.
The problem with having an inheritance hierarchy like the one shown in the diagram above is that when we instantiate an object of class D, any calls to method definitions in class A will be ambiguous – because it’s not sure whether to call the version of the method derived from class B or class C.

Java does not have multiple inheritance

But, wait one second. Java does not have multiple inheritance! This means that Java is not at risk of suffering the consequences of the diamond problem. However, C++ does have multiple inheritance

Java does have interfaces

Java has interfaces which do allow it to mimic multiple inheritance. Although interfaces give us something similar to multiple inheritance, the implementation of those interfaces is singly (as opposed to multiple) inherited. This means that problems like the diamond problem – in which the compiler is confused as to which method to use – will not occur in Java.

Method Overloading vs Method Overriding

The difference between overriding and overloading in Java is a common source of confusion – but it is fairly easy to understand with the examples we present below. Let’s start the discussion by talking more about method overloading first. Method overloading in Java occurs when two or more methods in the same class have the exact same name but different parameters (remember that method parameters accept values passed into the method). Now, two or more methods with the same name in the same class sounds simple enough to understand. But, what do we mean exactly by different parameters? Well, let’s consider a very simple example.

Suppose we have a class called TestClass which has two methods, and both methods have the same name. Let’s say that name is “someMethod”. Those two methods would be considered to be “overloaded” if if one or both of these conditions is true:

The conditions for method overloading

1.) The number of parameters is different for the methods.
2.) The parameter types are different (like 
changing a parameter that was a float to an int). 
 

How to NOT overload methods:

It’s also very important to understand that method overloading is NOT something that can be accomplished with either, or both, of these two things:
1. Just changing the return type of the method. If the return type of the method is the only thing changed, then this will result in a compiler error. 
2. Changing just the name of the method parameters, but not changing the parameter types. If the name of the method parameter is the only thing changed then this will also result in a compiler error.
 

Confused? Well, here are some very helpful examples of where overloading would be both valid and invalid – pay attention to the comments as well:

Examples of Method Overloading in Java – both valid and invalid:

//compiler error - can't overload based on the   
//type returned -
//(one method returns int, the other returns a float):    

int changeDate(int Year) ;  
float changeDate (int Year);    

//compiler error - can't overload by changing just 
//the name of the parameter (from Year to Month):    

int changeDate(int Year);   
int changeDate(int Month) ;  
 
//valid case of overloading, since the methods
//have different number of parameters:        

int changeDate(int Year, int Month) ;  
int changeDate(int Year);    

//also a valid case of overloading, since the   
//parameters are of different types:    

int changeDate(float Year) ;  
int changeDate(int Year);  

Overloading happens at compile time

Another important point to remember is that overloading is a compile time phenomenon. This just means that the compiler determines whether a given method(s) is correctly overloaded, and if not a compiler error is returned as shown in the examples above.

What about method overriding?


Overriding methods is completely different from overloading methods. If a derived class requires a different definition for an inherited method, then that method can be redefined in the derived class. This would be considered overriding. An overridden method would have the exact same method name, return type, number of parameters, and types of parameters as the method in the parent class, and the only difference would be the definition of the method.

Example of method overriding

Let’s go through a simple example to illustrate what method overriding would look like:
public class Parent {

 public int someMethod() {
   
   return 3;
       
    }
}


public class Child extends Parent{

 // this is method overriding:
 public int someMethod() {

    return 4;
       
    }

}

In the sample code above, someMethod is an overridden method in the Child class, because it has the exact same name, number of parameters, and return type as the someMethod method defined inside it’s parent class (conveniently named Parent).

Overriding happens at run time

Another important point to remember is that overriding is a run time phenomenon – not a compile time phenomenon like method overloading.
PD9waHAgaW5jbHVkZSAoJ2Fkc2Vuc2UtbWVkLXJlY3QyMDE0LnBocCcpOyA/Pg==

Summary of differences between overloading and overriding

Let’s summarize the differences between overloading and overriding. When overloading, one must change either the type or the number of parameters for a method that belongs to the same class. Overriding means that a method inherited from a parent class will be changed. But, when overriding a method everything remains exactly the same except the method definition – basically what the method does is changed slightly to fit in with the needs of the child class. But, the method name, the number and types of parameters, and the return type will all remain the same.
And, method overriding is a run-time phenomenon that is the driving force behind polymorphism. However, method overloading is a compile-time phenomenon.

Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency

In Object-oriented programming, one object is related to other to use functionality and service provided by that object. This relationship between two object is known as association in  object oriented general software design

Both Composition and Aggregation are form of association between two objects, but there is subtle difference between composition and aggregation

Association

Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example: A Student and a Faculty are having an association.

Aggregation

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.

Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Difference between aggregation and composition

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.
Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!


Abstraction

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.

Generalization

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specializtion to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.

Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.

Realization

Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

Example: A particular model of a car ‘Hyundai’ that implements the blueprint of a car realizes the abstraction.

Dependency

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Example: Relationship between shape and circle is dependency.