Friday 24 May 2013

Can Instance variables be overridden by inheritance in Java?

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

Accesing private variables using Reflection API

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 Data Encapsulation. Let us see a code that demonstrates how can we access private variables using Reflection API and even edit it.

Code :


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

}

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String args[]) throws Exception
    {
       
Someclass myClass = new Someclass();
        Field fs = myClass.getClass().getDeclaredField("name");
        fs.setAccessible(true);
        System.out.println("Variable is " + fs.getName() + " and value is " + fs.get(myClass));
        fs.set(myClass, "Sam");
        System.out.println("Variable is " + fs.getName() + " and value is " + fs.get(myClass));
    }
}

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.

For more details you can refer to it's documentation.
  

Saturday 18 May 2013

Hashtable example in Java.

In last post we saw difference between a HashMap and a Hashtable. Let us now see what Hashtable is and how do we use it.

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.

public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable
{...

Lets see how can we use Hashtable.

Code : 

package testCodes;

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableDemo {
    
    public static void main(String args[])
    {
        Hashtable<String, String> hashTable = new Hashtable<String, String>();
        //Populating Hashtable
        hashTable.put("Name", "John");
        hashTable.put("Country", "USA");
        hashTable.put("Gender", "Male");
        //Printing whole table
        System.out.println("hashTable : " + hashTable);
        //printing individual values
        Enumeration<String> data = hashTable.keys();
        while(data.hasMoreElements())
        {
            String str = (String) data.nextElement();
            System.out.println(str + " : " + hashTable.get(str));
        }
    }    
}

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.

 Related Links

Interview Question #12 Differences between HashMap and Hashtable?

There are several differences between HashMap and Hashtable. Hashtable was introduced earlier whereas HashMap is a newly introduced as a part of Java Collection Framework.

  • Hashtable is synchronized whereas HashMap is not.This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  • 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.


Related Links

Interview Question #11 How to make an object/class immutable and Why?

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 -


    public final class Person {
        private final String name;
        private final int age;
        private final String DOB;
    
        public Test(String name, int age, String DOB) {
            this.name = name;
            this.age = age;
            this.DOB = DOB;
        }
    }
    
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

  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
  2. Make all fields final and private.
  3. 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.
  4. 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. 

Related Links

Sunday 12 May 2013

How to iterate over a Map in Java?

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.

Java Code : 

package testCodes;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapDemo {

    public static void main(String args[]) {
        Map<String, String> persononalData = new HashMap<String, String>();
        // Populating Map with data
        persononalData.put("Name", "John");
        persononalData.put("Country", "USA");
        persononalData.put("Gender", "Male");
        persononalData.put("Age", "18");
        Iterator<Map.Entry<String, String>> mapIterator = persononalData
                .entrySet().iterator();
        while (mapIterator.hasNext()) {
            Map.Entry<String, String> keyValuPair = mapIterator.next();
            System.out.println("Key is " + keyValuPair.getKey());
            System.out.println("Value is " + keyValuPair.getValue());
        }
    }
}

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 : 

        for (Map.Entry<String, String> keyValuePairs : persononalData
                .entrySet()) {
            System.out.println("Key is " + keyValuePairs.getKey()
                    + "and value is " + keyValuePairs.getValue());
        }

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.

Iterate over keys : 

        for (String key : persononalData.keySet()) {
            System.out.println("Key is " + key);
        }

Output : 

Key is Name
Key is Age
Key is Gender
Key is Country

Iterate over Values : 

        for (String value : persononalData.values()) {
            System.out.println("Values is " + value);
        }

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.

Related Links

Simple Map example in Java.

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.

Java Code demonstrating Map usage

Code :

package testCodes;

import java.util.HashMap;
import java.util.Map;

public class MapDemo {

    public static void main(String args[]) {
        Map<String, String> persononalData = new HashMap<String, String>();
        // Populating Map with data
        persononalData.put("Name", "John");
        persononalData.put("Country", "USA");
        persononalData.put("Gender", "Male");
        persononalData.put("Age", "18");
        // Printing Map
        System.out.println("Map is " + persononalData);
        // removing data from Map
        persononalData.remove("Gender");
        // Printing Map
        System.out.println("Map is " + persononalData);
        if (Integer.valueOf(persononalData.get("Age")) < 18) {
            System.out.println("You are a minor");
        } else {
            System.out.println("You are a Major");
        }
    }
}

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.

Related Links

Why Map is not a true Collection?

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 -




A little fun with Linux command line!


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 -

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

     
  2.  cowsay
    Cowsay 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 CLI
    fortune | cowsay -f tux
  3.  
  4. espeak
    eSpeak 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

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

Why and when can we encounter ConcurrentModificationException in Java.

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.

Now if you recall the Iterator interface it was like -

public interface Iterator<E>

{
    boolean hasNext();
    E next();
    void remove();
}


Iterator object has a remove function but generally beginners tend to forget that. See the following code when you will encounter  ConcurrentModificationException.


Example Code

package testCodes;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorDemo {

    public static void main(String[] args) {

        List<String> nameList = new ArrayList<String>();
        nameList.add("John");
        nameList.add("Sam");
        nameList.add("kenny");

        nameList.add("Jessica");

        Iterator<String> namesIterator = nameList.iterator();
        System.out.println("Printing names");
        while (namesIterator.hasNext()) {
            String name = namesIterator.next();
            if (name.equals("Sam")) {
                nameList.remove(name);
            }
            System.out.println(name);
        }
    }
}

 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 - 

while (namesIterator.hasNext()) {
            String name = namesIterator.next();
            if (name.equals("Sam")) {
                namesIterator.remove();
            }
            System.out.println(name);
     }


Code will correctly compile and run. It's a very simple point but programmers tend to forget it some time.

So basically you should not modify the collection when it is being iterated upon. Another simple example that would throw this exception is

        Map<String, Object> myMap = new HashMap<String, Object>();
        myMap.put("Aniket", 1);
        myMap.put("Abhijit", 2);
        for(String key: myMap.keySet()) {
            myMap.remove(key);
        }


Solution as I mentioned above is to use remove() method of the iterator.Another option could be use concurrent collections. See following example -

        Map<String, Object> myMap = new ConcurrentHashMap<String, Object>();
        myMap.put("Aniket", 1);
        myMap.put("Abhijit", 2);
        for(String key: myMap.keySet()) {
            myMap.remove(key);
        }


What internally happens is as soon as data is updated in a collection the corresponding iterator is updated too which generally does not happen in normal collections.


Related Links


Understanding Iterators in Java

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 -

public interface Collection<E> extends Iterable<E> 

{

 int size();

 boolean isEmpty();

 boolean contains(Object o);

 Iterator<E> iterator();

 Object[] toArray();

 <T> T[] toArray(T[] a);

 boolean add(E e);

 boolean remove(Object o);

 boolean containsAll(Collection<?> c);

 boolean addAll(Collection<? extends E> c);

 boolean removeAll(Collection<?> c);

 boolean retainAll(Collection<?> c);

 void clear();

 boolean equals(Object o);

 int hashCode(); 
} 

and if you go and see what there in Iterable Interface you will find -

public interface Iterable<T> 
{
    Iterator<T> iterator();
}


Iterator is again an interface whose source code is as follows -

public interface Iterator<E> 
{
    boolean hasNext();
    E next();
    void remove();
}


Note :  All these are just Interfaces(abstract functions). Their concrete implementation will be in the first concrete subclass.

Points to Note -
  • We can iterate only in one direction.
  • Iteration can be done only once. This means once we reach end of a series we must get a new iterator to iterate. 

Lets take an example to demonstrate how Iterator works -

package testCodes;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorDemo {

    public static void main(String[] args) {
       
        List<String> nameList = new ArrayList<String>();
        nameList.add("John");
        nameList.add("Sam");
        nameList.add("kenny");
        nameList.add("Jessica");
       
        Iterator<String> namesIterator = nameList.iterator();
        System.out.println("Printing names");
        while(namesIterator.hasNext())
        {
            System.out.println(namesIterator.next());
        }
    }

}




 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.

Understanding Generics in Java

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.
  • Elimination of need to cast :

    The following code snippet without generics requires casting - 

    List list = new ArrayList();
    list.add("hello");
    String s = (String) list.get(0);
    
    
    When re-written to use generics, the code does not require casting - 

    List<String> list = new ArrayList<String>();
    list.add("hello");
    String s = list.get(0);   // no cast
    
    
  • Enabling programmers to implement generic algorithms :

    By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.
 Note :  Generics is not supported by primitive Data types. So you cannot do something like List<int> myList  = new ArrayList<int>();. You will have to do List<Integer> myList  = new ArrayList<Integer>();


Creating Generic Classes

 So far we saw use of generics on existing classes that JDK provides like List. Now lets write generic class of our own.


 I am going to create my own generic data structure called MyDataStructure. Code is as follows - 

public class MyDataStructure<T> {
    
    T data;

    public T getData() {
        return data;
    }

    public void putData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "MyDataStructure [data=" + data + "]";
    }
}

Notice that T. It's called type place holder - the type name T within angle brackets “<” and “>”. We use the same in all places in subsequent code. Now lets test this class.


public class TestGenerics {

    

    public static void main(String args[]) {

        MyDataStructure<String> myStringDataStructure = new MyDataStructure<String>();

        myStringDataStructure.putData("OpenSourceForGeeks");

        System.out.println(myStringDataStructure);

        MyDataStructure<Integer> myIntegerDataStructure = new MyDataStructure<Integer>();

        myIntegerDataStructure.putData(21);

        System.out.println(myIntegerDataStructure);

    }



}


and the output is : 
MyDataStructure [data=OpenSourceForGeeks]
MyDataStructure [data=21]

Diamond Syntax

MyDataStructure<String> myStringDataStructure = new MyDataStructure<String>();

Noticed how we have to provide same type parameters in both the declaration type
(MyDataStructure<String>) and the new object creation expression (new MyDataStructure<String>())

To simplify this diamond syntax is introduced in Java 7. In this type parameter in new Object creation expression can be omitted. Compiler infers the type from the declaration part.


So you can simply say
MyDataStructure<String> myStringDataStructure = new MyDataStructure<>();


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 -

public static void main(String []args) {
    List<Integer> integerList = new LinkedList<Integer>();
    List<Double> doubleList = new LinkedList<Double>();
    System.out.println("integerList class: " + integerList.getClass());
    System.out.println("doubleList class:" + doubleList.getClass());
}

Output : 

integerList class: class java.util.LinkedList
doubleList class:class java.util.LinkedList

Reason : 

At runtime there are no generics. It's plain concrete classes that exist. To sum this up due to type erasure after compilation both types are treated as same LinkedList type.

Important points

  • It’s possible to define or declare generic methods in an interface or a class even if the class or
    the interface itself is not generic.
  • You cannot instantiate a generic type using new operator. Eg you cannot do -

    T data = new T(); or
    T[] data = new T[10];


    Also you cannot create arrays of generic classes.

    List<Integer>[] array = new List<Integer>[10]; // does not compile

    Of course you can do -

    List[] array = new List[10]; // compiles

    but not with generics

    For reference see ArrayList code. There we have

    public class ArrayList<E> extends.......
    and

    data structure in it is

    private transient Object[] elementData; // note no generics here

    Then add method is like

    public boolean add(E e) {
        ensureCapacity(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
  • Also note Generics does not support covariance or subtyping. Meaning you cannot do something like -

    List<Number> numbers = new ArrayList<Integer>(); // will not compile

Related Links 



Collections Example(ArrayList)

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.

Code

package testCodes;

import java.util.ArrayList;
import java.util.List;

public class ListDemo {

    public static void main(String[] args) {

        List<String> nameList = new ArrayList<String>();
        nameList.add("John");
        nameList.add("Sam");
        System.out.println(nameList);
        nameList.add(0, "kenny");
        System.out.println("Size of list is " + nameList.size());
        System.out.println(nameList);
        nameList.remove("Sam");
        System.out.println(nameList);
        nameList.remove(0);
        System.out.println(nameList);
        System.out.println("Size of list is " + nameList.size());
    }
}

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.
t> UA-39527780-1 back to top