Saturday, 11 May 2013

Handling null in a Collection.

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 reference type 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.

  1. Reference being null

    List<String> operatingSystems = null;
    if(null == operatingSystems)
    {
        System.out.println("operatingSystems reference has not been initialized yet");
    }


    Explanation : No memory is allocated on heap in this case. This is just a reference that we have declared. We can check it for null as shown above.
  2. Collection being empty

            List<String> operatingSystem = new ArrayList<String>();
            if(operatingSystem.isEmpty())
            {
                System.out.println("List is empty");
            }


    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.
  3. 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.

            List<String> operatingSystem = new ArrayList<String>();
            operatingSystem.add(null);
            System.out.println("List is " + operatingSystem);
            if(operatingSystem.isEmpty())
            {
                System.out.println("List is empty");
            }
            else
            {
                System.out.println("List is not empty");
            }


    Output :



    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

How to find current Shell in Linux?

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 return back 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.

  1. 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 -


  2. Type in echo $0 in your console(Simplest)

    $0 gives you name of the Shell or Shell script you are using. Screen shot -
  3. 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 -
  4.  
     Play around with different Shells. Each have their own flavor. 

What is Shebang or Hashbang in Unix/Linux?

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

Interview Question #10 How ArrayList works internally in java?

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.

Code for it is as follows -

    public ArrayList(int initialCapacity) {
    super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
    this.elementData = new Object[initialCapacity];
    }



    public ArrayList() {
    this(10);
    } 



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.

Code for it is as follows -

    public boolean add(E e) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
    }



    public void ensureCapacity(int minCapacity) {
    modCount++;
    int oldCapacity = elementData.length;
    if (minCapacity > oldCapacity) {
        Object oldData[] = elementData;
        int newCapacity = (oldCapacity * 3)/2 + 1;
            if (newCapacity < minCapacity)
        newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
    }
    }



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 -



Related Links


Saturday, 4 May 2013

Most useful shortcuts in Eclipse.

As mentioned earlier for writing and debugging Java code there are two widely used IDE's
  • Eclipse
  • Netbeans
Though each of them have their own pros and cons, Eclipse is the most common choice of the programmers. Main reason being it's simplicity.



So lets take a look at various shortcuts that come handy while using Eclipse.


Manage Files and Projects

Ctrl + N Create new project using the Wizard
Shift + Alt + N Create new project, file, class, etc
Ctrl + Shift + R Open Ressource (file, folder or project)
Ctrl + S Save current file
Ctrl + Shift + S Save all files
Ctrl + W Close current file
Ctrl + Shift + W Close all files
F5 Refresh content of selected element with local file system

Navigate in Editor

Ctrl + L Jump to Line Number. To hide/show line numbers, press ctrl+F10 and select 'Show Line Numbers'
Ctrl + Q Jump to last location edited

Indentions and Comments

Tab / Shift + Tab Increase / decrease indent of selected text
Ctrl + I Correct indention of selected text or of current line
Ctrl + F Autoformat all code in Editor using code formatter
Ctrl + / Comment / uncomment line or selection ( adds '//' )
Ctrl + Shift + / Add Block Comment around selection ( adds '/*... */' )
Ctrl + Shift + J Add Element Comment ( adds '/** ... */')

Editing Source Code

Ctrl + Space Opens Content Assist (e.g. show available methods or field names)
Ctrl + 1 Open Quick Fix and Quick Assist

Code Information

Ctrl + O Show code outline / structure
F2 Open class, method, or variable information (tooltip text)
F3 Open Declaration: Jump to Declaration of selected class, method, or parameter
Ctrl + T Show / open Quick Type Hierarchy for selected item
Ctrl + move over method Open Declaration or Implementation

Refactoring

Alt + Shift + R Rename selected element and all references

Run and Debug

Ctrl + F11 Save and launch application (run)
F11 Debug
F5 Step Into function
F6 Next step (line by line)
F8 Skip to next Breakpoint
F7 Step out
t> UA-39527780-1 back to top