Personal tools
You are here: Home Information Systems Java Platform Introduction 4. Java and Javascript 4. Java and Javascript

4. Java and Javascript

Document Actions
  • Send this
  • Print this
  • Content View
  • Bookmarks

Java and Javascript

<-- Previous

Table of Contents

Next -->

If you have explored scripting languages such as VBScript and Javascript, this has provided you with some very valuable programming experience. It has had the disadvantage of teaching you programming in loosely typed environments however. Java is anything but a loosely typed language and there are some very crucial differences that you will have to absorb, although there are a lot of similarities too. These similarities make the move from Javascript to Java a lot easier as quite a lot will be familiar to you.

  1. Javascript is interpreted at runtime by whatever browser happens to be accessing the file containing the Javascript code. This means that different browsers interpret Javascript in different ways. Java however, always runs in exactly the same way on any platform because of the Java VM, whose job it is to make sure that this is the case. So, what works in a particular way on the computer on which you wrote Java code, will always work in exactly the same way on any computer running Java.
  2. Java, while considered to be an object-oriented programming language (OOP), is not completely object-oriented. In Java, numbers are not objects, so you can never call a static method on a number, i.e. if sqrt() is the Java method which returns the square root of a number, you cannot use:
    double myNum = 4;
    double result = myNum.sqrt();  //ERROR - illegal method call!
    Numbers can only be passed as explicit arguments to a method, enclosing the number in parentheses after the method name:
    double myNum = 4;
    //Calling a static method of the Math class
    double result = Math.sqrt(myNum);
    A static method is simply a method that cannot operate on any object - the name has nothing to do with the usual meaning of static in Java (which we will examine later).
  3. There are some strong similarities between the way in which Javascript and Java code is written, e.g. the way in which if(){} statements, for(){} statements, and single lines of code are written is essentially the same in both languages, including the semi-colon which indicates the end of a programming statement. In Javascript, if you leave out the semi-colon the code will in most cases still run; in Java the semi-colon is compulsory.
    //Java if() statement
    boolean testVal = true;
    if(testVal) {
       testVal = false;
    } else {
       testVal = true;
    }
    
    //Java for() statement
    int count = 0;
    for(int k=0; k < 6; k++) {
       count += 2;
    }

    Note above that Java for() statement expressions should include a data type for the loop counter where applicable - see the last paragraph of this page.

    In common with Javascript, if() and for() statements work by evaluating an expression placed in the parentheses that follow the keywords if and for. The expression in an if() statement must evaluate to one of the two boolean values true or false. If the expression evaluates true the code block within the if(){} statement's curly braces will execute. The expression in the for(){} statement's parentheses is used to determine how many times the code block in the curly braces will execute - see the two statements above.

  4. Both Java and Javascript are case sensitive.
  5. Comments in both languages are written in identical ways:
    //A single line comment.
    
    /*A comment that spans
    more than one line.*/
    Java however has some extra ways of writing comments that serve a special purpose; we will examine these when the time comes.
  6. Javascript assigns data types to objects on the fly, i.e. the interpreter makes its own decisions about whether some data are a string, a number, or an object. In Java, all data typing must be explicit. This means that every single variable that you define must be assigned a data type, and must also be initialised with some value that is legal for the data type which it is declared as. The Java data types that we will mostly be dealing with are:
    • byte - an integer value capable of being represented by a single byte, i.e. values from -127 to +127
    • int - a 16-bit integer, positive or negative, e.g. 1752
    • float - a floating point decimal number, e.g. 23.629F
    • double - a double-precision number, e.g. 45.7823
    • char - a character literal, i.e. a single character, delimited by single quotes: 'Q'
    • String - a string object (Object data type)
    • boolean - a boolean value (true or false)

    With the exception of the String object, all the data types above are primitive data types, i.e. they are not objects.

    In addition, every method and routine in Java must contain a declaration which indicates whether the code is public or private, static, which class it belongs to or is defining, what data type any returned value will be, the data type and name of all parameters, and the type of any exception (error) which the code might throw. For example:

    public class ConsoleInputTest {
       public static void main(String[] args) throws IOException {
         String input1;
         int count2;
         ...
         ...
       }
    }
    By way of a further example, consider the two code blocks below, both of which do exactly the same thing; the first is a Javascript function, the second is a Java class with equivalent object method:
    //Javascript function:
    function checkString(myString){
       var intCount = myString.length;
       var strHold;
       if(intCount < 10){
          strHold = "Input string too short!";
       } else {
          strHold = "String length is: " + intCount;
       }
       return strHold;
    }
    
    
    //Java class with equivalent object method:
    public class StringChecker {
      private String myString;
      private int intCount;
      
      //Constructs a StringChecker object>/font>
      public StringChecker(String aString) {
         myString = aString;
         intCount = myString.length();
      }
      
      //Object method
      public String checkString(){
         String strHold = "";
         if(intCount < 10){
            strHold = "Input string too short!";
         } else {
            strHold = "String length is: " + intCount;
         }
         return strHold;
      }
    }
    Note the following:
    1. Javascript has functions, Java has object methods.
    2. Javascript functions can stand alone; Java methods are member functions of a class.
    3. In Javascript, the function variables are declared in the body of the function; in Java, the variables are usually declared in the body of the class to which the method belongs. In the code above, only the block in bold type is the actual method.
    4. Normally no explicit data typing is required in Javascript; in Java all variables must be explicitly data typed when declared. Javascript merely uses the keyword var to initialise all variables, as they are automatically data typed by the interpreter. Data types such as double or String take the place in Java of the Javascript keyword var.
    5. Methods must be declared public or private, depending on whether they are visible (can be called) from outside the class (public), or are used inside the class only (private).
    6. The same goes for member variables, whose visibility must be declared (public or private).
    7. The data type of any data returned by a method must be declared in the method declaration, after the declaration of the visibility (public/private) of the method.
    8. In Java, by convention method names begin with a lowercase letter; class names begin with a capital letter.
    9. Object methods are used in the same way in both languages, i.e dot notation:
      StringChecker myStrChkr = new StringChecker("qwerty");
      String returned = myStrChkr.checkString();
      Notice that the checkString() method of the StringChecker class returns a value just like many other functions, so the return value of this method must be assigned to a variable - the string object variable returned in this particular case.
  7. In Javascript, arrays are not finite, i.e. we can add as many elements to any array as we choose. In Java, an array once declared is finite - it can have only as many elements as it is declared to have. Arrays are objects in both languages, and in both cases have a property length which is equal to the number of elements in the array. Array indices are zero based in both Java and Javascript, i.e. the first element in any array is element 0, the 2nd element is element 1, and so on; a 6-element array will therefore have indices 0 to 5. To declare an array:
    //Javascript 6-element array
    var myArray = new Array(5);
    for(k=0; k < myArray.length; k++){
        myArray[k] = k;
    }
    
    //Java 6-element array
    int[] myArray = new int[6];
    for(int k = 0; k < myArray.length; k++){
        myArray[k] = k;
    }
    Note that in Javascript an array is defined by using round () parentheses; in Java square parentheses are used after the name of the data type that the array will hold - String[]. This means that Java arrays are more formal - they must be data typed like all other variables in Java. In Javascript we can place any kind of value in any element of any array; this is not possible in Java. Also, in Java the number of elements required in the array must be placed in the brackets; in Javascript a number 1 less than the number of elements is entered.

     

  8. In both languages instances of an object must be created by using the new keyword. In Java however, the object classname must precede the name of the object variable - this works exactly like declaring the data type of a variable. Using the class StringChecker declared in the code above, if we want to create a new StringChecker object, we declare and initialise it like this:
    StringChecker myStringChecker = new StringChecker(theString);
    This is standard and compulsory; so initially the rule is:
    ClassName objectVariableName = new ClassName(arguments);
    There must be parentheses after the class name that follows the new keyword because some classes have parameters in the same way that some methods have parameters. We will learn more about this when we come to the section on object constructors (in Java, object classes contain a special method that builds an instance - actual object - of that class). Strictly speaking then, the rule for object instantiation is really:
    ClassName objectVariableName = new ObjectConstructorName(arguments);
    In Java the name of a constructor is always the same as the name of the class, except that parentheses are added to the end of the name, and if required arguments must be placed in the parentheses. For example, let's say we define a Circle class which has a constructor Circle(double aRadius). To create and assign a circle object that has a radius of 6.2 cm to an object variable called myCircle, we would need to say the following:
    //ClassName objectName = ObjectConstructorName(arguments);
    Circle myCircle = new Circle(6.2);

<-- Previous

Table of Contents

Next -->

Copyright 2007-2008, by the Contributing Authors. Cite/attribute Resource. 4. Java and Javascript. (2008, July 16). Retrieved May 22, 2013, from UWC Free Courseware Web site: http://freecourseware.uwc.ac.za/freecourseware/information-systems/java-platform-introduction/java-and-javascript-1/java-and-javascript. This work is licensed under a Creative Commons License : Attribution-ShareAlike 3.0. Creative Commons License : Attribution-ShareAlike 3.0