Showing posts with label object. Show all posts
Showing posts with label object. Show all posts

Friday, August 5, 2011

Java: Pass by Value

I was in an interview and interviewer asked me the following question.

public static void main(){
          String s1 = "A";
          s1 = s1 + 1;
          System.out.println("Before function call S1 is:" + s1);
          modifyString(s1);
          System.out.println("After function call S1 is:" + s1);
}

String modifyString(String a){
          a = a + 2;
          return a;
}

What is the output of the following problem?

Though I knew Java is pass by value but at the time of function call Java passes memory reference of the objects. So with the conviction I wrote the output of the program.

Before function call S1 is: A1
After function call S1 is: A12

Interview was over, I returned home, wrote the program and ran it in my eclipse. Bomb... It exploded. Results were not as I expected. WTF, why are those results not the same as I expected? I am the Java bond I can not be wrong. Instantaneously I pinged for an assistance. I wanted to hear "there is a problem with my eclipse instance. I should dump the current eclipse and take the latest eclipse soon." But instead hearing those words  I got following response.

Before function call S1 is: A1
After function call S1 is: A1

My expectation were shattered and I started arguing. Argument ended with my broken believe and I figured out "I have to cover a lot more about java fundamentals".

Anyways let me tell  you how does java pass the object to the function. In general java do not differentiate between Objects and primitive data type. It uses copy operation to pass the value of both type of data types.
If you have overridden copy method of your class then java will copy the object based of your implementation otherwise it will copy the object shallowly, in other words we say java uses shallow copy functionality of the objects. In case of shallow copy it creates a new reference to the object passed to the method. Now whenever you change in this method, are reflected back in the mutable classes, whereas in case of immutable classes it is not possible to change the object so we refrain ourselves to changing anything in those classes.

Lets review the following program.


public class PassByValueInJava {

int xy = 0;
private static void modifyPav(PassByValueInJava pav3 ,PassByValueInJava pav4) {
int temp  = pav3.xy;
pav3.xy = pav4.xy;
pav4.xy = temp;
}

public static void main(String[] args) {
PassByValueInJava pav1 = new PassByValueInJava();
PassByValueInJava pav2 = new PassByValueInJava();
pav1.xy = 10;
pav2.xy = 20;
System.out.println("Before Modify:::: pav1 x:" + pav1.xy + "   pav2 x:" + pav2.xy);
modifyPav(pav1, pav2);
System.out.println("After Modify::::pav1 x:" + pav1.xy + "   pav2 x:" + pav2.xy);
}

}


Can you guess what is the output of the program written here?
After seeing the above example I thought it should not switch the values. So results should be the following
Before Modify:::: pav1 x:10 pav2 x:20
After Modify:::: pav1 x:20 pav2 x:10

Now it is strange. Why did swapping happened? Was there something different?

Okay, lets analyze what has happened in this program? Main function calls the modify function and providing them the copy of pav1 and pav2. As copy is a shallow copy, so in this case Java will create a reference which will point to the same memory location of the previous object. Memory location depicts the situation well here.

Why did not same thing happened when string object was passed to the method.
As string in java are immutable so java deals with string in a different manner. Initially when S1 = A then string was pointing to one memory location and as soon as S1 = S1 + 1, it creates new string object and S1 was assigned to it.

Now when Main called modify function s1 was pointing to A1 memory location whose reference was passed to modify function. When string s2 got changed, then it started pointing to the A12 string object's memory location. But s1 is still pointing to the A1 string object's memory location. That is why value for s1 did not modify.

So it is clear that java always uses pass by value and as java tackles string in a complete different way, this is the reason we see such a huge difference between objects and strings.

Program mentioned above could enhance with the following


public static void main(){
          String s1 = "A";
          s1 = s1 + 1;
          System.out.println("Before function call S1 is:" + s1);
          s1 = modifyString(s1);
          System.out.println("After function call S1 is:" + s1);
}

String modifyString(String a){
          a = a + 2;
          return a;
}

It will result in the expected output.

Wednesday, June 30, 2010

Object Oriented Programming Part 2

In earlier post we have already discovered Object oriented programming, orientation, its fundamentals and features. Here we will take up next remaining questions.

These are the questions whose answer are we seeking here in these blogs…

ü  What is Object Oriented Programming?
ü  What are the fundamental concepts/Features of OOP?
ü  What is Object Based Programming?
ü  What is Procedural programming?
ü  What are the features of Procedural programming?
ü  Compare basic features of the OOP and PP?

First 2 questions have already been answered in the first blog. Here I will start with the third question.

What is Object Based Programming?

Object based programming is associated with objects, objects which consist fields and methods similar to OOP. In object based programming few features(Abstraction, Polymorphism, Encapsulations, Inheritance) of OOP are included. It is not wrong to say, OBP is a subset of OOP where subset has all the features except few.

As I am not concentrating more on this paradigm so I am not going to invest much of your time here.

What is Procedural programming?

In Procedural programming instead of data; structure of the program is the determining feature. Here programmer concentrate on structure of the program instead the behaviour and state of the object.

Edsger Dijkstra's structured programming, where the logic of a program is a structure composed of similar sub-structures in a limited number of ways. This reduces understanding a program to understanding each structure on its own, and in relation to that containing it, a useful separation of concerns.

At low level. structure programming composed of simple, hierarchical program flow structures. These are Sequence(Ordered sequence of statements), selection (Decision making conditions) and repetition(repetitive statements).

In current scenario Fortron, Basic are using structured programming. Branch of structures programming used by Procedural programming which is implemented in C.

Procedural programming is a branch of structural programming where procedure are created on the basis of structures. Procedures are routines, subroutines, functions and their sequence.

What are the features of Procedural programming?

As stated above the poles of the procedural programming are methods, modules, functional calls, variables whereas procedural programming does not have features like abstraction, encapsulation, inheritance and polymorphism.

Methods: These can be understand as the basic feature. We create the structure of the program, divide it into sequence, selection, repetition and accordingly divide one routine to different subroutines and achieve the desired functionality.

Modules: n number of subroutines creates a module where all subroutines are scope specific.

functional calls: As oops uses messages pass between object here it is achieved by functional calls.

Variables: As PP does not belong to object, so each routine has its own variables associated with function’s scope.

Compare basic features of the OOP and PP?

Till now it is understood that Procedure based programming is much closer to deal with structure on the other side OOP only deals with objects, and blueprint of the objects.

Pros and Cons of PP: Procedure based programs tends to run quickly and use system resources efficiently. Whereas the drawback is that it does not fir gracefully with certain type of problems, such as in this paradigm programmer is forced to use structure approach to reach to the conclusion.

Pros and Cons of OOP: OOP is very similar to the perception of world, so it is less difficult to visualize things there. Code reuse is another big advantage of OOPS which is one among the hard hitting drawbacks of PP. OOP is runtime inefficient. It needs more memory and resource to run the program.

If we summarize the whole story, it is evident that none of the paradigm is inferior or superior. It is just our requirements which makes one preferred to us. To finalize the paradigm there are few factors which should be taken into account. First we should look for the data structure of the problem and accordingly should decide the paradigm. Benchmarking is another aspect which effects mostly testing efforts a lot. These 2 factors could highlight the preferences of selecting the programming structure.

I will take a break now. Again I am open to discussions, please post me your queries in comments.

Disclaimer: All the material here is the result of research and understanding of other material. If there is some content which is either incorrect or inappropriate to the context of the article I am always open for discussion.

Thursday, June 17, 2010

Object Oriented Programming

Java is called Object Oriented Programming where as C called Procedure oriented programming. There are always confusion and enquiry. It is always a question why did new paradigm evolve when there was already existing paradigm which did not have much hassles.

There are few questions which always click to mind. Few are as following

ü  What is Object Oriented Programming?
ü  What are the fundamental concepts/Features of OOP?
ü  What is Object Based Programming?
ü  What is structured programming?
ü  What are the features of structured programming?
ü  Compare OOP and SP?

These are the few questions that have been troubling me for past few years. Now when I am four years senior in IT then it feels best to start looking for answers and understand them.

What is Object Oriented Programming?

Object Oriented Programming known as OOP is a programming paradigm which relies on data. It is a paradigm which represents data and its use. So basically an object is a representation of data structure which consist fields and methods, which provides a way a interaction between each other.

OOP concepts were mainly introduced for maintainability of code. Earlier people were having function oriented approach, which was becoming difficult to maintain in the long term. To get rid of this tedious process orientation moved to data and communication of data, which was introduced in OOP. OOP is a collection of interacting object having communicating facilities between objects. The technology focuses on data rather than processes/procedure/functions.

Simula was the first language which introduced the concepts of OOP, it was followed by LISP. Well known language to us is JAVA.


public class DemoClass {

                private int test = 0;

                public int getTest() {
                                return test;
                }

                public void setTest(int test) {
                                this.test = test;
                }
               
}

Here class DemoClass has a variable which has an integer as field who is deterministic factor to define the state of the object of the class (We will discuss private and public modifier later). getTest method will provide the state of the variable whereas setTest method will change the existing state of the test variable.

This class uses oops fundamental where it is designed around data instead of procedures/functions.


class InteractWithDemo{
               
                DemoClass testDemo = new DemoClass();
                public void useTestDemo(){
                                testDemo.setTest(10);
                                testDemo.getTest();
                }
               
}


PS: Please ignore the syntax if you are not aware.

InteractWithDemo class works as interacting class with the class created above. It creates an object of DemoClass and change the state of the DemoClass's object. This is the way objects interact with each other.

What are the fundamental concepts and Features of OOP?

Foundation of every entity is kept on fundamental concepts and it is appreciated on the basis of features. OOP also have few fundamental concepts and few others important and fascinating features.

Following are the fundamental concepts and Features of OOP

ü  Object
ü  Class
ü  Instance
ü  Method
ü  Interface
ü  Package
ü  Message Passing
ü  Abstraction
ü  Encapsulation
ü  Polymorphism
ü  Inheritance

These are the fundamental concepts along with that features of OOPS. Let’s discuss them in details further.

Object

Object is any entity who has characteristics, behaviours and state. In our day to day we see lots of object. Every human in itself is an object. How? Each individual has few characteristics which can be used to uniquely identify him. E.g. A person has name, DOB, parents name which are used to uniquely identity him. The same guy will have some habits. His state can be his age, marital status, job status, property balance and many more things. So a human being is an object. Similarly we have software concepts.
There are few advantage listed to have objects:
ü  Modularity
ü  Information Hiding
ü  Code Re-Use
ü  Pluggability and Debugging Use Case.

Class

Class is the blue print of the Object. Class is to hold the state and the behaviour of the entity. In the example given above, here to define a state of a human being following is the information that may suffice to define a unique person
  • Name
  • DateOfBirth
  • Father's name
  • Mothers' Name

These 4 attribute can tell the characteristics of the human along with that we can more variable to define the state and accordingly there can be few methods which define characteristics.

Instance

Instance is an occurrence or copy of an object. Multiple instances, of a class share, same set of attributes whereas value of the attributes may differ for each instance.

Methods

Method is a subroutine which is either associated to a class or to an instance of object. Method is a sequence of the statement to perform an action on the instances of objects or classes. Method may have inputs which are either processed or used to modify the state of the object. Few methods return the required datatype.

In case of OOP, methods provide the mechanism for accessing and manipulating the encapsulated data of the object.

In OOP these are type of methods:
  • Static methods - Mainly associated with the class.
  • Instance Methods - Affiliated with the instance of the class i.e. object.
  • Constructor - Cannot be called explicitly, in general these methods are used for initialization purpose.
  • Abstract Methods - These methods do not body defined for it (Implementation of the method is not given) i.e. sequence of instructions are defined by some other class.
  • Destructor - Cannot be called explicitly, in general these methods are used for object destroy purpose.

Interface

Best example to define interfaces will be a TV Set with a remote functionality. E.g. let’s say Videocon has different types of TV, where display type, screen size are different but company wants to create a generic remote for all. So Generic Remote is an interface to interact with TV object of various types of TV classes.

Here interface remote will be implemented by each TV class to perform actions guided by user.
Interface defines the behaviour to interact with outside the world.


                interface Remote{
                                void increaseVolume();
                                void reduceVolume();
                                void nextChennal();
                                void previousChannel();
                                void changeChennalTo(int);
                }


As defined above interface remote has defined five methods. Implementations of these methods have not been provided in the interface. Now when a class implements an interface it will implement all methods.  Interfaces form a contract between the class and the outside world, whereas this contract is enforced at build time by the compiler.

Package
Package is similar to the folders in windows, which are used to manage the data better and efficient. Packages are the namespace which provide better overview and understanding of the classes and their utilization. It is recommended, while coding related objects should belong to the same package.

Message passing

Message passing is a method of communication where sender sends messages to one or more than one recipients. These forms of message are method invocation, signal and packets.
In case of OOP invocating a method from object, class or other object is called message passing. The order in which message have been passed in their reversal order method responses are received by the sender.

Abstraction

An "abstraction" (noun) is a concept that acts as super-categorical noun for all subordinate concepts, and connects any related concepts as a group, field, or category.
In OOP abstraction is used to provide bare minimum information at the user level. The information which matters the user most is provided. Abstraction asks to make sure to provide minimal information. As user does not internals of the class, object, database and design it is not even altered with the changes of inside the objects.
The best thing of abstract is that this decouples the user of the object and its implementation. So now object is easy to understand and maintain also. As if there is any change in the process of some operation. You just need to change the inner details of a method, which have no impact on the client of class.

Encapsulation

Encapsulation is data hiding or reducing the access to others. Here it is made sure that every field of the class should not be accessible from the outside world. They should be taken care by methods and their accessibility should not go beyond the boundaries of the class. Encapsulation is a tool which provides the way to implement abstraction for a class.

Inheritance

Inheritance is well known terminology used in programming fundamentals. Inheritance is child’s rights on his father’s property. i.e. anything that belongs to father will belong to child until unless father explicitly mentions his wishes. Same inheritance is applied in Java, if class is child of a class it means it will be able to use all the members other than private members.

Usage of inheritance is very important in reusability of the code, which reduces the efforts of rewriting the same code again.

Polymorphism

It is a paradigm where values of two different data type are handled by uniform interface. In other way 2 methods or fields name can co exist with different set of parameters?
Polymorphism is better known as providing similar functionality to different set of parameters. In java achieving polymorphism is possible in 2 ways. Overriding and overloading which will be analyzed in the further discussions.
 

Disclaimer: All the material here is the result of research and understanding of other material. If there is some content which is either incorrect or inappropriate to the context of the article I am always open for discussion.