Friday, 10 January 2014

What Language Should You Learn Next?

          Earlier it was pretty easy to decide what language to learn next. For example, during my graduation days, the choice was very simple - learn first C, C++ and then we used to go for either JAVA or C#.NET...thats it!! 

But then after 2010, the platforms were trying to relocate...bikes superseded by mopeds,  laptops by palmtops and ancient nokia kind of cellphones by qwerty keypads and again by screentouch. 

This screentouch laid tremendous change in the era of computing. The phase changed from 0 to 1 directly. On the other hand, the great computer scientist were breaking their head to centralize the data, resources and all available computing peripherals in a  consolidated way. This made the rise of the term CLOUD COMPUTING...here they introduced the terms "pay per use" and "on demand".

The concepts like IAAS, PAAS, SAAS made the techniques of virtualization the real powerful cloud computing. Now the entire industry was trying to be open source oriented and increase their revenues...windows 7 was out-chosen and Ubuntu was a priority of technical users.

And then came ANDROID - which actually made NOKIA out of market (it was nokia's biggest mistake not to support android since they had complete faith in simbion). Because of the rise of Android, programmers from the entire world started freelancing development and this is actually contributing a lot. The depth of the computer applications, as you can observe, is never before deep & getting more deeper. 

Because of this scenario, many small scale industries survived and could fetched up more number of trusted customers. At this point, thinking ways differed, logics generated, efficacy was given top priority, requirements changes a lot and it made the great comuter scientist again to think and develop new consoles, compilers and languages.

Languages like JAVA, Python, Scala, Perl, Ruby, Groovy, APL, Clojure, Lisp and Brainfuck  was adopted for different purposes. Never before in the history of computer science have we had so many choices before us. 

A friend, who is involved in big data, analytics and cloud computing, is learning and using Scala for his work. Scala is a language that targets Java platform; it merges both object-oriented and functional feature. {Now a days one more thought process is picking up - "functional programming", the colors of this are really blooming than object oriented programming. Object Oriented programming is a  old one now.} Because of Scala's fuctional capabilities, it is good for writing concurrent codes and for analysing large quantities of data. But there is a risk of getting trapped in unreachable code and one can end up with while writing in Scala.

Grovvy - a superset of Java. Another friend works on developing software for the financial domains and is currently learning Grovvy which has productivity of scripting languages in Java-like syntax. If you are a java programmer and want to be more productive go for this language. 

Another old friend of mine had an unusual transition from fixing bugs in C/C++ compiler to programming the web using javascript! She is exploring a growing list of languages like Dart, TypeScript that are trying to replace JavaScript. However she finds CoffeeScript to be a sweet spot since it compiles to javascriptand she can seemlessly use her existing javascript code and third-party libraries in it. 

Suggestions for learning new languages based on real world experience include : 
  • Cojure (with a warning not to give up learning because of its Lisp syntax)
  • Ruby
  • Python (for a wide range of pogramming tasks - from automation to web programming)
  • Scala (for concurrent programming).
Thinking about what programming language one should learn next, I realized that this is a deeply personal matter. Just like preferences for different brands differ from person-to-person, choosing programming language depends on an individual's personal likes and dislikes, preferences and the kind of work one does. Hence before deciding on which language to learn next, seriously consider the following factors : 
  1. How much time  can you afford to spend on learning a new language?
  2. Does the new language help you solve your problems more effectively?
  3. Does the new language match your way of thinking?
  4. Does the new language help you think differently?
  5. Does the new language excite you?
We are also at a point of transition - the erstwhile mainstream languages like C, C++, JAVA were designed for the old era. In this decade in which computers are shrinking to the size of a button, the internet is becoming ubiquitous, computing is becoming paid and pervasive service, and data is growing to the order of exabytes, the dominants languages will be completely different. More than anything else, learning a new language is fun! So what are you waiting for - go ahead, carefully choose, and then enjoy learning a new programming language! 
[thanks to Ganesh S.]

Tuesday, 7 January 2014

Liskov's Principle of Substitution (LSP) and Java Programming

Who is Liskov?

Barbara Liskov (born Barbara Jane Huberman on November 7, 1939 in California) is a computer scientist. She is currently the Ford Professor of Engineering in the MIT School of Engineering's electrical engineering and computer science department and an institute professor at the Massachusetts Institute of Technology.


Statement - 

"In a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may be substituted for objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)."

More formally, the Liskov substitution principle (LSP) is a particular definition of a subtyping relation, called (strong) behavioral subtyping, that was initially introduced by Barbara Liskov in a 1987 conference keynote address entitled Data abstraction and hierarchy.
[from wiki]. Now let us illustrate this - 

I have following structure in the program -
class C1
{
    int a;
    int b;
    void m1(){
       System.out.println("m1 of C1");
    }
    void m2(){
       System.out.println("m2 of C1");
    }
}
class C2 extends C1
{
    int c;
    int d;
    void m3(){
       System.out.println("m3 of C2");
    }
    void m4(){
       System.out.println("m4 of C2");
    }
}
Thats a very common and simple form of inheritance in java.
In the main class I create the objects for these classes
class Main{
  public static void main(String [] args){
    
     C1 obj1 = new C1();
     //
     C2 obj2 = new C2();
  }

C1 --> Base Class.
C2 --> Derived Class.

Inheritance means  : DRY - "Don't Repeat Yourself". 

Rather I established a relationship between C, C1 and C2 by the keyword - "extends".
Notice carefully that there is a great difference between copying & establishing  a relationship.
So basically I prohibit copying when I say "I am inheriting"..which eventually means "I am reusing my/someone else's code". 

Here it means that object of C2 has 8 things but this perception is logical; not physical. Because the members of C1 i.e a, b, m1() and m2() are fetched up by C2 logically and not physically..that means they are available for C2 at runtime. Actually C2 has just 4 things that are written in its own class body. In java, this phenomenon is termed as "extension/mixing". 

So - physically 4 & logically 8 for C2. 
Proper and clear visualization matters a lot in programming. A tiny imperfect visualization of a simple set of code, say a data structure, changes the entire performance of your program . 

In java we have class-based inheritance i.e. here a child object has a copy of  parent's variables.
Now from here onwards in this blog  - the LSP plays.
Lets reconsider the above code with some modification :

class Main{
   public static void main(String [] args){
        C1 obj1 = new C1();
        C2 obj2 = new C2();
        Client1(obj1); //1st call
        Client2(obj2); //2nd call
        Client1(obj2); //3rd call
   }
   static void Client1(C1 h){
        h.m1();
        h.m2();
   }
   static void Client2(C2 q){
        q.m3();
        q.m4();
   }
}


No need to explain about 1st and 2nd call. 
But observe the 3rd  call carefully. Here type is "Parent" and the handle i.e object that is being passed is of type "Child". So the picture is very clear - A child object is behaving as a parent now.

But is it possible? The answer is - YES. 
In fact, we all know and have been using this concept since long. But just to know, this is termed as LISKOV's PRICIPLE OF SUBSTITUTION (LSP). 


"A child object can act as a parent object  & hence, a child object can be passed if parent object is not present. But a parent object can not act as child. So this substitution is asymmetrical.(I can't say vice versa here)". 

To make it clear and simple - A child can act as a substitute to its parent but the other way its not possible. While programming, some people also prefer to refer it as "Liskov's situation".
  • Some key result that I am not explaining here, but you can use and follow are - 
  1. When a child object is playing child's role, method hiding is effective.
  2. When a child object is playing its parent's role, method hiding is ineffective.
  • In programming languages, if you want that a child object should act as a substitute to parent & still it should not loose its own identity(of being child), you must have parents permission.
  • Hence we make such methods "virtual" in C++ and C#. And now this becomes a complete hiding. This complete hiding is nothing but "OVERRIDING"
  • 99% people in the field of programming have wrong concept here.
  • In java, by nature it is overriding.
There are some things, we can't express in C++ & C# but can be in java. In the same way there are some things that are not explainable in java but in C#. In java, by default it is over-riding.
  • NO HIDING IN JAVA.
Some useful links - 
3. c2.com

Thanks a lot. Happy programming.

Tuesday, 7 May 2013

JAVA on Loop (Iterations)

(I) SumAndAverage (Loop): 

Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to an upperbound (e.g., 100). Also compute and display the average. The output shall look like :  
The sum is 5050
The average is 50.5


Hints:
public class SumAndAverage { // saved as "SumAndAverage.java"
public static void main (String[] args) {
int sum = 0; // store the accumulated sum, init to 0
double average; // average in double
int lowerbound = 1; // the lower bound to sum
int upperbound = 100; // the upper bound to sum
for (int number = lowerbound; number <= upperbound; ++number) { // for loop
sum += number; // same as "sum = sum + number"
}
// Compute average in double. Beware that int/int produces int.
......
// Print sum and average.
......
}
}


Dowanload Sample Code - SumAndAverage.java

Try :
  1. Modify the program to use a "while-do" loop instead of "for" loop. int number = lowerbound; int sum = 0; while (number <= upperbound) { sum += number; ++number; }
  2. Modify the program to use a "do-while" loop. int number = lowerbound; int sum = 0; do { sum += number; ++number; } while (number <= upperbound);
  3. What is the difference between "for" and "while-do" loops? What is the difference between "while-do" and "do-while" loops?
  4. Modify the program to sum from 111 to 8899, and compute the average. Introduce an int variable called count to count the numbers in the specified range. int count = 0; // count the number within the range, init to 0 for (...; ...; ...) { ...... ++count; }
  5. Modify the program to sum only the odd numbers from 1 to 100, and compute the average. (Hint: n is an odd number if n % 2 is not 0.)
  6. Modify the program to sum those numbers from 1 to 100 that is divisible by 7, and compute the average.
  7. Modify the program to find the "sum of the squares" of all the numbers from 1 to 100, i.e. 1*1 + 2*2 + 3*3 + ... + 100*100.
=======================================================================

(II) Product1ToN (Loop):

Write a program called Product1ToN to compute the product of integers 1 to 10 (i.e., 1×2×3×...×10). Try computing the product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product obtained and explain the results.

Hints: Declares an int variable called product (to accumulate the product) and initialize to 1.
 
Sample Code - Product1ToN.java

======================================================================

(III) HarmonicSum (Loop):

Write a program called HarmonicSum to compute the sum of a harmonic series, as shown below, where n=50000. The program shall compute the sum from left-to-right as well as from the right-to-left. Obtain the difference between these two sums and explain the difference. Which sum is more accurate?


Hint :
public class HarmonicSum { // saved as "HarmonicSum.java"
public static void main (String[] args) {
int maxDenominator = 50000;
double sumL2R = 0.0; // sum from left-to-right
double sumR2L = 0.0; // sum from right-to-left
// for-loop for summing from left-to-right
for (int denominator = 1; denominator <= maxDenominator; ++denominator) {
// Beware that int/int gives int.
}
// for-loop for summing from right-to-left
......
// Find the difference and display
......
}
}


Sample code - HarmonicSum.java
================================================================ 

(IV) ComputePI (Loop & Condition): 

Write a program called ComputePI to compute the value of π, using the following series expansion. You have to decide on the termination criterion used in the computation (such as the number of terms used or the magnitude of an additional term). Is this series suitable for computing π?



JDK maintains the value of π in a double constant called Math.PI. Compare the values obtained and the Math.PI, in percents of Math.PI
Hint: Add to sum if the denominator modulus 4 is 1, and subtract from sum if it is 3.


double sum = 0;
int maxDenom = 10000000;
for (int denom = 1; ..... ; denom = denom + 2) {
   if (denom % 4 == 1) {
      sum += ......;
   } else if (denom % 4 == 3) {
      sum -= ......;
   } else {
      System.out.println("The computer has gone crazy?!");
   }
}
 
Sample Code - ComputePI.java  
================================================================

(V)CozaLozaWoza (Loop & Condition)****:

Very Interesting. 
Write a program called CozaLozaWoza  which prints the numbers 1 to 110, 11 numbers per      line. The program shall print "Coza" in place of the numbers which are multiples of 3, "Loza" for multiples of 5, "Woza" for multiples of 7, "CozaLoza" for multiples of 3 and 5, and so on. 
The output shall look like:

1 2 Coza 4 Loza Coza Woza 8 Coza Loza 11 
Coza 13 Woza CozaLoza 16 17 Coza 19 Loza CozaWoza 22 
23 Coza Loza 26 Coza Woza 29 CozaLoza 31 32 Coza
...... 

Note - You have to print just 11 numbers per line.
Hint - 
public class CozaLozaWoza {   // saved as "CozaLozaWoza.java"
   public static void main(String[] args) {
      int lowerbound = 1;
      int upperbound = 110;
      for (int number = lowerbound; number <= upperbound; ++number) {
         // Print "Coza" if number is divisible by 3
         if (......) {   
            System.out.print("Coza");
         }
         // Print "Loza" if number is divisible by 5
         if (......) {
            System.out.print(.....);
         }
         // Print "Woza" if number is divisible by 7
         ......
         // Print the number if it is not divisible by 3, 5 and 7
         if (......) {
            ......
         }
         // Print a space
         ......
         // Print a newline if number is divisible by 11
         if (......) {
            System.out.println();
         }
      }
   }
} 
 
Try - Modify the program to use nested-if (if ... else if ... else if ... else) instead.
Sample Codes - CozaLozaWoza.java  
======================================================================

 (VI) Fibonacci (Loop):

Write a program called Fibonacci to display the first 20 Fibonacci numbers F(n), where F(n)=F(n–1)+F(n–2) and F(1)=F(2)=1. 
Also compute their average. The output shall look like: 
The first 20 Fibonacci numbers are:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 
The average is 885.5

Hints - 
public class Fibonacci {
   public static void main (String args[]) {
      int n = 3;          // the index n for F(n), starting from n=3
      int fn;             // F(n) to be computed
      int fnMinus1 = 1;   // F(n-1), init to F(2)
      int fnMinus2 = 1;   // F(n-2), init to F(1)
      int nMax = 20;      // maximum n, inclusive
      int sum = fnMinus1 + fnMinus2;
      double average;
      System.out.println("The first " + nMax + " Fibonacci numbers are:");
      ......
      while (n <= nMax) {
         // Compute F(n), print it and add to sum
         ......
         // Adjust the index n and shift the numbers
         ......
      }
      // Compute and display the average (=sum/nMax)
      ......
   }
}
 
Sample Code - Fibonacci.java
========================================================================

 (VI) Tribonacci (Loop): 

Tribonacci numbers are a sequence of numbers T(n) similar to Fibonacci numbers, except that a number is formed by adding the three previous numbers, i.e., T(n)=T(n-1)+T(n-2)+T(n-3), T(1)=T(2)=1, and T(3)=2. Write a program called Tribonacci to produce the first twenty Tribonacci numbers.
 Sample Code - Tribonacci.java
========================================================================

(VI) ExtractingDigits

In this section of looping, this is going to be our last program and what it is? 
Write a program to extract each digit from an int, in the reverse order. For example, if the int is 1542, the output shall be "2,4,5,1", with a comma separating the digits. 
Hints: Use n % 10 to extract a digit; and n = n / 10 to discard the last digit.

int n = ....;
while (n > 0) {
   int digit = n % 10;  // Extract the last digit
   ......
   .....
   n = n / 10;          // Drop last digit and repeat the loop
}

JAVA on Flow Controls (if-else/switch case)

( I ) CheckPassFail (if-else):

Write a program called CheckPassFail which prints "PASS" if the int variable "mark" is more than or equal to 50; or prints "FAIL" otherwise.

Hints : [Recommended IDE - Eclipse Ganymede 32 bit]
public class CheckPassFail { // saved as "CheckPassFail.java"
public static void main(String[] args) {
int mark = 49; // set the value of mark here!
System.out.println("The mark is " + mark);
if ( ...... ) {
System.out.println( ...... );
} else {
System.out.println( ...... );
}
}
}


Download the Code at -
https://docs.google.com/file/d/0B8MoFjuZZZwjUTNLVjd5Tm5OSVU/edit?usp=sharing
=========================================================================
 
( II )Exercise CheckOddEven (if-else): 
 
Write a program called CheckOddEven which prints "Odd Number" if the int variable “number” is odd, or “Even Number” otherwise.
Hints: n is an even number if (n % 2) is 0.

public class CheckOddEven { // saved as "CheckOddEven.java"
public static void main(String[] args) {
int number = 49; // set the value of number here!
System.out.println("The number is " + number);
if ( ...... ) {
System.out.println( ...... );
} else {
System.out.println( ...... );
}
}
}

Download the sample code at –
https://docs.google.com/file/d/0B8MoFjuZZZwjc2owbHNQWUMyLWs/edit?usp=sharing
======================================================================
 
( III )PrintNumberInWord (nested-if, switch-case):
 
Write a program called PrintNumberInWord which prints "ONE", "TWO",... , "NINE", "OTHER" if the int variable "number" is 1, 2,... , 9, or other, respectively. 
Use (a) a "nested-if" statement; (b) a "switch-case" statement.

Hints:
public class PrintNumberInWord
{ //saved as"PrintNumberInWord.java"
public static void main(String[] args)
{
int number = 5;
// Using nested-if
if (number == 1) {
System.out.println("ONE");
} else if (......) {
......
} else if (......) {
......
......
} else {
......
}
// Using switch-case
switch(number) {
case 1: System.out.println("ONE"); break;
case 2: ......
......
......
default: System.out.println("OTHER");
}
}


Download the Code here –
https://docs.google.com/file/d/0B8MoFjuZZZwjWEVqdldNVWpzcTA/edit?usp=sharing
=====================================================================
 
( IV )PrintDayInWord

Write a program called PrintDayInWord, which prints “Sunday”, “Monday”, ... “Saturday” if the int variable "day" is 0, 1, ..., 6, respectively. Otherwise, it shall print “Not a valid day”. This one is your practice problem. 
Sample Code to Download -  
https://docs.google.com/file/d/0B8MoFjuZZZwjS2p5aWlSbG5jaWs/edit?usp=sharing =======================================================================

Welcome to JAVA Beginners

Exercises on JAVA Basics

Hello friends, this blog is exclusively for those people who are newbies in java and find themselves more and more interested in learning and practicing JAVA. So while navigating through this blog,  you will observe that there are 7-8 basic sections I have prepared. Each section concentrates on a particular set of logic, which I feel even a mediocre student can practice and manifest a good programming skill. Do try each problem, find out the logic to solve it, apply your JAVA and see how interesting it is to code in JAVA.

It is strongly recommended not to refer any standard Google help/Text Book such as Head First Java or Thinking in Java or Let Us Java to "find out the Logic". Do not ever hesitate to put a query on any of the problem, if any. Enjoy programming. Love Programming. 

All the best!!!