Arrays – Insert into a div

Javascript arrays are just like any other object orientated language, in the aspect an array is a block of memory associated with main object. To create an array in Javascript just need to call
= Array(5);
Or
= Array(‘value1′,’value2’);

The code below is using a default screen from which you press the ‘Click Here’ button and the array is used to insert into a <div> html tag. To insert into a div tag within javascript, there needs to be a new node created and in this instance a text node is created which in turn is appended to the div.

The code hopefully will explain more.

<html>
       <script language="javascript">
              // setup the main array
              var setArray = Array("hi", "there", "this", "is", "a","test");
 
              // insert the array into the DIV smalltest object
              function insertArray()
              {
                     var theText = "";  // set the theText output to an empty string otherwise it would start with null.
                     for (var i=0; i < setArray.length; i++)
                     {
                            // create the array of text to insert
                            theText += setArray[i];
                     }
                     // create the createTextNode 
                     var insertText = document.createTextNode(theText);
                     document.getElementById("smalltest").appendChild(insertText);
              }
       </script>
       <body>
              Just a small test, 
              <div id="smalltest">
              </div>
              <input type="submit" value="click here" onclick="javascript:insertArray()" />
       </body>
</html>

Add two numbers

This tutorial demonstrates how to get two inputs from the user within a HTML page and have a button on the page to call a javascript method to process the inputs and alter the answer output on the web-page.

Within HTML, there are input tags that allow the user to input data that is passed either to a javascript method to validate the inputs (for example a registration forum) or to pass data back to the server (after the validation has taken place if required).

The value 1 input is defined as
value 1 = <input type=’text’ id=value1 name=’value1′ value=’1’/>
the input type is text, which means any textual value, [A-Z]*[0-9]* but in this case since just adding integers [0-9] would be the required input.
The id is for getting the value from the input with using javascript document.getElementById, value is for setting the default value.

The function within the javascript, addNumbers() will get the inserted value1 by using the javascript document object. Within this object there is a method called getElementById that returns back the object, which in turn using the .value of the object returned can be passed to the parseInt (which converts a string value into a integer value). The same method is used for the answer input within the web-page (getElementById) but assign the return object to a variable allows access to the .value to set the value on the web-page.

The source code is

<html>
  <head>
        <title>Input tutorial</title>
        <script language="javascript">
                function addNumbers()
                {
                        var val1 = parseInt(document.getElementById("value1").value);
                        var val2 = parseInt(document.getElementById("value2").value);
                        var ansD = document.getElementById("answer");
                        ansD.value = val1 + val2;
                }
        </script>
  </head>
  <body>
        value1 = <input type="text" id="value1" name="value1" value="1"/>
        value2 = <input type="text" id="value2" name="value2" value="2"/>
        <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/>
        Answer = <input type="text" id="answer" name="answer" value=""/>
  </body>
</html>

save as addtwonumbers.html and then open in a web browser (e.g. FireFox)

Hello world

Well, this is the javascript hello world. The javascript is used within web pages and the client browser (e.g. Internet Explorer or Firefox etc) will use the javascript code to help display the content of the page. This tutorial displays the “Hello World” in the webpage.

If you cut from

<html>
       <title>Javascript hello world</title>
       <body>
       <script language="javascript">
              document.write("Hello World!");
       </script>
       </body>
</html>

as javascripthelloworld.html

and then open up within IE or FF, this shall display a white page with the words in the top left “Hello World!”

The javascript is based on Objects, the same as Java,C++, C# etc, and the document object is the web page itself.

Hope it helps

Arrays

Arrays are ways of having a block of memory allocated to a single variable type, this allows for holding the national lottery numbers within an array of 6 instead of actually having 6 different variables, saves on variable overload

e.g.

int value1 = 1;
int value2 = 2;
int value3 = 3;
int value4 = 4;
int value5 = 5;
int value6 = 6;

and instead you could just have

int[] values = {1,2,3,4,5,6};

This is example code of how to use arrays.

public class arraytest
{
       public static void main(String[] args)
       {
              // the main method passes in parameters from the console command line 
              // e.g. ./arraytest hi there, hi there are two parameters
              for (int i =0; i < args.length; i++)
              {
                     System.out.println(args[i]);
              }
 
              // to create a array of numbers
              int[] intarray = {0,2,3,4};
 
              for (int i =0 ; i < intarray.length; i++)
              {
                     System.out.println(intarray[i]);
              }
       }
}

After compiled the above code and executed the class file that would be generated by

Java arraytest hi there

The output of the program would be

hi
there
0
2
3
4

But if the console command line was empty then just the number values would be outputted since they are inserted into the code and the ‘hi there’ was inserted manually on the command line.

Interfaces

An interface describes what functions an implemented class will have to code. E.g. if a class was a car and the interface had functions for how many doors etc, then a class of Vauxhall that implements the interface would have to code the function to return the correct amount of doors.

Here is the code, I usually find the code explains it better.

// defines the fuctions that have to be implemented by a implementable class
interface implementThese
{
       void printHi();       // have to implement these
       void printBye();
}
 
// the interClass will implement the interface implementThese
class interClass implements implementThese
{
       public void printHi()
       {
              System.out.println("Hi");
       }
 
       public void printBye()
       {
              System.out.println("Bye");
       }
}
 
class inter
{
       public static void main(String args[])
       {
              interClass in = new interClass();
              // call the classes functions.
              in.printHi();
              in.printBye();
       }
}

If you save as inter.java, and then run the output will be

Hi
Bye

There can be many interfaces per class to be implemented.

Generics

A Generic is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A generic class negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

This will demonstrate the basics of the generics.

// the class for the generics (the T is the object of any type)
class genericsClass<T> 
{
       T val;              // private object val of type T
       public genericsClass(T t)       // constructor for the class
       {
              val = t;              // set the internal to the passed value
       }
 
       public T returnValue()       // return the internal value
       {
              return val;
       }
}
 
// main runable class
public class generics
{
       public static void main(String args[])
       {
              // create a Integer class with a default value of 3
              genericsClass<Integer> genInt = new genericsClass<Integer>(3);
              System.out.println("Value= " + genInt.returnValue());
 
              // create a String class with a default value of "hi there"
              genericsClass<String> genStr = new genericsClass<String>("hi there");
              System.out.println("Value = " + genStr.returnValue());
       }
}

If you save the code and run with java version 1.5 + (since this was part of java 1.5). The output will be

Value = 3
Value = hi there

As you can see the same class is able to use both integer and strings as the default variable type.

Method – Add Two numbers

This tutorial uses the same code as Add Two Numbers but includes a function/method to add two numbers together and return a value. In this case the value is a integer (int) and that is why the int is just before the name of the method (addIntegers) with two parameters passed to the method, these are the values that are being added together. I have called them a and b, so that they are different names to the variables within the main method.

The source code

// just import the BufferedReader and inputstream reader
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
class addtwonumbers_function
{
       // private = local to this class
       private static int addIntegers(int a, int b)
       {
              return (a+b);
       }
 
       public static void main(String[] args)
       {
              // system.in reader (e.g. the input from the console)
              InputStreamReader ISR = new InputStreamReader(System.in);       
              // buffer the console reader
              BufferedReader BR = new BufferedReader(ISR);                     
 
              // the default values for the two numbers
              int val1 = 0;
              int val2 = 0;
              try 
              {
                     // output the question.
                     System.out.print("Enter first number : ");
                     // read in the console intput one line (BR.readLine) and then convert to a integer
                     val1 = Integer.parseInt(BR.readLine());
                     System.out.print("Enter second number : ");
                     val2 = Integer.parseInt(BR.readLine());
              }
              catch (Exception ex)
              {
                     // if the input was a string.
                     System.out.println(ex.toString());
              }
              // output the answer of adding both of the values together
              System.out.println("Answer = " + addIntegers(val1, val2));
       }
}

save as addtwonumbers_function.java, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.