Friday, 24 May 2013

We know that functions can be overridden by inheritance but are instance variables overridden?
Go through the following code

We have a class called Superclass which has an instance variable name and an public method printName() to print it.

public class Superclass { private String name = "John";

public void printName() { System.out.println("Name is " + name); }}

Now we write Subclass which extends Superclass. This class also has an instance variable called name and a function with same name(overridden).

public class Subclass extends Superclass {

private String name = "Sam";

public void printName() { System.out.println("Name is " + name); }

}

Finally we do the following

Superclass myClass = new Subclass(); myClass.printName();

and guess what the output is? Even before that is it correct to have variables with same name is super class and subclass.

The answer is Yes!!
The output is : Name is Sam

Explanation

Simple explanation is only functions are overridden not the variables. When we call printName() function on myClass object it first check whether the reference type SuperClass has this function. if it is not there Java will throw an exception. Since it is present we can proceed. Now java will find what kind of object this actually is. It will travel down the inheritance tree and call the appropriate function of Subclass. Since name is Sam in SubClass it is printed.

Sunday, 19 May 2013

Reflection API in Java comes very handy to test class variables and methods at runtime. You can call it a type of hack as it violates the principle of DataEncapsulation. Let us see a code that demonstrates how can we access private variables using Reflection API and even edit it.

Output :

Explanation :

Note that the private variable name is in the Someclass class and our main method is in the Test class. According to OOP principles we should not be able to access the private variable name. Using the instance of the class myClass we get the declared field with name name. Then we set it accessible property to true. Then we can access it and print it(as shown in the output). Moreover we can also change it's value using Reflection API. fs.set(myClass, "Sam") method does that.

Saturday, 18 May 2013

If you see the source code implementation of Hashtable it is similar to that of map. Infact Hashtable implements Map interface.As of the Java 2 platform v1.2, this class was retrofitted to
implement the Map interface, making it a member of the
Java Collections Framework. For more information refer to Hashtable JavaDocs.

Output :

Understanding the code :

Code is very much similar to HashMap usage but has slight variations. Note Hashtable is a class and not an Interface. put() and get() method remain the same as that of HashMap. What is different is the concept of Enumeration. As specified earlier when Hashtable was introduced there was no Collections and hence no iterators. What we had to use was Enumeration. Enumeration is similar to Iterator. We check whether it has more elements using hasMoreElements() function, if yes access the next element using nextElement() function. Note the use of generics remain the same.

Few very common differences between a HashMap and a Hashtable are -

Hashtable is synchronized where as HashMap is not.

Hashtable does not allow null keys or values whereas HashMap allows one null key and any number of null values.

keys() method of Hashtable return Enumeration where as keySet() method of HashTable returns a Set which can be iterated over as it implements Iterable interface - Enumeration does not.

Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

One of HashMap's subclasses is LinkedHashMap,
so in the event that you'd want predictable iteration order (which is
insertion order by default), you could easily swap out the HashMap for a
LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

If synchronization is not an issue for you HashMap is recommended. If synchronization becomes an issue, you may also look at ConcurrentHashMap.

Background

This is a very interesting question. To give some background let me give an example - String Object in Java. You must have used it a lot but did you know that Strings are immutable. This means once you create a String object you cannot modify it.

Next obvious question that may arise is How do I get different String when I use methods like concat() or substring() ? The answer is you get a different String but not the modified one. Once desired operation is carried out and the result is computed a new String is created with this result and returned.You simply cannot edit a String instance which makes it immutable.

Having the background information let us now get back to our original question - How can we make such an immutable object/class?

How to make an object/class immutable?

First thing that we can do is make the class itself final. This means this class cannot be sub classed any further. So you can start with - public final class Person{}

Secondly make any data that you have in your class final. For example if you are creating a Person class you can define name, age, DOB etc Final.

final String name;
final int age;
final String DOB;

Once this is done you can be sure that the data will not be modified once it is initialized. But how do we initialize the data? We cannot use setter methods as final data cannot be modified.Hence we go for 3rd point.

Now create a constructor with these data as arguments and initialize the data.Now your class will look like -

This will make your class/object immutable. You can simple create object by saying Person p = new Person("John",21,"12/7/1991");
If you do not wish anyone to instantiate your class. You can provide a method like get public static Person getInstance(String name, int age, String DOB). Inside this function you can create an object of type Person and return it. You can also make your class singleton by checking if any instance already exists. There are many things you can do as per your implementation but the points mentioned above are sufficient to make a class/object immutable.

There can be more follow up questions like why would you make a class immutable?

Why prefer immutable object?

All atomicity and visibility issues that arise from multithreading are due such as race conditions, getting stale value, inconsistent state etc are due to multiple threads trying to access a mutable instance. If the instance is immutable these issue do not arise. Immutable objects are inherently thread safe.

NOTE : Immutable objects are always thread safe.

Summary

Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.

If the instance fields include references to mutable objects, don't allow those objects to be changed:

Don't provide methods that modify the mutable objects.

Don't share references to the mutable objects. Never store references to
external, mutable objects passed to the constructor; if necessary,
create copies, and store references to the copies. Similarly, create
copies of your internal mutable objects when necessary to avoid
returning the originals in your methods.

Sunday, 12 May 2013

Just to revise basic of Map go through it demo code. We will use the same piece of code and iterate over it.Purpose of this post is to demonstrate how can we iterate over a Map. We know Map interface does not implement Collection interface and hence we cannot just say someMap.iterator(). To revise Iterators refer to the post on understanding Iterators.Lets see then how do we iterate over a Map.

output :

Understanding the code :

As Map is not a Collection we cannot use .iterator() function on it. What we do is we create a set of Entry objects and iterate over it. Internally key-value pair are stores in Entry objects in the Map. We then get iterator of this set and iterate over it. Entry object has key and values stores in it and we can extract them using .getKey() and .getValue() methods.

Smarter Way :

This is a bit smarter way to do the same iteration. Internally it does the same thing i.e use a iterator and iterate over the Entry set.This may look a bit complex for beginners. So method mentioned above is recommended.

What if I only wish to iterate over keys or just values?

Yes there is a way to specifically iterate over keys and values in Map. The .keySet() function will return a set of keys where as .values() function will return Collection of values.Note once you have the Set you can get it's iterator and iterate over it's values.

Output :

Iterate over Values :

Output :

Values is John
Values is 18
Values is Male
Values is USA

Note : Keys in a Map are unique and hence .keySet() will return a set. Two different keys can have same value and hence values can't form a set(Values in a set are unique) and hence what you get from .values() is a Collection.

We have learned enough theory on Collections. We also saw a working demo code for ArrayList. In last post we saw why Map interface does not implement Collection framework and in the coming posts we will see how to iterate over the data in Map. But for now lets see a demo code of Map.

Output :

Understanding the Code :

We create a Map named persononalData to store personal information of some person named John. Note the generics used. Both key-value are of type String. At a later point of time if you try to put another data type(say int) then that is not allowed. You must always decide on the data structure before you start writing you actual code.In this case I am going to store everything as String.

We then start populating data. We add Name, Country, Age and Gender.Note the function is put(key,value) unlike add(element) in Collections.We then print the Map. Note when we say System.out.println(someMap) internally toString() method is invoked on the corresponding object and is printed to standard output.

Next we remove an element using .remove(key) method.Again we print out the Map to see the difference. Check out the output screen shot provided above.

Note : All keys in the Map must be Unique i.e you cannot store two different values for the same key. Lets say you do someMap.put("Name","John") and then again you say someMap.put("Name","Sam") then Sam will overwrite John and when you extract data by get("Name") you will get Sam and not John.

Next we extract age of the person using .get("Age") method. Note this will return you a String. But for comparison purpose you need an integer and hence we convert String to an int using Integer.ValueOf(SomeString) method.In our case age is 18 and hence age<18 will evaluate to be false and else part will get executed. Hence the output shown.

Hope basic operations in Map are clear. In next post we will see how to iterate over Map to manipulate it's data.

We saw what are Collections in Java. If you recall the diagram from that post Map does not form a part of Collection though it comes under Collection framework. In more technical terms Map interface does not implement Collection interface. Knowing this the question that naturally comes in mind is why so? Why can't Map be a part of Collection frame work? Let us see the explanation.

Reason for Map interface not extending Collection interface

If you look at the respective data structure you can easily guess why Map is not a part of Collection. Each Collection stores a single value where as a Map stores key-value pair. So methods in Collection interface are incompatible for Map interface.For example in Collection we have add(Object o). What would be such implementation in Map. It doesn't make sense to have such a method in Map. Instead we have a put(key,value)method in Map.

Same argument goes for addAll(), remove(), removeAll() methods. So the main reason is the difference in the way data is stored in Map and Collections.

Also if you recall Collection interface implemented Iterable interface i.e any interface with .iterator() method should return an iterator which must allow us to iterate over the values stored in the Collection. Now what would such method return for a Map? Key iterator or a Value iterator? This does not make sense either.

There are ways in which we can iterate over keys and values stores in a Map and that is how it is a part of Collection framework.Do not get confuse here. Let me repeat this - Map is a part of Collection framework but it does not implement Collection interface. We will see in next few posts how Map works internally(that's really an interesting topic) and also how we manipulate data in it.

Just to recall the Collection framework refer to the following diagram -

Yes that's the picture I posted on LinuxForGeeks today on the special occasion of Mother day. Let me take this occasion to clarify that people using CLI(Command line interface) are not some geeks who know something special which common people don't. Once you start using CLI you will know how much fun it is. For now let me introduce some cool commands.

Here are some command you may enjoy in your spare time -

fortune Fortune is a simple program that displays s pseudo random message from a database of quotations that first appeared in version 7 Uiux. Just type fortune in the CLI and see the various messages that are displayed.To install fortune type the following in CLI - sudo apt-get install fortune-mod

Some examples are as follows -

You get the point. For more info refer to its man page.Some options that you can use with the command are -

cowsayCowsay is a program(written in Perl) which generates ASCII picture with of a cow with a message It can also generate pictures using pre-made images of other animals, such as Tux the Penguin, the Linux mascot.To install cowsay just type in CLI - sudo apt-get install cowsay

Example -

You can use -f tux option to get a tux instead of a cow.That's not it. You can combine fortune and cowsay commands to have a bit more fun.Type the following in your CLIfortune | cowsay -f tux

espeakeSpeak is a compact open source software speech synthesizer for Linux.Just type espeak 'Hello World' in your CLI and you will hear the voice saying the argument supplied(Hello World). This is the default program installed on Ubuntu.It can also read from a text file supplied with -f argument. For more info you can refer eSpeakCommands.

Saturday, 11 May 2013

One of the general problem programmers land into is the NullPointerException. This post will mainly focus on how do we handle this null value. Specially in case of Collections what is the difference between and empty collection, a null Collection and a Collection containing a null value.

Before we see how to handle null value remember that member(instance) variables are assigned default values if they are not initialized where as for local variable you need to explicitly initialize them before using them.So when we define a referencetype as an instance variable it is by default set to null.Complete set of default values assigned to instance variables are as follows -

Good Practice

Important point to note while comparing String literals is always put the literal to the L.H.S(Left hand side) of the == or equals() operator. For example -String typeOfOS; if("linux".equalsIgnoreCase(typeOfOS)) { System.out.println("Very good choise of OS"); }
Why so you might ask? Reason is simple if your variable typeOfOS is null it will throw a java.lang.NullPointerException.

Handling null in Collections

It is important you understand the difference between a reference being null, Collection being empty and Collection containing null as an element.

Explanation : Here we create an object of List. Memory is allocated on the heap but there is no element in the List i.e the List is empty.You can check if Collection is empty or not by using .isEmpty() function.

Collections containing null as an element

Ground Work : We know List can have duplicate elements. This means a list can have multiple null values stored in it. Also in a Set duplicates are not allowed and hence only one null value is allowed. Never the less null is an acceptable value as an element in Collection. There are exceptions like EnumSet where null is not allowed but thats a rare usage.

Explanation : List is clearly not empty as we have added an element(null) to it. Whole point being null can be an element stores in a Collection.If you wish to remove null from the List you can simple say .remove(null).

Friday, 10 May 2013

A very simple question that most of the Linux beginners have. Which shell am i using? How can i change it?When you write any shell script you need to specify which shell you want to use to execute your script(Given as an argument to Shebang).

Be default on most of the distros the shell you have is BASH(Bourne-Again SHell). You can have other shells like CSH(C SHell), KSH (Korn SHell) etc.

Default BASH is as follows -

How to install other Shells?

Let us first see how can we install other shells, change from BASH(default) to new shell and back.Lets say you want to install KSH (Korn SHell) . Simply type ksh in your console. If it is installed you will directly see $ symbol instead of your normal aniket@aniket-Compaq-610:~$ representation.If you do not get such a change you will see program not installed. So now you need to install it.
Type sudo apt-get install ksh . Your ksh will now be installed. Again type in ksh which will bring you to korn shell with a $ symbol.To returnback to your BASH shell simple type exit and enter.

KSH (Korn SHell) looks like below -

Now lets get to our main question. How do we figure out what shell are we using.

What Shell I am using?

There are 3 Ways in which users generally check their Shell. Let me explain each of them.Note all the snapshots here after will be executed in KSH (Korn SHell) so ksh must be the answer we are interested in.This is just FYI but point is to find what shell are we using.

Just type echo$SHELL in your console(Not recommended method).

What this will give is your default Shell not your current shell. So in both BASH as well as KSH you will get output as /bin/bashScreen shot for the same is -

Type in echo $0 in your console(Simplest)

$0 gives you name of the Shell or Shell script you are using. Screen shot -

Type ps -p $$ in your console(the smart way)

$$ symbol gives you the PID of the process running your current Shell. PS command gives you the PID of various running process(Try ps -ax to see yourself). -p argument take the specific PID you wish to see. So ps -p $$ whill give you your Current Shell with PID.Screen shot -

In a script if the first line consists of characters number sign and exclamation sign (i.e #!) then such a sequence is know as Shebang or a Hashbang.

This hashbang takes arguments. The first argument is always the path to the interpreter that will be used to interpret the script code to follow.

Suppose you are writing a shell script then the 1st line of your script would be something like #! /bin/sh . Code which will follow this will be interpreted by your shell(whatever you have usually this is Bourne shell).

Another point to note that hashbang begins with a # character which is interpreted as comment in most of the scripts. So the corresponding interpreter will ignore this line.

Syntax

Syntax is very simple#! interprter [optional arg]

Note this must be the 1st line of your script.

The interpreter must usually be an absolute path to a program that should be used to interpret rest of the script code.

Example

Some usage examples are -

#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell

#!/bin/csh -f — Execute the file using csh, the C shell, or a compatible shell, and suppress the execution of the user’s .cshrc file on startup

#!/usr/bin/perl -T — Execute using Perl with the option for taint checks

#!/usr/bin/php — Execute the file using the PHP command line interpreter

#!/usr/bin/python -O — Execute using Python with optimizations to code

#!/usr/bin/ruby — Execute using Ruby

Purpose of a Hashbang

Purpose is fairly straight forward. Lets say you have a perl script(GetIP.pl) and perl module is installed at /usr/bin/install/perl . Every time you wish to execute this file(from any directory you are in) you will need to give the absolute path where perl module is located to run the script /usr/bin/install/perl GetIP.pl but using hashbang all you need to do is GetIP.pl . It will execute the script using perl module directly.

What happens behind the scene(Magic number)?

The Shebang is actually a human readable instance of magic number in executable file. The magic byte string being 0x23 0x21 , the two character encoding in ASCII. The magic number is detected by "exec" family of functions which determine whether the image file is a script or an executable binary. The presence of shebang will result in execution of specific executable, usually an interpreter for the script's language.

Sunday, 5 May 2013

Another favorite interview question. Honestly whole of Collections is an interesting topic and a lot of interview questions can be framed on it. Advantage of this being, Java knowledge of Candidate is tested along with his/her data structure knowledge.

So lets understand how ArrayList works. This is the most basic question you could frame. Many other questions to come are based on this.

Basic Data Structure used in an ArrayList is -

private transient Object[] elementData;

So it's an array of Object(Just the declaration.)
When we actually create an arrayList following piece of code is executed -

this.elementData = new Object[initialCapacity];

You create an ArrayList as follows -

List<String> myList = new ArrayList<String>(); OR

List<String> myList = new ArrayList<String>(6);

1st one invokes a default constructor while the second will invoke a constructor with an integer argument. When we create an ArrayList in the 2nd way it will internally create an array of Object with size specified in the constructor argument(6 in our case). Default value is 10 i.e if no size is supplied array with size 10 is created.

Once you tell this interviewer can be sure you know what data structure is internally used.Now we know ArrayList is better than normal arrays as it is size dynamically increases. But how does this take place internally? How much does the size increase?

Inside .add() method there is this check. Before adding element into the array it will check what is the current size of filled elements and what is the maximum size of the array. If size of filled elements is greater than maximum size of the array(or will be after adding current element) then size of the array must be increased. But if you know array basic you cannot dynamically increase the array size. So what happens internally is a new Array is created with size 1.5*currentSize and the data from old Array is copied into this new Array.

If you wish to know more you can view the ArrayList Sourecode. In Eclipse press Ctrl+T(Open Type) and type in ArrayList. Open it to view the source code.To visualize the ArrayList class refer to following image -

Background

If you are a beginner level Java developer and experimenting with Collections you may encounter this exception. Even I was taken with surprise when i first encountered such Exception.Let see why and when do we get such an Exception.
Before we proceed take a look at the Iterator Example code in the post on Understanding Iterators. We will refer to a lot of things from that post.

Output

Explanation

Why did we get this Exception. Reason is simple. When we Iterate using an Iterator, Iterator objects expects there should be no modification in the Collections which it points to. So how do we remove one might ask. For this reason we have .remove() method in Iterator interface. You can do something like below -

Having some idea about Collections in Java lets see what is an Iterator and what is it used for? As described in post on Java Collection an Iterator object is used to iterate over elements stored in a Collection.

You know that Collection is an Interface. Even List, Set, Queue are Interfaces which then have their own concrete implementations like ArrayList, HashSet, LinkedList etc. Collection Interface implements another Interface called Iterable.

If you go and open the sour code for Collection Interface in Java you will find -

Output

Understanding the code

First we create a ArrayList called nameList and store some values in it. Note the use of Generics. nameList will and should always contain a String. If you try to add any other object Compiler will complaint. Also when you extract any element from the List you will always get a String object.

Next we get an Iterator from the ArrayList. Note the Syntax. We can get such Iterator from any entity(interface/class) which come under Collection inheritance tree(Remember Collection implements Iterable). So we just need to use .iterator() function to get the respective iterator. Then we can iterate to get the elements. Note .hasNext() checks whether Collection(List/ArrayList in our case) has next element or not where as .next() will actually give you the next element.

Note : Map and its sub classes/ sub interfaces are not a part of Collections.So you cannot use .iterator() function on it. There are other was to iterate over it's data but we shall cover that separately.

When you talk about Collections, Generics are automatically introduced. After knowing basics of how Collections work let us explore the World of Generics.

Before we proceed to even understanding what generics is I want you remember one thing

"Generics is a Compile Time Concept"

By Generics you define what data type is associated with your Generic Class or a method. So at compile time when you do operations on your class or method compiler will always expect that generic type. Lets take an example to understand this better.

Lets say you have a List to store name of some people. This is how you do it.

List nameList = new ArrayList();

nameList.add("John"); // 0th index

nameList.add("Sam") ; // 1st index

etc

So far things look good. We created a List and we added some names to it. But now say I do something like below -

nameList.add(23); // 2nd index

Notice here 23 is not a String but an integer. Even if some one has a name called 23 we must say "23". But the point to note here is that one can add anything to the List at this point of time. So far so good. Code will Compile and even run.

Lets see where the problem might occur.

String name1 = (String) nameList.get(0);

String name2 = (String) nameList.get(1);

String name3 = (String) nameList.get(2); //Oops Error!

because 23 is a int and you can't type cast it into a String. Also note that even if you store and actual String every time we have to type cast it . Wondering if there is a better alternative ?

This is why we use Generics.

Let rewrite above example -

List <String>nameList = new ArrayList<String>();

nameList.add("John"); // 0th index

nameList.add("Sam") ; // 1st index

All good. Now lets add an integer -

nameList.add(23); // 2nd index

At this point compiler will give error. Compiler know nameList can only have String and cannot accept integer . Program will not compile so running program will never come into picture. That's why we say generics is used for compile time safety.

Now lets extract valued from the List

String name1 = nameList.get(0);

String name2 = nameList.get(1);

That's right! No need to type cast. Compiler will know that nameList only contains String and hence it will always return a String.Lets revise benefits of using Generics -

Why Generics?

Stronger type checks at Compile time :

A Java compiler applies strong type checking to generic code and issues
errors if the code violates type safety. Fixing compile-time errors is
easier than fixing runtime errors, which can be difficult to find.

Type Erasure

If you recollect I had mentioned in the beginning of this post that generics is compile time concept. This is also called type erasure. After compilation all generic code is replaced by concrete type. At Runtime there is no generics involved.

Knowing this fact try to answer following question. What would be the output -

Before we dive further into Collections let me take an example to show how Collections actually work.Lets take an List example as it is the most simple to understand. You can then try similar operations on Set and Queue. Not the functions remain the same for all as all three implement Collection interface. Only their implementations will vary.

Output

Explanation

First we create a List name nameList and then populate it with some values.Not the use of polymorphism(Superclass reference i.e List to subclass object i.e ArrayList). You can add values in any Collection using .add() method.Observer the .add(0, "kenny") method. You can specify index as the 1st argument. Since i have put 0 "Kenny" is added to the front of the list(index 0). .remove() is also similar. Either you can specify an object to be removed as an argument or index at which object is to be removed. You can print the size of collection using .size() method. There are various other methods in Collection that we will learn in time but for now these should suffice. You can now play around with other Collections like Set and Queue.

.clear() is another simple method to try. It will simple remove all emenets from the Collection. After this if you do .size() you will get 0.