May 31, 2015

Method and Variable shadowing in Java

Method Shadowing

In java only instance method of parent class can be overridden, not static methods. Below example shows method shadowing in java.

class Parent {
 private static String hideMe = "HIDDEN-GEM-PARENT";

 public static void show() {
  System.out.println("show():HIDDEN - GEM is " + hideMe);

 public void display() {
  System.out.println("display():HIDDEN - GEM is " + hideMe);

class Child extends Parent {
 private static String hideMe = "HIDDEN-GEM-CHILD";

 // @Override - Not allowed, only instance method can be overridden
 public static void show() {
  System.out.println("show():HIDDEN - GEM is " + hideMe);

 public void display() {
  System.out.println("display():HIDDEN - GEM is " + hideMe);

public class ShadowingMethods {

  * @param args
 public static void main(String[] args) {
  Parent child = new Child();; // calls Parent class static methods, not Overridden
  child.display(); // calls Child class methods, since Overridden

Sample output :-
display():HIDDEN - GEM is HIDDEN-GEM-CHILD - calls parent class methods, since it is static method. In java static method is not overridden it is shadowed by Child class (If we @override above static method created, compiler reports error).

Variable Shadowing:-

package javacore;

public class ShadowVariable {

 private String strVar = "OuterMostString";

 class FirstLevel {

  private String strVar = "FirstLevelString";

  class SecondLevel {
   private String strVar = "SecondLevelString";

   void displaySecondLevel(String strVar) {
    System.out.println("strVar  = " + strVar);
    System.out.println("this.strVar = " + this.strVar);
    System.out.println("ShadowVariable.this.x = "
      + FirstLevel.this.strVar);
    System.out.println("ShadowVariable.this.x = "
      + ShadowVariable.this.strVar);

 public static void main(String[] args) {
  ShadowVariable st = new ShadowVariable(); 
  ShadowVariable.FirstLevel l1 = FirstLevel();
  ShadowVariable.FirstLevel.SecondLevel l2 = SecondLevel();

Sample Output: 

strVar  = MethodArgumentVariable
this.strVar = SecondLevelString
ShadowVariable.this.x = FirstLevelString
ShadowVariable.this.x = OuterMostString

If a declaration of a type (such as a member variable or a parameter name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, then the declaration shadows the declaration of the enclosing scope. You cannot refer to a shadowed declaration by its name alone. (Source)

In order to access corresponding member variable of class we have to use <classname>.this as scope resolution, based on context variable is referred. 

May 30, 2015

Textual description of firstImageUrl

Inheritance in python

In object-oriented programming, a modular and hierarchical organization of classes and software module is achieved using  inheritance. 
The classes at top in hierarchy is typically described as the base class, parent class, or superclass, while class which extend base class is known as the subclass or child class. The relation between these two class base class ,derived classes or subclass is called "IS-A". Here is the class hierarchy of exception types in python.
Hierarchy of exception types
BasicException class is super class and all classes in below hierarchy are derived classes. BaseException is parent class for child class/subclass keyboardInterrupt.

What inheritance brings in Object oriented programming ? - Re-usability of code. i.e : base class defines common functionality for derived class and allow derived class to focus on specific functionality related to that class.
In order to get holistic picture of inheritance, lets take an example of Numeric Progressions classes. Here Arithmetic progression and Geometric progressions are derived classes and Progression is base class. (Example reference : Data Structure and Algorithm by Goodrich)
The class hierarchy will looks like this :
Hierarchy of progression classes
Lets write definition of these classes. Open python IDLE, create a file and copy following code lines in it:
class Progression(object): #Inheriting object class
 def __init__(self, start=0):
   self._current = start

 def _advance(self):
   self._current += 1

 def next(self):# Python 3: def __next__(self)
   #our convention to end a progression
   if self._current is None: 
     raise StopIteration()
   # record current value to return
     answer = self._current 
     return answer 
 def __iter__(self):
   return self

 def print_progression(self, n):
   print( ' '.join(str(next(self))
                                        for j in range(n)))
Now we will be creating Arithmetic and Geometric implementation inheriting Progression:
from Progression import Progression
class ArithmeticProgression(Progression): # inherit from Progression
 '''Iterator producing an arithmetic progression.'''
 def __init__(self, increment=1, start=0):
  Progression.__init__(self,start) # initialize base class
  self._increment = increment

 def _advance(self): # override inherited version
  self._current += self._increment

class GeometricProgression(Progression): # inherit from Progression
 '''Iterator producing an geometric progression.'''
 def __init__(self, base=2, start=1):
  self._base = base

 def _advance(self): # override inherited version
  self._current *= self._base
In above classes defined . Progression inherit from object class, mother of all in python. Progression class defines constructor to declare current element and various method like incrementing sequence ,
getting next element and printing the sequence. ArithmaticProgression and GeometricProgression are inheriting Progression class and override advance method as per logic of ArithmaticProgression (incremented by constant value) and GeometricProgression (multiplied by constant value).
Sample output: ------------------------------------
>>> p = Progression(4)        #start is initialized with 4
>>> p.print_progression(4)  #for loop will iterate four times and execute next(self) of Progression
4 5 6 7

>>> a = ArithmeticProgression(increment=2, start=3)   #Overwrite default value
>>> a.print_progression(4)  #Overridden _advance() of  ArithmeticProgression executed  
3  5 7 9

>>> g =GeometricProgression( base=3, start=12)  #Overwrite default value
>>> g.print_progression(3) # Overridden _advance() of  GeometricProgression executed and each
                                             # time values are multiplied by 3 using self._current *= self._base 

12 36 108
  1.  class Progression(object) vs  class Progression/class Progression() : class Progression(object) is new style of writing class definition while class Progression: is old way of doing this.In order to unify type and class from python 2.2 new style of class definition was introduced. For detail refer this post. 
  2. super(GeometricProgression,self).__init__(start) / How super() got changed in python 3 ?In python 2.x, for initializing member variables of parent class from derived class we need to pass parameters values via calling super(<current_class>, self).__init__(<arguments>). However, form python 3,  <current_class>, self become optional. Refer this for detail.
    Another way of accessing init of parent class by explicitly using class name. i.e : We have used Progression.__init__(self , start) , Progression is base class name.
In order to make backward compatible both old class definition/classical definition of class are still valid in python 3 and so as use of super with class name and self as argument.

Previous: Method overloading and Operator overloading   

May 17, 2015

Print Even and Odd number using two different thread

One of the basic question asked in Java interview to check basic understanding of inter thread communication and related threading construct.
In this post we are using synchronisation block and wait()/notify() to print even/odd numbers by two different threads. Another approach to print odd/even number using interruption mechanism.

Below are the sample code which displays even and odd numbers with a time delay of 1 second.
package com.devinline.thread;

public class PrintOddAndEven {

 static volatile int counter = 1;
 static Object object = new Object();// Monitor

 public static void main(String[] args) {
  Thread tEven = new Thread(new EvenProducer(), "Even thread");
  Thread tOdd = new Thread(new OddProducer(), "Odd thread");

 static class EvenProducer implements Runnable {
  public void run() {
   synchronized (object) {
    while (true) {
     if (counter % 2 == 0) {
        + " produced " + counter);
      try {
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
     } else {
      try {
      } catch (InterruptedException e) {

 static class OddProducer implements Runnable {
  public void run() {
   synchronized (object) {
    while (true) {
     if (counter % 2 != 0) {
        + " produced " + counter);
     } else {
      try {
      } catch (InterruptedException e) {
======Sample output=======
Odd thread produced 1
Even thread produced 2
Odd thread produced 3
Even thread produced 4
Odd thread produced 5
Even thread produced 6
Odd thread produced 7
Even thread produced 8
Read also : How to solve above problem using Thread interrupt() - display Even/odd by interrupting thread which is sleeping for a infinite time. 

May 5, 2015

Python questions and answers - Part 1

1. What is floor division in python ?  OR What is difference between operator / and // ?
Answer: Operator // is called floor division in python.Integer division was a concern for  python developer prior to python 2.2. Python 2.2 came up with new operator to support
floor division and regardless of input type.  i.e :  // always gives floor result.
Note :-
In Python 3, / is float division
In Python 2, / is integer division (assuming int inputs)
In both 2 and 3, // is integer division
In Python 2.x, make sure to have at least one operand of your division in float. \
Consider following example for better understanding, (I am using python 2.7)
>>> 20/14  #Integer outcome
>>> float(20)/12  # floating outcome since one of the operand is float

2. What will be outcome of following snippet ? / What are First-Class Objects in python ?
>>>def disply_msg():
             print 'hello world from function'
>>>x = disply_msg #Function assigned to an identifier
Answer: It will display "hello world from function" .
The fundamental behind is that, functions are first-class types in Python. First-class objects are instances of a type that can be assigned to an identifier, passed as a parameter, or returned by
a function.So, x = function executes, x becomes alias of function disply_msg and when x() executes definition of disply_msg executes and display hello world from function.
Notes :
  1. function can also be passed as argument of function.For example, inbuilt function min and max passed abs function to calculate minimum absolute value.
    >>>min(12, -34, key=abs)  # abs(-34) > abs(12), so display 12
  2. In python, class are also first class object. 
3. Swap values of two variable in python without using temporary variable.Consider a =8, b= 9
and after swapping be a = 9, b= 8.
(Hint: Use Simultaneous Assignments
Answer: a,b = b,a    Done!!
What is Simultaneous Assignments in python ?
The combination of automatic packing and unpacking forms a technique known as simultaneous assignment.We explicitly assign a series of values to a series of identifiers, all of the expressions are evaluated on the right-hand side before assignment.
>>> x, y, z = 6, 2, 5   # x = 6, y = 2, z = 5
>>> x
Note: Data packing: Series of comma-separated will be treated as a single tuple, even
if no enclosing parentheses are provided.
data = 10,1,23,45   # it is equivalent to (10,1,23,45), python provide missing ( ).
It can be used while returning multiple values from function/method.  - return x,y
Data unpacking : Python can automatically unpack a sequence, allowing one to assign a series of individual identifiers to the elements of sequence.
Example :   a, b, c, d = range(7, 11)   # a=7, b=8, c=9, and d=10
It is used in built-in function, divmod(a, b), returns the pair of values (a // b, a % b) as quotient, remainder. quotient, remainder = divmod(a, b)
It can be used while iterating over sequence
for x, y in [ (7, 2), (5, 8), (6, 4) ]:   # x= 2, y = 7 in first iteration
for k, v in mapping.items():            #k - key of first dict entry and v = value

4.What is significance of  if name == __main__: in python module creation ?
Answer: In python module (a file with .py extension) is collection of functions and classes.There are various in built module for specific use included in python. Example : math for Mathematical operation , os for Operating system related thing, re for regular expression , sys for interaction with the Python interpreter, collection, array, etc.
We can create our custom module and it can be imported in python program or another module or executed as standalone program too. When a module is imported for the first time, the main block in that module is run. 
Every module has __name__  and value of __name__ is decided whether module has been used as standalone program or imported in a module.
  • If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". 
  • If this file is being imported from another module, __name__ will be set to the module's name.
"if name == __main__:"  is a conditional statement used to distinguish whether given module is used as standalone program or as module. Consider following sample code and save it in a file named
if __name__ == '__main__':
     print 'This program is being run by itself'
     print 'I am being imported from another module'
Open this file in IDLE interpreter and execute it as standalone program it display "This program is being run by itself" because __name__ is initialized with value __main__ and that makes if condition true.
Now import it as module and press enter , it displays "I am being imported from another module"
>>> import _module
I am being imported from another module

Refer this for another example for better understanding.This approach used to embed unit tests within the module and execute as standalone program to test that module.

5.What is Deep and shallow copy in python ?
Answer: In python when an identifier is assigned a data structure, that identifier becomes an alias of that data structure. Either of identifier old or new referring to list can modify that data structure.
Suppose we want to create separate list for both identifier, python comes with concept of shallow copy and create a separate list for each.
list_original = ["Apple","mango","Water melon"]
copy_original_list =  list(list_original ) #list constructor used to create separate list DS. 55555555
>>> list_original = ["Apple","mango","Water melon"]
>>> copy_original_list = list_original [:]
Since python’s lists are referential and each element referenced by list can be a object(a sub-list), so when element of an list is an object then also we have not achieved clear separation of concern.
Here python come up with concept of deep copy, where copy method is executed recursively and all object is created separately for both references .
from copy import deepcopy
list_original  = ["Apple","mango","Water melon",["pineapple","papaya"]]
copy_original_list = deepcopy(list_original  )
copy_original_list[2][1] = "Jack fruit"
list_original  [0] = "No Fruit";

print copy_original_list  #['Apple', 'mango', 'Water melon', ['pineapple', 'jack fruit']]
print list_original  # ['No Fruit', 'mango', 'Water melon', ['pineapple', 'papaya']
For detail discussion about shallow and deep copy with example refer this.

Read about :  Python - object oriented paradigm
                      Python data structure