Sunday, 15 July 2012

Java Strongly typed language


We call C/C++ and Java are strongly typed languages and JavaScript and PERL are loosely typed languages. What does it mean?

Either in C or Java, when a variable is declared, it must be informed to the compiler what data type the variable stores like integer, float, double or string etc. Observe the following variable declaration in Java.

  int marks = 20.
            String str = "way2java.com";
            boolean raining = true;



The variable must be declared along with the data type. Similarly, an array object must be instantiated with the size. This is a feature of strongly typed languages.

Just reverse with loosely typed languages. Observe the variable declaration in JavaScript, an object-based language.



 var marks = 20.
            var str = "way2java.com";
            var raining = true;



The string and data types int and boolean are replaced by var that stands for variable. Depending on the value assigned, var becomes a number or a string or boolean. This is done implicitly by the JavaScript interpreter. It looks strange and unbelievable for a C or Java programmer. A JavaScript programmer need not remember the list of data types (actually, they exist), JavaScript supports.

It looks nice and easy with loosely typed languages. But I feel it raises a lot of problems in coding. Observe the following.

Say in Java language:



 int cost = 10;
             int cost = 20;

It is compilation error as two times cost is initialized. You must declare only ones and can be reassigned number of times as follows.


int cost = 10;
            cost = 20;


Same thing in JavaScript or PERL is not error. Observe the code.


 var cost = 10; 
            var cost = 20;


The earlier cost value is overridden with 20, but not error; earlier value is lost. This is a very dangerous situation which leads problems. If an article costs Rs.10 and the programmer declared correctly earlier. In the later part of the code, he forgot that he declared and redeclares with a different value (which may be wrong). For this reason, the object-based languages like JavaScript, PERL and Ruby etc. have limited scope in programming and are not used as full-fledged languages to develop software like banking, insurance etc.

A strongly typed language compiler enforces strict rules over the operations, what programmer can do, on data types and also passing parameters and return type to a method. An advantage of strongly typed language is it gives consistency over the results (by declaring the variables with data types). Specific operations are allowed on certain types. For example boolean cannot be used in addition, but an int can be used in addition. Boolean is used in control structures. This type of accidental wrong coding raises error by a strongly typed language.









No comments:

Post a Comment

There was an error in this gadget