Java for C++ Programmers

History/Motivation
Code Compilation and Execution
Program Structure
Class Libraries and Package
Java Basics and Arithmetic
Basic Input/Output
Keyboard input
Formatting output
Flow of control/Equality
User-Defined Classes
Reference Objects
Static variables and Methods
Arrays
Strings, characters and StringTokenizer
Inheritance
Packages
Polymorphism
Interfaces
Abstract Class
Exceptions
Classpath Variable
Serialization
Applets

History/Motivation
Code compilation and execution Compilation Program Structure
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}


Class libraries and packages
Java Basics and Arithmetic
BasicArithmetic.java

Basic Input/Ouput

Keyboard input
Formatting output NOTE: Prior to Java 1.5, programs used a BufferedReader to do I/O.  The BufferedReader class is no longer covered in these notes.

SalesTax.java


Flow of control
Equality tests

Comparison.java


User-Defined Classes
Visibility
Constructors, Accessors and Mutators
Methods
Methods Inherited from Object

Time.java and TimeTest.java


Reference Objects

public class PassByValue {
  public static void One(Point v) {
    v = new Point(0, 0);
   }

   public static void Two(Point v) {
   v.setX(5);
   }

public static void main(String[] args) {
  Point p = new Point(10, 10);
  System.out.println("Original point: " + p);

  One(p);
   System.out.println("Point after one: " + p);

   Two(p);
   System.out.println("Point after two: " + p);
   }
}


Exercise

Create a class named Person which has two fields, a String called name and an integer called age.  Include a default constructor, a 2-parameter constructor, accessors, modifiers, a toString and an equals method.

Create a second class named People which contains only the main function.  Create several Person objects and use the toString, equals, == and other methods to get a basic understanding of using classes in Java.


Static variables and methods
public class Logins { 
static private int numLogins = 0;

// constructor just updates static counter
public Logins() {
++numLogins; // another login has been performed
}

public static void main(String[] args) {
  Login l1 = new Login();
  Login l2 = new Login();
  Login l3 = new Login();

  System.out.println("Number of logins: " + Login.numLogins);
}
}

Conversion.java


Arrays
Person.java and Friends.java and TripPlanner.java

Strings and Characters
StringTokenizer

The StringTokenizer class is useful for parsing a string into individual words.

    // Sample String
    String s = "I am learning Java. Show me how to use StringTokenizer.";

    // StringTokenizer, pass string into constructor
    // Could pass delimiter as second parameter, if other than \t\n\r, delimiters discarded
    StringTokenizer st = new StringTokenizer(s);

    // Retrieve and display tokens
    System.out.println("The total number of words is " +  st.countTokens());

    // Use the StringToken iterators hasMoreTokens to see if more words
    while (st.hasMoreTokens())
      System.out.println(st.nextToken());  // nextToken will get the next word

    System.out.println("Any tokens left? " + st.countTokens());

Inheritance

Account.java, SavingsAccount.java and AccountDemo.java


Polymorphism

Polymorphism (having many forms)

Mammal pet;
Horse secretariat = new Horse();
pet = secretariat;


Exercise

Extend your Person class to be a Student with additional field of type double called GPA.  Include accessor and mutator for your new field.  Override toString and equals for your new class.

Write a new driver file to create an array of Person objects.  Write a loop to accept 5 people.  Each time through the loop, ask it the person is a student.  If so, add a Student object to the array, otherwise add a Person object to the array.  Accept the appropriate information, based on the type.  Then include another loop to print out the information in your array.


Interfaces
public interface Speaker

{
           public void Speak();
           public void announce (String str);
}

If Philosopher and Dog both implement Speaker, can do:

Speaker guest;
guest = new Philosopher();
guest.speak();
guest = new Dog();
guest.speak();

Shape.java and Point.java and InterfaceTest.java
Abstract Classes



Nested classes
Outer.java and TestOuter.java

Collections
ArrayTest.java
File I/O

Anonymous Inner Classes



Basic Input and Output in Java 1.5

Keyboard input

Formatting output


Exceptions

Abnormal events in a program, such as running past the end of an array or invalid characters encountered during an I/O operation, generate an event known as an exception.  The run-time system throws an exception based on the type of error (e.g., Null pointer exception, IO Exception, etc.).  The program will either catch and handle the exception or terminate with an error. 

Java requires that some potential errors must either be handled explicitly OR acknowledged via a throws expression.  In the first IO program below, the programmer has decided not to handle IO errors.  Notice the throws IOException clause at the end of the the main method.  If an error occurs during input (e.g., the user enters an invalid character), the program will abort).  Also, the throws clause is required for the creation of fileScan. In the second IO program, the IO statement is embedded in a try-catch clause.  The Java runtime will "try" the statement, and if an IO error occurs, the catch clause will take over and handle it, so the program will not need to abort. 

Some exceptions must be caught (e.g., the fileScan statement in program one).  These are known as checked exceptions.  Others do not need to be caught (e.g., the scan.nextInt statement in program one). These are known as unchecked exceptions.  Runtime exceptions such as divide by zero are generally unchecked, because the cost of implementing handlers for them could be too high.

import java.io.*;
import java.util.Scanner;

public class IOThrows {
    public static void main(String[] args) throws IOException
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter an integer: ");
        scan.nextInt(); // unchecked
       
        // requires throws clause or FileNotFound must be handled.
        Scanner fileScan = new Scanner( new File("myfile.txt"));
       
    }

}

import java.io.*;
import java.util.Scanner;

public class IOTryCatch {
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        try
        {
            scan.nextInt();
        }
        catch (java.util.InputMismatchException e)
        {
            System.err.println("Error in input, shame on you!");
        }
    }

}


Serialization

Serialization allows you to take the state of a Java object and write it in binary form to an output stream.  A second program can then create a new object with an equivalent state.

The Java java.io.Serializable interface is used to enable you to save the state of a class.  Serialization relies on class metadata and reflection to extract the state of an instance.  Data are written to the output stream in binary format. A serial number is assigned to each object.  If the same object is written to the output file more than once, only the serial number is written. 

public class Contact implements java.io.Serializable {
    String name;
    String email;

    public Contact() {
        name = "";
        email = "";
    }

    public Contact(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String toString() {
        return "Name: " + name + " Email: " + email;
    }
}

import java.io.*;

public class IOWriteDemo {
    public static void main(String[] args) {
        try {
            // Specify the file where you'll store the data
            FileOutputStream fos = new FileOutputStream("datafile");
            // Create an ObjectOutputStream
            ObjectOutputStream oos = new ObjectOutputStream(fos);
   
            Contact contact = new Contact("Cyndi Rader", "crader@mines.edu");
            // Serialize the object
            oos.writeObject(contact);
        }
        catch (IOException e)
        {
            System.out.println("Problem with file output");
        }
    }
}

import java.io.*;

public class IOReadDemo {
    public static void main(String[] args) {
        try {
            // Specify the file where you'll find the data
            FileInputStream fis = new FileInputStream("datafile");
            // Create an ObjectInputStream
            ObjectInputStream ois = new ObjectInputStream(fis);
   
            Object o = ois.readObject();
            System.out.println(o);
        }
        catch (IOException e)
        {
            System.out.println("Problem with file input");
        }
        catch (ClassNotFoundException e)
        {
            System.out.println("Problem with file input");
        }

    }
}



Applets Applet methods Applets and Components
Applets and Security

Packages

To create your own package, put a package statement at the top of your program:

package edu.crader.mypackage

A common practice is to use your domain name in reverse, with a unique ending to match the purpose of the package.

To compile the source code and have the compiler create the appropriate directory structure, use the -d . switch:

javac -d . myProgram.java

This will create the directory structure edu/crader/mypackage starting from the current directory (the . in the command).

To run the program, you must specify the complete pathname:

java edu/crader/mypackage/myProgram




Classpath

The classpath tells Java where to search for a package or class.  CLASSPATH is not a Java variable, it is an operating system variable.  Therefore, the way the CLASSPATH variable is set is operating system dependent.  Some examples:

Unix:
set CLASSPATH=/libraries/java;.
export CLASSPATH

XP:
Control Panel->System->Advanced->Environment Variables
Edit or Add Classpath

Note the . at the end of the classpath.  This is needed so that your classpath includes the current directory.  

You can override the CLASSPATH setting when you compile or run a program by using the -classpath switch on the command line, such as:
java -classpath . myProgram

which tells the java interpreter to run myProgram from the current directory.