Search This Blog

Tuesday, 31 March 2015

10 difference between Java and JavaScript for Programmers


Programmers, developers and internet users  have always been confused between Java and JavaScript.  Many people still thinks that JavaScript is part of Java platform, which is not true. In truth, JavaScript has nothing to do with Java, only common thing between them is word "Java", much like in Car and Carpet, or Grape and Grapefruit. JavaScript is a client side scripting languagefor HTML, developed by Netscape, Inc, while Java is a programming language, developed by Sun Microsystems. James Gosling is Inventor of Java, popularly known as father of Java. While in today's world calling JavaScript just a client side scripting language would not be good, as its now been used in servers also using node.js and people are doing object oriented development in JavaScript, but that was what it was originally developed. There are several difference between Java and JavaScript, from how they are written, compiled and executed. Even capability of Java and JavaScript vary significantly. Java is full feature Object oriented programming language, used in almost everywhere, starting from programming credit card to server side coding. Android uses Java as programming language for creating Android apps, Swing is a Java API used to create desktop applications and Java EE is a Java platform for developing web and enterprise applications. On the other hand JavaScript is primarily used to bring interactivity into web pages, though there are other alternatives like Flash, JavaScript is the most popular one and regaining lots of ground lost earlier with introduction of powerful and easy to use libraries like jQuery and jQuery UI. You can use JavaScript to validate user input, create animation and cool effects in HTML page and can do lot of interactive stuff e.g. reacting on button click, mouse movement, image click etc. In this article, I will share some key differences between Java and JavaScript, mostly from a programmers perspective.
Here is my list of key differences between JavaScript and Java as programming languages. I have worked both on them, mainly used Java for all Server Side development, Android and JavaScript for writing client side scripts to do validation, interactivity, animation and ajax calls.
Difference between Java and JavaScript
1) Execution Environment



First difference between Java and JavaScript is that Java is compiled + interpreted language, Java code is fist compiled into class files containing byte code and than executed by JVM, on the other hand JavaScript code is directly executed by browser. One more difference which comes form this fact is that, Java is run inside JVM and needs JDK or JRE for running, on there other hand JavaScript runs inside browser and almost every modern browser supports JavaScript.

2) Static vs Dynamic Typed language



Another key difference between JavaScript and Java is that, JavaScript is a dynamic typed language, while Java is a statically typed language. Which means, variables are declared with type at compile time, and can only accept values permitted for that type, other hand variables are declared using vary keyword in JavaScript, and can accept different kinds of value e.g. Stringnumeric andboolean etc. When one variable or value is compared to other using == operator, JavaScript performs type coercion. Though it also provides === operator to perform strict equality check, which checks for type as well. See here for more differences between == and == operator in JavaScript.

3) Support of Closures



JavaScript supports closures, in form of anonymous function. In simple words, you can pass a function as an argument to another function. Java doesn't treat method as first class citizen and only way to simulate closure is by using anonymous class. By the  way Java 8 has brought real closure support in Java in form of lambda expression and this has made things much easier. It's very easy to write expressive code without much clutter in Java 8.

4) OOP



Java is an Object Oriented Programming language, and though JavaScript also supports class and object, it's more like an object oriented  scripting language. It's much easier to structure code of large enterprise application in Java then JavaScript. Java provides packages to group related class together, provides much better deployment control using JAR, WAR and EAR as well.

5) Right Once Run Anywhere



Java uses byte code to achieve platform independence, JavaScript directly runs on browser, but code written in JavaScript is subject to browser compatibility issue i.e. certain code which work in Mozilla Firefox, may not work in Internet Explorer 7 or 8. This is because of browse based implementation of JavaScript. This was really bad until jQuery comes. Its a JavaScript library which helps to free web developers from this browser compatibility issues. This is why I prefer to write code using jQuery rather than using plain old JavaScript code, even if its as simple as calling getElementById() or getElementByName() methods to retrieve DOM elements.

7) Block vs Function based Scoping



Java mainly uses block based scoping i.e. a variable goes out of scope as soon as control comes out of the block, unless until its not a instance or class variable. On the other hand JavaScript mainly uses function based scoping, a variable is accessible in the function they are declared. If you have a global variable and local variable with same name, local will take precedence in JavaScript.

8) Constructors



Java has concept of constructors, which has some special properties e.g. constructor chaining and ensuring that super class constructor runs before sub class, on the other hand JavaScript constructors are just another function. There is no special rules for constructors in JavaScript e.g. they cannot have return type or their name must be same as class.

9) NullPointerException



JavaScript is much more forgiving than Java, you don't have NullPointerException in JavaScript, your variable can accept different kinds of data because of JavaScript is dynamically typed language.

10) Applicability



Last but not the least, JavaScript has it's own space, sitting cozy along with HTML and CSS in Web development, while Java is everywhere. Though both has good number of open source libraries to kick start development, but jQuery has certainly brings JavaScript on fore front.
That's all on difference between Java and JavaScript language. As I said, they are totally different language, one is a general purpose programming language, while other is scripting language for HTML. Though you can do lot of fancy stuffs using JavaScript, you still don't have features like multithreading, as compared to Java. By the way JavaScript was originally named as Livescrpit, may be due to the fact that it makes your HTML pages live, and programming world would certainly be free of this confusion, had Netscape hadn't renamed LiveScript as JavaScript.



Thursday, 26 March 2015

How to reverse array in place in Java?

Reversing an array sounds pretty easy, isn't it? It does sounds like that, because all you need to do is create an array of same size, iterate through original array from end to start and populate your new array. Boom!!, you have got an array which has elements in reverse order of original array, but problem is you have used and additional array here, which makes space complexity of your solutionO(n). You cannot use this solution if array is big e.g. an array of 10 million orders and you don't have enough heap space available. Can we make it better? Can we reverse array in Java without using an additional buffer? Even If you encounter this question in your programming job interview, you will be surely asked to reverse array in placewithout using an additional buffer as earlier solutiontakes lot of space. So now your task is to write a Java program to reverse an array in place. For the sake of this problem, you can assume that its an integer array (during interview, you should ask these question to your interviewer, because asking right question to fill the gap in requirement is a trait of good programmer and highly appreciated on both telephonic and face-to-face interviews). Key point to understand here is that you need to reverse the same array, you cannot use another array but one or two variable is fine. You are also not allowed to use any open source library or Java API which can reverse the array directly e.g. any method from java.util.Arrays class except Arrays.toString()to print arrays in Java. So now the requirement is clear, what approach comes in your mind? how do you solve this problem?


Java Program to Reverse Array In Place

The first thing which comes in my mind is to loop through array and swap the elements of array e.g. swap first element with last element, swap second element with second last element until you reach the middle of the array. This way, all elements of array will be reversed without using any additional buffer. Key thing to keep in mind in this algorithm is that you only need to iterate till middle element, if you go beyond that then you end up swapping elements twice and result in same array. Some of you will be puzzled, what is length of array is even? In that case there will be two middle element and we need to swap them, that's why your loop condition should be index <= middle and not index < middle. Here middle index is nothing but length/2. Remember, we are using division operator, which means if length is 8 then it will return 4 and when length is 7 it will return 3. So in case of even length, the middle element will be swapped twice, but in case of odd length there is just one middle element and it will not be swapped.

It's been said time and again that a picture is worth a thousand word and true to the point, this image explains the algorithm we used to reverse array in place quite well. You can see that how elements of arrays are swapped position with each other and middle element remain unchanged, with just two swapping we have reversed an array of five elements.

Algorithm to reverse array in place in Java

Here is our sample Java program to reverse array in placesolution is simple and easy to follow, but don't forget to look my JUnit tests to understand it bit more.

import java.util.Arrays;

/**
 * Java Program to demonstrate how to reverse an array in place.
 */
public class ArrayReversalDemo {

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7};
        reverse(numbers);
    }

    /**
     * reverse the given array in place 
     * @param input
     */
    public static void reverse(int[] input) {
        System.out.println("original array : " + Arrays.toString(input));
        
        // handling null, empty and one element array
        if(input == null || input.length <= 1){
            return;
        }       
        
        for (int i = 0; i < input.length / 2; i++) {
            int temp = input[i]; // swap numbers
            input[i] = input[input.length - 1 - i];
            input[input.length - 1 - i] = temp;
        }

        System.out.println("reversed array : " + Arrays.toString(input));
    }
    
    
}

Output
original array : [1, 2, 3, 4, 5, 6, 7]
reversed array : [7, 6, 5, 4, 3, 2, 1]
original array : []
original array : null
original array : [1, 2, 3, 4, 5, 6]
reversed array : [6, 5, 4, 3, 2, 1]
original array : [1]

You can see in output here that input array is reversed properly and in case of null, empty and array with just one element, same array is returned.

JUnit tests

Here is my suite of JUnit tests for our reverse(int[] input)  method. I have made sure to test our solution can handle null, empty array, an array with just one element, and array with even or odd number of elements. You can even test drive this problem. Writing Unit test is a good practice and during Interview you must write JUnit test even if Interview has not asked for it. This shows that you are a professional software developer and you care for your trade.
import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;

public class ArrayReversalDemoTest {
    
    @Test
    public void testReverseWithEvenLengthOfArray(){
        int[] numbers = {1, 2, 3, 4, 5, 6};
        HelloWorld.reverse(numbers);
        assertArrayEquals(new int[]{6, 5, 4, 3, 2, 1}, numbers);
    }
    
    @Test
    public void testReverseWithOddLengthOfArray(){
        int[] numbers = {1, 2, 3, 4, 5, 6, 7};
        HelloWorld.reverse(numbers);
        assertArrayEquals(new int[]{7, 6, 5, 4, 3, 2, 1}, numbers);
    }
    
    @Test
    public void testReverseWithEmptyArray(){
        int[] numbers = {};
        HelloWorld.reverse(numbers);
        assertArrayEquals(new int[]{}, numbers);
    }
    
    @Test
    public void testReverseWithNullArray(){
        int[] numbers = null;
        HelloWorld.reverse(numbers);
        assertArrayEquals(null, numbers);
    }
    
    @Test
    public void testReverseWithJustOneElementArray(){
        int[] numbers = {1};
        HelloWorld.reverse(numbers);
        assertArrayEquals(new int[]{1}, numbers);
    }
   
}

and here is the output of running our unit tests, they all pass.

How to reverse array in place in Java



That's all about how to reverse array in place in Java. Time complexity of this method is O(n/2) or O(n) because it only iterate through half of the array, but its in O(n) because response time increases in same order as input increases. As a task, can you find a faster solution of this problem?


Tuesday, 17 March 2015

Top 10 Popular Programming languages and their Inventors

Here is my list of top 10 programming language and their creators. Languages are listed on no particular order, but since I am a Java developer and benefited a lot from Java, I have no hesitation to put it on top of the list. I know many C programmer will not agree as C is the longest surviving, yet going strong programming language, but this is not about ranking but about knowing and remembering their creators. The master programmers who has made difference in the world of programming language and software development.

1) Java - James Gosling

Java is one of the most popular and successful programming language. Dr. James Arthur Gosling is invented Java and best known as the father of the Java programming language. Java was developed and supported earlier by Sun Microsystem and now by Oracle, after their acquisition of Sun Microsystem on January 2010. Java is created with mission WORA, "Write Once Run Anywhere" and platform independence of Java is one of the pillar of it's success in the enterprise world. Till date, it is one of the most popular application programming language.


2) C - Dennis Ritchie

Dennis MacAlistair Ritchie, An American computer scientist, created the C programming language between 1967 and 1973 at AT&T Bell labs. C is still very popular and used extensively in System programming. It's older than Java but still maintains it's stronghold. By the way Dennis Ritchie has also created world famous UNIX operating system, with his long-time colleague Ken Thompson. If you compare his popularity with Bill Gates or Steve Jobs, he is no where but if you compare Dennis' contribution to the software world, he has no matching. Every Programmer must know about Dennis Ritchie and his contribution to the programming world.

 

3) C++ - Bjarne Stroustrup

Bjarne Stroustrup; born 30 December 1950 in Aarhus, Denmark is a Danish computer scientist, most notable for the creation and the development of the widely-used C++ programming language. C++, as name suggested is the next generation language at time C was popular. It comes with object oriented programming feature which was considered phenomenal compared to structural way of C programming. C++ is still one of the very popular language and used extensively in high frequency trading world because of its close proximity with native System and popular object oriented feature.



4) Python - Guido van Rossum

Python is a general-purpose, high-level programming language, whose design philosophy emphasizes code readability. Its syntax is said to be clear and expressive.Python is designed by Guido van Rossum of CWI. In United states, Python has actually replaced Java at academic level, now days students are started learning programming using Python instead of C or Java, as was the case of previous generation. If you are still not sure whether to use Python or Java to start with programming, this infographic may help you. Python is used extensively in web application development, there are lots of python based web framework out there, software development and information security. Python is also used extensively by tech giants like Google, Yahoo and Spotify.



5) PHP - Rasmus Lerdorf

No matter how much you hate PHP, you just can't ignore the fact that half of the internet is running on this wonderful internet language. PHP was originally created by Rasmus Lerdorf in 1995. The main implementation of PHP is now produced by The PHP Group and serves as the formal reference to the PHP language. That time, PHP was a competitor to Microsoft's Active Server Pages (ASP) server-side script engine and similar languages e.g. Java Server Pages (JSP), but gradually received better acceptance and is now installed on more than 20 million Web sites and 1 million Web servers. It is also open source and used by internet giants like Facebook, Wikipedia, Wordpress and Joomla. PHP is used extensively to to build dynamic web pages and server side development. Sorry, I forgot to tell you the full form of PHP, any guess? Its Personal Home Page :)



6) Perl - Larry Wall

Perl is a high-level, general-purpose, interpreted, dynamic programming language. designed and developed by Larry Wall in the mid-1980's. Perl rose to fame because of its excellent text processing capability. It is still main language to develop reports, scripts on UNIX systems. Perl is known for parsing and processing large text files and its used in CGI, database applications, network programming and graphics programming. Perl is also used extensively by internet companies like IMDB, Amazon, and Priceline. For Java developers, adding Perl or Python in their portfolio is good addition because you often need a scripting language to do adhoc tasks for maintenance and support purpose.



7) JavaScript - Brendan Eich

If you ask me, which language is the winner in last 5 to 10 years, I would say JavaScript. It has clearly dominated the client side scripting space in recent past with libraries like jQuery and now moving to Server side development with libraries like node.js. JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions, designed by Brendan Eich and developed by Netscape Communications Corporation. JavaScript is used extensively for client side scripting, validation, animation, event capturing, form submission and other common task. It runs inside browser and used by almost all websites e.g. Gmail, Mozila Firefox etc.



8) Ruby - Yukihiro Matsumoto

Ruby was first designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan. Its fun working with Ruby and if you tried Ruby with Rails you know what I mean. Ruby is influenced by Perl, Ada, Lisp and Smalltalk and designed for productive and enjoyable programming. Ruby is mostly used for web application development and used by major sites like Twitter, Hulu and Groupon.



9) Lisp - John McCarthy

John McCarthy , second oldest high level programming language. Lisp stands for List processor. I have never tried Lisp but its said to be father of functional programming language e.g. Haskell, Erlang or Scala. It is used for AL development and air defense system.



10) Pascal - Niklaus Wirth

Pascal is an influential imperative and procedural programming language, designed in 1968–1969 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.
and here is the infographic, which gives you a nice overview of 10 programming language and their creators. It contains some of the language mentioned here, plus some additional language like FORTRAN and Ada.
Top 10 Programming Language and creators
That's all about top 10 programming languages and their Inventors. They have made huge difference in programming world and without their contribution, we would not be here. Some of them are here with us and some of them has left us for better place, let's remember them for their contribution to our programming world.



Blog Archive