Power of grep: search set of strings from an input file

grep is a common command which is used for search patterns in a file. I use it commonly for searching access log files, debug log files, looking for a pattern in user behavior.

If a user wants to search for a word or phrase in a file following is the command

grep "hello world" input.txt

this will list the lines which have the “hello world” in it.

grep works with regex expressions and support wild characters too.

grep "hello*" input.txt

will list all the lines having hello* pattern.

Now suppose there is a file with the list of user ids and the task is to search all the users who have visited the website from debug.log.

grep  -F -f userids.txt debug.log
The above command tells grep to look for strings as patterns from the input file

-F, –fixed-strings

  Interpret pattern as a set of fixed strings (i.e. force grep to behave as fgrep).

-f file, –file=file

 Read one or more newline separated patterns from a file.  Empty pattern lines match every input line.  Newlines are not considered part of a pattern.  If a file is empty, nothing is matched.


Java Interview Questions

Some of the most common interview questions I generally ask Java programmers. For more comprehensive list, check Java Interview Questions

Q) What is polymorphism?

Ans) The ability to define a function in multiple forms is called Polymorphism. In java,c++ there are two types of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding). Method overriding Overriding occurs when a child class implements the method with the same signature as a method in a parent class. When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time.

Overloading occurs when several methods have same names but different number or type of parameters.

  • Overloading is determined at the compile time.
  • Different method signature and different number or type of parameters.
  • Same method signature but the different number of parameters.
  • Same method signature and same number of parameters but of different type

Example of Overloading

int add(int a,int b)
   float add(float a,int b)
   float add(int a ,float b)
   void add(float a)
   int add(int a)
   void add(int a) //error conflict with the  method int add(int a)
class BookDetails{
  String title;
  setBook(String title){}
class ScienceBook extends BookDetails{
  setBook(String title){} //overriding
  setBook(String title, String publisher,float price){} //overloading

Q) What is the difference between final, finally and finalize() in Java?

Ans) final – A final variable acts as a constant, a final class is immutable and a final method cannot be overridden while doing inheritance.

finally – handles exception. The finally block is optional and provides a mechanism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc.

finalize() – method belongs to Object class. The method that is invoked while doing the garbage collection of the object. It could be used for allowing it to clean up its state. Good use cases will be to free connection pools, deallocate resources etc.

Q)What is the difference between HashMap and HashTable?

Ans) Both collections implement Map. Both collections store value as key-value pairs. The key differences between the two are

  1. Hashmap is not synchronized in nature but hashtable is.
  2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.
    Fail-safe -if the Hashtable is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException?
  3. HashMap permits null values and only one null key, while Hashtable doesn’t allow key or value as null.

Q) What is the difference between abstract class and interface?


  • A class is called abstract when it contains at least one abstract method. It can also contain n numbers of concrete method. An interface can contain only abstract( non implemented) methods.
  • The abstract class can have public, private, protect or default variables and also constants. In interface, the variable is by default public final. In nutshell, the interface doesn’t have any variables it only has constants.
  • A class can extend only one abstract class but a class can implement multiple interfaces.
  • If an interface is implemented its compulsory to implement all of its methods but if an abstract class is extended it’s not compulsory to implement all methods.
  • The issue with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement the new method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.

Q) What is the difference between equals() and == ?

Ans) == operator is used to compare the references of the objects.
public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. But since the method can be overridden like for String class. equals() method can be used to compare the values of two objects.

String str1 = "MyName"; 
String str2 = "MyName";
String str3 = new String(str2);

if (str1 == str2) {
  System.out.println("Objects are equal")
  System.out.println("Objects are not equal")
if(str1.equals(str2)) {
  System.out.println("Objects are equal")
} else {
  System.out.println("Objects are not equal")

Objects are not equal
Objects are equal
String str2 = "MyName";
String str3 = str2;
if (str2 == str3) {
System.out.println("Objects are equal")
System.out.println("Objects are not equal")
if (str3.equals(str2)) {
  System.out.println("Objects are equal")
} else {
  System.out.println("Objects are not equal")

Objects are equal
Objects are equal

Q) What is the difference between an ArrayList and a Vector?


  • Synchronization – ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block, thus making Vector class thread-safe.
  • Data growth – Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of capacity. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
  • Performance the Since vector is thread-safe, the performance is slower than ArrayList.

Q) Which all classes implement Set interface ?

Ans) A Set is a collection that contains no duplicate elements. More formally, a set contains no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet, SortedSet and TreeSet are the commonly used class which implements Set interface.

  • SortedSet – It is an interface which extends Set. A the name suggest, the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
  • TreeSet – It is the implementation of SortedSet interface. This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized. The class uses Red-Black tree data structure.
  • HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

Q) Describe the exception hierarchy in Java?

Ans) The hierarchy is as follows:

java exception hierarchy

Throwable is a parent class of all Exception classes. There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of exceptions extends Exception class.

Difference between final, finally and finalize in Java ?

final – final keyword can be used with a class, variable or a method.

  • A variable declared as final acts as constant, which means one a variable is declared and assigned , the value cannot be changed. An object can also be final, which means that the once the object is created it cannot be assigned a different object, although the properties or fields of the object can be changed.
  • A final class is immutable, which means that no other class can extend from it. E.g String, Integer.
  • A final method in a class cannot be overridden in the child class.

The underlying behavior of using final keyword is to act as constant.

public class Test {
    private static final String PREFIX = "test." 
    private final MyClass obj = new Myclass();

    publc Test() {
      obj = new MyClass() ;// throws error 
  public class Test {
    private static final String PREFIX = "test." 
    private final MyClass obj;

    publc Test() {
      obj = new MyClass() ;// this works

finally – finally keyword is used with try-catch block for handling exception. The finally block is optional in try-catch block. The finally code block is always executed after try or catch block is completed. The general use case for finally block is close the resources used in try block. For e.g. Closing a FileStream, I/O stream objects, Database connections, HTTP connections are generally closed in a finally block.

public class Test {
  public static void main(String[] args) {
    BufferedReader br = null;
    try {
      String sCurrentLine = "";
      br = new BufferedReader(new FileReader("C:\\testing.txt"));
      while ((sCurrentLine = br.readLine()) != null) {
    } catch (IOException e) {
    } finally { // close the resource. 
      try {
        if (br != null)br.close();
      } catch (IOException ex) {

finalize() – This is the method of Object class.It is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

How to code URL shortener from scratch?

I am going to explain one of the common approaches used to create URL shortner.

  1. Think of an alphabet we want to use. In your case that’s [a-zA-Z0-9]. It contains 62 letters.
  2. Take an auto-generated, unique numerical key (the auto-incremented id of a MySQL table for example).

    For this example I will use 12510 (125 with a base of 10).

  3. Now you have to convert 12510 to X62 (base 62).

    12510 = 2×621 + 1×620 = [2,1]

    Now map the indices 2 and 1 to your alphabet. This is how your mapping (with an array for example) could look like:

    0  → a
    1  → b
    25 → z
    52 → 0
    61 → 9

    With 2 → c and 1 → b you will receive cb62 as the shortened URL.


How to resolve a shortened URL to the initial ID

The reverse is even easier. You just do a reverse lookup in your alphabet.

  1. e9a62 will be resolved to “4th, 61st, and 0th letter in alphabet”.

    e9a62 = [4,61,0] = 4×622 + 61×621 + 0×620 = 1915810

  2. Now find your database-record with WHERE id = 19158 and do the redirect.

Use of hashcode() and equals()

Tech Read..

Use of hashCode() and equals(). 

Object class provides two methods hashcode() and equals() to represent the identity of an object. It is a common convention that if one method is overridden then other should also be implemented.

Before explaining why, let see what the contract these two methods hold. As per the Java API documentation:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashcode() method must consistently return the same integer, provided no information used in equals() comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
  • It is NOT required that if two objects are…

View original post 958 more words

Quick Tip: How to Work with GitHub and Multiple Accounts

Sometimes you may need to have multiple github accounts (one for office, one for work , one for girl friend, whatever) .

Lets say you have ssh keys already setup and github is set for one account. Now for new account:

  • Create a new ssh key

ssh-keygen -t rsa -C "your-email-address"

     Careful while name the file , dont overwrite the existing one .I named it as ~/.ssh/id_rsa_xxx

  • Add the new key to github account

     This is simple enough. Copy the id_rsa_xxx.pub in github > Settings > SSH Keys

  • Create a new config file in  vi ~.ssh/config

        Add following :

#Default GitHub
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa
Host github-COMPANY
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_xxxx
You are done . Try it out ..
Vola !! Happy coding !!