Skip to main content
blog title image

4 minute read - Java For Testers

Some Similarities Between Java And JavaScript

May 7, 2018

TLDR: Learn one programming language and you have already learned parts of other languages. You can speed up learning other languages by learning the differences.

I wrote a bunch of code in Java in my Test Tool Hub for generating CounterStrings.

I thought it would be useful to have it online and written in JavaScript.

JavaScript and Java have a lot of similarities. So many similarities in fact that I was able to copy and paste the code, and then make minor tweaks without too much thinking.

If you already know Java then learning these similarities and differences might help learn JavaScript faster.

Similarities

Both JavaScript and Java:

  • use { and } as code block delimiters
  • use ; to end statements
  • have a Math library e.g. Math.pow
  • have if, do...while (pretty much same syntax)
  • have return statements

Differences

Classes are Functions

JavaScript now has a class object, but I tend not to use it.

In JavaScript an object can be created with a new keyword on functionCall()

So Classes are really functions.

e.g. here is a JavaScript function representing an object

function CounterStringRangeStruct(space, minX, maxX) {
    this.spaceValueInRangeTakes=space;
    this.minValInRange=minX;
    this.maxValInRange=maxX;
};

And here is a similar Java Class.

public class CounterStringRangeStruct {
    public final int spaceValueInRangeTakes;
    public final int minValInRange;
    public final int maxValInRange;

    public CounterStringRangeStruct(int space, int minX, int maxX) {
        this.spaceValueInRangeTakes = space;
        this.minValInRange = minX;
        this.maxValInRange = maxX;
    }
}

They are different, I haven’t represented the final notion in the Java. But you can see the similarities

Both languages would instantiate an object with the same syntax:

new CounterStringRangeStruct(5, 1, 2);

Methods are Functions

Methods are really functions within functions in JavaScript.

e.g. an append method on StringCounterStringCreator

function StringCounterStringCreator(){

    this.string="";

    this.append = function(nextPart) {
        this.string = this.string + nextPart;
    }
};

And here is a similar Java Method.

public class StringCounterStringCreator implements CounterStringCreator {

    private final StringBuilder string;

    public StringCounterStringCreator(){
        string = new StringBuilder();

    }

    @Override
    public void append(String nextPart) {
        string.append(nextPart);
    }
}

To convert my classes from Java to JavaScript I basically:

  • copy and pasted the Java code into a JavaScript file
  • converted the classes into functions
  • if my classes have constructors then I incorporated the constructor code into the main function
  • converted all methods into functions on the main function
  • removed all types from Java in the JavaScript
  • added ; after all function definitions
  • converted my Java lists into JavaScript arrays
  • fixed syntax errors

Differences

Some code I have to change.

e.g.

  • javascript uses unshift to add an item to the start of an array
  • be careful about types - since JavaScript doesn’t have types, I have to be careful about the code I write.
    • for the app I was converting this meant that I had to enforce some integer division with Math.floor(x/y)
  • converting numbers to strings was simpler in JavaScript number.toString()
  • Java String .length() method is a property in JavaScript .length
  • remember to add this. in JavaScript otherwise a local variable is assumed and used

Code

But code was much the same.

You can see code similarities if you look at my JavaScript Counterstring code:

And the Java code it is based on was:

The class names match the function names in the JavaScript.

Differences That Bite

Differences that bite me because I constantly forget.

Polymorphic Methods

JavaScript does not have polymorphic method declaration e.g.

function generateCounterString(){
    var howlong = Number(document.getElementById('lengthOfCounterString').value);
    generateCounterString(howlong);
}
function generateCounterString(howlong){
    var separator = document.getElementById('csseparator').value;
    document.getElementById(elementIdToStoreResult).innerText=
        new CounterString().create(howlong, separator);
    document.getElementById("status").innerText="Generated - Ready to Copy"
}

The above doesn’t work.

The second declaration overrides the first. A call to generateCounterString() is actually a call to generateCounterString(undefined)

And my code doesn’t handle that.

I default to ‘default’ argument processing code like this:

howlong = typeof howlong !== 'undefined' ? 
            howlong : Number(document.getElementById('lengthOfCounterString').value);

Caveats

Clearly it is better to have a set of tests for the code when you migrate code to a different language. I didn’t have that.

  • but the Java code was well covered with unit tests
  • the functionality is pretty self contained with only one or two entry methods, so was easy to test interactively

Organised code is easier to migrate.

  • I amended my Java code prior to migration
  • refactored the code
  • simplified code into new classes
  • added more JUnit tests on the Java code
  • simplified the algorithms

Things that bit:

  • polymorphic methods
    • different languages have different coding styles so we have to learn them
  • lack of types
    • I had to use methods to enforce integer arithmetic in JavaScript
    • JavaScript arrays are so flexible I didn’t need to use any List code

Why Migrate

Migrating code can help learn a new language.

  • you can compare the working code for the same example
  • you have to learn nuances to get simple code working
  • you concentrate on the ‘differences’ which helps learn new language features