Recent Changes - Search:

Network Programming

This website demonstrates using wikis as teaching and learning tool.

The course instructor is happy to share the teaching materials here with those who find it readable.

Introduction to Java Programming

A Network Programming Lecture by Steven Choy

Lecture Overview: The Java Virtual machine - Different editions of Java - Install Java SE Development Kit (JDK) - A Simple Java Program - Primitive Data Types - Program Flow Controls - Object-oriented programming with Java


The Java virtual machine (JVM)

  • The JVM provides a sandbox environment in which the program is executed.
  • "write once, run everywhere"
(Java bytecode can be executed on any platform with a Java virtual machine)
  • The JVM is also responsible for loading other ready-made components, called class libraries, as required by the program
(A functional block diagram of JVM)

Different editions of Java

Java is split into three different editions, each targeting a different platform:

  • Java Platform, Standard Edition (Java SE)
It includes the tools necessary to develop Java applications for desktop platforms.
  • Java Platform, Enterprise Edition (Java EE)
It includes the tools necessary to develop robust, secure and scalable middleware applications for enterprises.
  • Java Platform, Micro Edition (Java ME)
It includes the tools necessary to develop Java applications on portable or embedded devices such as mobile phones. A special version of virtual machine has been developed for Java ME due to restrictions usually found on the target platforms.

Install Java SE Development Kit (JDK)

  • Before doing Java programming, you need to have the necessary tools downloaded and installed on your computer.
  • Download Java SE Development Kit (JDK) from http://www.oracle.com/technetwork/java/javase/downloads/index.html
  • Follow the installation instructions
  • Assuming that the base directory of your installation is C:\Program Files\java\jdk1.6.0_10
  • You will find the following tools inside C:\Program Files\java\jdk1.6.0_10\bin:
    • javac – the Java compiler
    • java – the Java runtime, or Java virtual machine (JVM), for running Java applications
  • You may want to include the path C:\Program Files\java\jdk1.6.0_06\bin@ into the PATH environment variable.

A simple Java program

Reference: "Hello World!" for Microsoft Windows (The Java™ Tutorials > Getting Started > The "Hello World!" Application)

/**
 * Hello World Demo
 */

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
  • Use Notepad or any other plain editor (such as Notepad2), enter the above program and save it as HelloWorld.java in a folder, say, c:\temp.
  • Note that the file name must be identical (case-sensitive) to the class defined in the source code.
  • In a Command prompt, change to that directory and compile the source:
      C:\>c:
      C:\>cd temp
      C:\temp>javac HelloWorld.java
  • The compiled program is stored in a class file called HelloWorld.class. To execute the program:
      C:\temp>java HelloWorld
  • It is essential that you do not enter the .class extension.
  • If for some reason java is unable to locate the HelloWorld class, tell it to look for it in the current directory.
      C:\temp>java –classpath . HelloWorld
  • The following message is displayed on screen when the program is executed:
      Hello World

Primitive data types

  • byte - 1 byte : -128 to 127
  • short - 2 bytes : -32,768 to 32,767
  • int - 4 bytes : -2,147,483,648 to 2,147,483,647
  • long - 8 bytes : -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
  • float - 4 bytes : 4.94065645841246544e-324d to 1.79769313486231570e+308d (+/-)
  • double - 8 bytes : 1.40129846432481707e-45 to 3.40282346638528860e+38 (+/-)
  • char - 2 bytes, 0 to 65535 (Unicode)
  • boolean - ture or false

Program flow controls

  • Decision making – if and switch
    if (boolean expression)
      statement or block of statements
    else
      statement or block of statements

    switch (integer expression) {
        case integer expression:
             statement or block of statements
             break;
        ...
        default:
             statement or block of statements
             break;
    }
  • Examples:
      // The if-then Statement 
      if (isMoving) {
        currentSpeed--;
      }

      // The if-then-else Statement
      if (isMoving) {
        currentSpeed--;
      } else {
        System.err.println("The bicycle has already stopped!");
      }

      // The switch Statement
      switch (month) {
        case 1:  System.out.println("January"); break;
        case 2:  System.out.println("February"); break;
        case 3:  System.out.println("March"); break;
        case 4:  System.out.println("April"); break;
        case 5:  System.out.println("May"); break;
        case 6:  System.out.println("June"); break;
        case 7:  System.out.println("July"); break;
        case 8:  System.out.println("August"); break;
        case 9:  System.out.println("September"); break;
        case 10: System.out.println("October"); break;
        case 11: System.out.println("November"); break;
        case 12: System.out.println("December"); break;
        default: System.out.println("Invalid month.");break;
      }
  • Looping – do-while, while, for and for-each loops
    do {
      statement or block of statements
    } while (boolean expression);

    while (boolean expression) {
      statement or block of statements
    }

    for (initialization; boolean expression; step) {
      statement or block of statements
    }

    for (type variable : array or collection) {
      statement or block of statements
    }
  • Examples:
        // The do-while Statement
        int count = 1;
        do {
          System.out.println("Count is: " + count);
          count++;
        } while (count <= 11);

        // The while and do-while Statements
        int count = 1;
        while (count < 11) {
          System.out.println("Count is: " + count);
          count++;
        }

        // The for Statement
        for(int i=1; i<11; i++){
          System.out.println("Count is: " + i);
        }
The for-each loop, also called enhanced for loop, is a new addition to the flow controls since Java 5. It provides a convenient way to iterate through the elements of an array or a collection. For example, the following code calculates the total of integers in an array:
        int[] arr = { 12, 4, 23, 5 };
        int total = 0;
        for (int i : arr) {
          total += i;
        }
        System.out.println("Total = " + total);

Object-oriented programming with Java


Java and Network Programming

We will use Java as one of programming languages to write network programs.
We will learn more about Java programming in the course of studying network programming.
So, don't worry if you can't understand all the topics about Java programming.
Some basic topics that are important to you are:
  • What is an object?
  • What is a class?
  • What is an interface?
  • How to declare classes
    • Declare member variables
    • Declare methods
    • What is class constructors?
  • How to create and use objects?
  • How to define an interface?
  • How to implement an interface?

An Example Java Network Program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class Post2WebTest {

    public static void main(String[] args) {
        String postUrl = "";
        String postData = "";

        try {
            URL url = new URL(postUrl);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            //conn.setRequestProperty("Referer", "");

            // write POST data to server
            OutputStream output = conn.getOutputStream();
            output.write(postData.getBytes());
            output.close();
            // read response from server
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null)
                System.out.println(line);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Homework for you

Readings: The Java Tutorial (http://download.oracle.com/javase/tutorial/)

  • Homework 1 - Go to The Java Tutorial. Choose the trail Getting Started – lesson The “Hello World!” Application. Read the part “Hello World!” for Microsoft Windows.
  • Homework 2 - Go to The Java Tutorial. Read the lessons A Closer Look at the "Hello World!" Application and Common Problems (and Their Solutions) under the trail Getting Started.
  • Homework 3 - Go to The Java Tutorial. Choose the trail Learning the Java Language and study the lesson Language Basics.
  • Homework 4 - Go to The Java Tutorial. Choose the trail Learning the Java Language. Then study the sections Object Oriented Programming Concepts and Classes and Objects.
This online reading contains a fair amount of material. Prepare to spend an additional four hours on the examples and exercises. Note that the reading covers some concepts that will be discussed again later. Use the reading as a preparation for this.

Thanks for Reading

If you would rather like to have this lecture note in printed format, please click the print action link in the top right corner.

If you find any problem in this lecture note, please feel free to tell Steven via steven@findaway.hk.

Edit - History - Print - Recent Changes - Search
Page last modified on October 03, 2011, at 09:10 AM