Creating Hashtables in C#

Creating a Hashtable Object with the Hashtable Class in C#

The hashtable class in C# is used to create a hash table. The syntax to create a new hash table is:

public Hashtable name_of_hashtable = new Hashtable ();

When you create a new hashtable, it is empty. Let’s create a hashtable called hashtableexample and place three integer keys inside it:

using System.Collections;
using System;
class Example
    static void Main()
                Hashtable hashtableexample = new Hashtable();
                hashtableexample[1] = "One";
                hashtableexample[3] = "Three";
                hashtableexample[29] = "Twenty-Nine";
                foreach (DictionaryEntry entry in hashtableexample)
                    Console.WriteLine("{0} : {1}", entry.Key, entry.Value);
29: Twenty-Nine
3: Three
1: One

In this program, we have created a class called Example to hold the hashtable named hashtableexample. We added three integer keys to that hashtable, with different entry key numbers and values. The integer keys we added belong to the DictionaryEntry type, which contains keys and their corresponding values. We added three keys with different key entries and values. In the final part of the program, we printed the keys with the corresponding values to the screen using the foreach loop.

It’ll be easier to learn the language as a whole instead of bits and pieces, so we recommend you check out this advanced course in C# to learn more about hashtables.

Adding Entries to a Hash Table

Now that we know how to add keys to a hash table, let’s see how to add entries to it. The syntax to add an item to a hashtable object is:

name_of_hashtable.Add(Parameter 1 (Data), Parameter 2 (Data))

You’d understand the syntax better with an example program. We’ll write a simple hashtable that contains the name of three authors and the number of books they’ve sold recently:

using System.Collections;
using System;
class Example
    static void main()
                // Creating a simple hashtable called hashtableexample.
                Hashtable hashtableexample = new Hashtable();
                hashtableexample.Add("JKRownling", 5000);
                hashtableexample.Add("JArcher", 3000);
                hashtableexample.Add("AChristie", 1000);

We created a simple hashtable with three entries inside it. As you can see, we used string values as well as integer values. Both your entries could have contained string or integer values. You can try writing the hashtable to the screen to see what it looks like (using the foreach loop, as we showed you earlier).

Hashtable Methods

There are several methods that you can use with the hashtable class. The Add method, for example, adds an entry to the hashtable class (like in the program above), the Clear method can be used to wipe the hashtable clean, the Clone method creates a copy (shallow) of your hashtable and the GetHash method returns the hashcode for a specific key. You will need to get familiar with most of the hashtable methods if you’re going to get a good grasp on hashtables and handle them properly. You can check out the different methods in the official documentation on the Microsoft Office website. Learn more about these methods in detail with this C# course.

We’ll write a simple program that demonstrates the use of the Contains method to help you understand the concept better. We’ll just extend the program we wrote earlier:

using System.Collections;
using System;
class Example
static Hashtable GetHashtable()
                // Creating a simple hashtable called hashtableexample.
                Hashtable hashtableexample = new Hashtable();
                hashtableexample.Add("JKRowling", 5000);
                hashtableexample.Add("JArcher", 3000);
                hashtableexample.Add("AChristie", 1000);
                return hashtableexample;
static void Main ()
Hashtable hashtableexample = GetHashtable ();
Console.WriteLine(hashtableexample.Contains (“JKRowling”));

The Contains method checks the hash table to see if a specific key is present. If it is, it will return a true value. If not, it returns a false value. We created a simple hash table called hashtableexample and then returned its value. We then checked to see if any of the keys in the hash table match “JKRowling” with the Contains method.

C# also has a newer, much more efficient class called the Dictionary collection which is quite similar in functionality. If you’re going to operate or maintain one of those programs for a company, you need to know about the hashtable class. The .NET framework makes C# sharp portable and platform independent, just like Java.  There is a growing demand for C# programmers in the industry and a shortage of good programmers. You may want to explore C# programming as a career option. This three part course gets into the details of C#(Part I, Part II, Part III) – from the basics to the advanced concepts – to help you along your journey.

Star Wars Javascript Game

I wanted to see if I could create a simple game example using numerical randomized values and using Javascript one page coding. I will probably expand the gameplay of this game in the future but here is the initial coding for a Star Wars game.

Here is a link to the game:
Here is a link to the GitHub source code:

 var myHealth = 100,
    enemy1Health = 100,
    enemiesKilled = 0,
    attackPower1 = 1,
    attacking = 0,
    enemyLoaded = 0,
    enemy1dead = 0,
    enemy2dead = 0,
    enemy3dead = 0;

    function isGameOver(){
      if (enemiesKilled === 4) {
      $("#you-won").html("<h1>YOU WIN</h1><br><h2>You defeated all enemies</h2>");
      document.getElementById("you-won").style.background = "#f4af0a";
      document.getElementById("you-won").style.padding = "30px";
      document.getElementById("enemy-image").style.display = "none";

    function iAmAttacking() {
          if (enemyLoaded === 0) {
          } else {
                var myAttack = attackPower1;
                enemy1Health = (enemy1Health - myAttack);
                document.getElementById("healthBar").style.width = (enemy1Health + "%");
                      if (enemy1Health <= 0) {
                            document.getElementById("healthBar").style.width = "0%";
                            $("#enemy-image").html("<img class='enemypic' src='assets/images/explode.gif'>"); 
                            $("#kills").html(enemiesKilled + " /4");
                           document.getElementById("bottom-col").style.opacity = "100"; 
                            enemyLoaded = 0;
                            enemy1dead = 1;
                      } else {

    function enemyIsAttacking() {
        if (attacking === 1) {
        var enemyAttack = Math.floor(Math.random()*10);
        if (attacking === 2) {
        var enemyAttack = Math.floor(Math.random()*18);
        if (attacking === 3) {
        var enemyAttack = Math.floor(Math.random()*7);
        if (attacking === 4) {
        var enemyAttack = Math.floor(Math.random()*4);

          myHealth = (myHealth - enemyAttack);
              if (myHealth <= 0) {
              document.getElementById("myHealthBar").style.width = ("0%");
              $("#you-won").html("<h1>YOU LOST</h1><br><h2>You were defeated by the enemy</h2>");
              document.getElementById("my-attack").style.display = "none";
              document.getElementById("power1").style.display = "none";
              document.getElementById("you-won").style.background = "red";
              document.getElementById("you-won").style.padding = "30px";
              document.getElementById("enemy-image").style.display = "none";
              } else {
              document.getElementById("myHealthBar").style.width = (myHealth + "%");

        $("#power1").on("click", function() {

        $("#reset").on("click", function() {


        //PROBE DROID
        $("#enemy1").on("click", function() {
          document.getElementById("enemy1").style.opacity = "0";
          document.getElementById("bottom-col").style.opacity = "0";  
          attacking = 1;
          enemyLoaded = 1;
          enemy1Health = 100;
        $("#enemy-image").html("<img class='enemypic' src='assets/images/probe.gif'>");
        document.getElementById("healthBar").style.width = "100%";
        $("#enemy2").on("click", function() {
         document.getElementById("enemy2").style.opacity = "0";
         document.getElementById("bottom-col").style.opacity = "0"; 
          attacking = 2;
          enemyLoaded = 1;
          enemy1Health = 100;
        $("#enemy-image").html("<img class='enemypic' src='assets/images/stormtrooper.gif'>");
        document.getElementById("healthBar").style.width = "100%";
        //AT-ST WALKER
        $("#enemy3").on("click", function() {
         document.getElementById("enemy3").style.opacity = "0";
         document.getElementById("bottom-col").style.opacity = "0"; 
          attacking = 3;
          enemyLoaded = 1;
          enemy1Health = 100;
        $("#enemy-image").html("<img class='enemypic' src='assets/images/at-st.gif'>");
        $("#enemy-name").html("<b>AT-ST Walker</b>");
        document.getElementById("healthBar").style.width = "100%";
        //BOBA FETT
        $("#enemy4").on("click", function() {
          document.getElementById("enemy4").style.opacity = "0";
          document.getElementById("bottom-col").style.opacity = "0"; 
          attacking = 4;
          enemyLoaded = 1;
          enemy1Health = 100;
        $("#enemy-image").html("<img class='enemypic' src='assets/images/boba-fett.gif'>");
        $("#enemy-name").html("<b>Boba Fett</b>");
        document.getElementById("healthBar").style.width = "100%";

Currency Convertor Using Math.js Javascript Library and

For this currency convertor to work we have to link the math.js Javascript library and pull the current currency conversion rates from

Using a text inbox you can generate almost and string of currency values. I have the decimal place set to 2 but you can change that to be more or less by changing the precision value in this line:

 var resultStr = math.format(math.eval(expr.value), {notation: 'fixed', precision: 2})
<!DOCTYPE html>
  <title>Currency Conversion</title>

  <script src=""></script>

    input {
      font-size: 11pt;
      font-family: Gotham, Verdana, Arial, Sans-Serif;
      color: #4d4d4d;
      max-width: 600px;

    h1 {
      font-size: 120%;

    input {
      padding: 5px;
      width: 400px;
    .lbl {
      font-size: 13px;

<p id="info">
  fetching currencies...
  <label class="lbl" for="expr">Enter an expression with currencies:</label><br>
  <label class="lbl" for="expr">EXAMPLE: 25 GBP + 5 EUR + 25 AUD in USD</label><br>
  <label class="lbl" for="expr">The above expression adds 25 British Pounds with 5 Euros and 25 Australian Dollars and outputs the amount in US Dollars.</label>
<div id="form" style="display: none;">
    <input id="expr" value="25 GBP + 5 EUR + 25 AUD in USD" /><br/>
  <p id="result"></p>

      .then(function (currencies) {
        document.getElementById('expr').oninput = evaluate;
        document.getElementById('form').style.display = '';
        document.getElementById('info').innerHTML = 'Available currencies: ' + currencies.join(', ');


  function fetchAndImportCurrencies () {
    // this calls for the actuall currency conversion rates from
    return fetch('')
        .then(function (response) {
          return response.json();
        }).then(function (data) {

          // import the currencies
          Object.keys(data.rates).forEach(function (currency) {
            math.createUnit(currency, math.unit(1 / data.rates[currency], data.base));

          // return an array with all available currencies
          return Object.keys(data.rates).concat(data.base);

  function evaluate () {
    var expr = document.getElementById('expr');
    var result = document.getElementById('result');

    try {
// precision: 2 gives 2 decimal places.  
      var resultStr = math.format(math.eval(expr.value), {notation: 'fixed', precision: 2})
      result.innerHTML = '<span style="color: dodgerblue;">' + resultStr + '</span>';
    catch (err) {
      result.innerHTML = '<span style="color: red;">' + err.toString() + '</span>';

Setup a MacBook Java Development Environment

As we’ve become more mobile it’s important to enable our travel work stations to handle a multitude of development environments. Most developers will want to setup a Java SE development kit on their laptop. This is a step-by-step walkthrough outlining the elements necessary to develop Java applications on your iMac, MacBook, or any OS X device.

Step 1 : Install Java Development Kit (JDK)

Java SE Development Kit 8
Download the MAC OS X installation file jdk-Bu121-macosx-x64.dmg (233 MB).

java development kit installation

Step 2 : Setup JAVA_HOME Environment Variable

If you’ve never setup a bash profile open up Terminal and enter:
cd ~/

This will take you to the root directory. Then type:
touch .bash_profile to create the new file.

I personally prefer to edit files in Terminal using Vim editor:
vim .bash_profile

When the editor opens, the file should be blank. Press V then I to activate editing and copy and paste the following line into the file:
export JAVA_HOME=$(/usr/libexec/java_home)

To exit the editor and save the document press ESC and then type a colon : ( shift + : ) which will bring up a colon : at the bottom of the file. Now type in wq! and hit ENTER. This will save the .bash_profile file with your new JAVA_HOME entry.

Lastly, type:
. .bash_profile
This will reload .bash_profile and update the function we just added.

To check our work type in:
source .bash_profile
This should display:

You can skip all of step 3 by installing Homebrew.
I recommend installing it as you will need it down the road to install other environments.
To install Homebrew via SSH type the following line into terminal:

/usr/bin/ruby -e "$(curl -fsSL"

Now that you have Homebrew installed you can install Apache Maven:
brew install maven

Check you have Maven installed by entering:
mvn -version

Now you can skip Step 3A and go to Step 3B.

Step 3A : Install Apache Maven

Go to Apache’s Website here: Apache Maven

Then download the source zip archive file found halfway down the page:
Apache Maven Install File

Step 3B : Setup Maven Symbolic Link

I recommend making a symbolic link to the Maven installation folder inside of an opt folder by entering the following:
First create the folder name “opt”
mkdir opt
Enter the opt folder:
cd opt
Create a folder named “maven”
mkdir maven
Now go back one folder:
cd ..
Lastly, make a symbolic link inside the maven folder by typing the following:
ln -s ~/apache-maven-3.5.0 ~/opt/maven

Then we will go into our .bach_profile file:
vim ~/.bash_profile

Add the following 3 lines into the file (after our previously added JAVA_HOME line).

export M2_HOME=/path/to/maven
export M2=$M2_HOME/bin
export PATH=$M2:$PATH

Remember to close the file using wq! to save changes.

Now type:
. .bash_profile
To initialize those changes.

Step 4 : Install GCC and GIT

There are a couple different ways to install Git and the GNU Compiler Collection GCC.
The easiest is to install Homebrew

brew install gcc
brew install git

Grab a brew because this is gonna take some time to install.

Step 5 : Install IntelliJ IDEA

A Java IDE (Integrated Development Environment) is a software application which enables you to easily write and debug Java programs. IntelliJ provides features like syntax highlighting and code completion. Some popular ones include Eclipse, NetBeans, ItelliJ IDEA, JDeveloper and Android Studio.

I’m going to have you install IntelliJ IDEA (418 MB) from their download page

After the zip file has downloaded, unzip it and drag the file into your Application folder.

You are now technically done! Launch IntelliJ and start developing the next big application.

Here are some extras you can install to add more features to your JAVA development environment.

NodeJS – Download Page
I’m brave so I installed the latest version 7.9.0 but you can choose to install the most stable version 6.10.2 if you feel that suits you better. The difference between the stable and latest version is you may experience issues with the latest version that are due to its current code.

Linked List Example

Here is the code structure for the linked list:

class linked_list {
    linked_list(void);     // Constructor
    ~linked_list(void);    // Destructor

    void print(void);      // Prints Entire List
    void insert(int item); // Insert Function
    void remove(int item); // Remove Function
    bool search(int item); // Search Function
    linkedNode *first;     // Pointer to first node

class linkedNode {
    int data;            // Data held by this node
    linkedNode *next;    // Pointer to next node

What Exactly IS a Relational Database Management System RDBMS

IBM doesn’t just make hardware. They also have laboratories like mad scientists. It was in their San Jose Research Laboratory that Edgar Frank Codd developed the DBMS (database management system) relational model. RDBMSs still encase the backbone of most systems worldwide, even with the introduction of object-oriented database management systems or OODBMS …seriously not every computer term needs an acronym.

MySQL by Oracle Corporation is still deployed on 50% of database backed sites according to Gartner. Because it’s open source (free!) it is typically the introductory database most developers come across. The other big giants are Microsoft’s SQL Server and Oracle Database. Structured Query Language (SQL) is a specific language used to insert, query, update, and delete data inside the database.

Here’s the basic structure of an SQL Statement:
SQL example statement

Working with MongoDB

Advantages of MongoDB over RDBMS (relational database management system).

Schema less − MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another.
Structure of a single object is clear.
No complex joins.
Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that’s nearly as powerful as SQL.
Ease of scale-out − MongoDB is easy to scale.
Conversion/mapping of application objects to database objects not needed.
Uses internal memory for storing the (windowed) working set, enabling faster access of data.

Why Use MongoDB?

Document Oriented Storage − Data is stored in the form of JSON style documents.
Index on any attribute
Replication and high availability
Rich queries
Fast in-place updates
Professional support by MongoDB

Where to Use MongoDB?

Big Data
Content Management and Delivery
Mobile and Social Infrastructure
User Data Management
Data Hub

Here is an example of a MongoDB query. As you can see, you call out an item and then fields can be whatever you want them to. Unlike MySQL there is complete freedom over item values.

   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }

Java String Q&A

I’ve made a list of some common Java String questions I receive starting from extremely basic to more advanced questions.

What is String in Java?

String is a Class in java and defined in java.lang package. It’s not a primitive data type like int and long. String class represents character Strings. String is used in almost every Java application.

String str = new String("abc");
String str1 = "abc";

Further Use:
Here is an example method that will remove a given character from a String.

 private static String removeChar(String str, char c) {
        if (str == null)
            return null;
        return str.replaceAll(Character.toString(c), "");

Why using Char array for password storage is better than using String?

String is immutable in java and stored in String pool. Once it’s created it stays in the pool until garbage is collected, so even when we’re finished with a password it is still available in memory, and we don’t want that. This means anyone with access to the memory dump will have access to it, a big security no no.

So, by using char array for password storage, we can set it to blank once we are done with it. Also we can control how long it’s available in memory thus avoiding the security threat.

How do you check if two Java Strings are equal?

There are two ways to check if two Strings are equal or not – using “==” operator or using equals method. When we use “==” operator, it checks for value of String as well as reference but in our programming, most of the time we are checking equality of String for value only. So we should use equals method to check if two Strings are equal or not.
There is another function equalsIgnoreCase that we can use to ignore case.

String s1 = "sethcodes";
String s2 = "sethcodes";
String s3 = new String("sethcodes");
System.out.println("s1 == s2 ? "+(s1==s2)); //true
System.out.println("s1 == s3 ? "+(s1==s3)); //false
System.out.println("s1 equals s3 ? "+(s1.equals(s3))); //true

What does the String intern() method do?

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
This method always return a String that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

Java Connect to Remote Database through SSH using Port Forwarding

There may be a time when you need to connect to a remote database using an SSH connection. Here is an example of using port forwarding to connect remotely. This example is for MySQL but you can use it for almost any database.

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.sql.Connection;
public class MySqlConnOverSSH {
    public static void main(String[] args) throws SQLException {
        int lport=5656;
        String rhost="";
        String host="";
        int rport=3306;
        String user="sshuser";
        String password="sshpassword";
        String dbuserName = "mysql";
        String dbpassword = "mysql123";
        String url = "jdbc:mysql://localhost:"+lport+"/mydb";
        String driverName="com.mysql.jdbc.Driver";
        Connection conn = null;
        Session session= null;
            //Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
            java.util.Properties config = new java.util.Properties(); 
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();
            session=jsch.getSession(user, host, 22);
            int assinged_port=session.setPortForwardingL(lport, rhost, rport);
            System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
            System.out.println("Port Forwarded");
            //mysql database connectivity
            conn = DriverManager.getConnection (url, dbuserName, dbpassword);
            System.out.println ("Database connection established");
        }catch(Exception e){
            if(conn != null && !conn.isClosed()){
                System.out.println("Closing Database Connection");
            if(session !=null && session.isConnected()){
                System.out.println("Closing SSH Connection");

Write to MySQL Database Using Java

Probably one of the most common tasks you’ll ever utilize is writing to a database. Java INSERT is a very basic code snippet. This code inserts a first and last name into the table.

create table users (
  id int unsigned auto_increment not null,
  first_name varchar(32) not null,
  last_name varchar(32) not null,
  date_created timestamp default now(),
  is_admin boolean,
  num_points int,
  primary key (id)

Just for your reference here is another way to write to a MySQL database using JavaScript. Note: I’ve got the database host set to “localhost” since we are executing the script on the same server. The username is set to “root”.

This script will be inserting a first name, last name, and date created etc. I created a Prepared Statement to capture all the values before executing the write.

import java.sql.*;
import java.util.Calendar;

public class JavaMysqlPreparedStatementInsertExample

  public static void main(String[] args)
      // create a mysql database connection
      String myDriver = "";
      String myUrl = "jdbc:mysql://localhost/test";
      Connection conn = DriverManager.getConnection(myUrl, "root", "");
      // create a sql date object so we can use it in our INSERT statement
      Calendar calendar = Calendar.getInstance();
      java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());

      // the mysql insert statement
      String query = " insert into users (first_name, last_name, date_created, is_admin, num_points)"
        + " values (?, ?, ?, ?, ?)";

      // create the mysql insert preparedstatement
      PreparedStatement preparedStmt = conn.prepareStatement(query);
      preparedStmt.setString (1, "Barney");
      preparedStmt.setString (2, "Rubble");
      preparedStmt.setDate   (3, startDate);
      preparedStmt.setBoolean(4, false);
      preparedStmt.setInt    (5, 5000);

      // execute the preparedstatement
    catch (Exception e)
      System.err.println("Got an exception!");

Now that you’ve written to the database you can query it using the following script:

select * from users;

The output should resemble this:

| id | first_name | last_name | date_created        | is_admin | num_points |
|  1 | Barney     | Rubble    | 2010-06-23 14:02:00 |        0 |       5000 | 
1 row in set (0.00 sec)