URL http://www.cs.hmc.edu/~keller/java_talk.html

C++ -> Java

(or is it C++ . Java?)

Robert Keller

12 September 1996

Language Distinctions

C++
Java
Designed to be architecture-neutral (and thus portable)
Multithreading support, if any, is through system calls Multithreading is part of language (Threads are objects)
Programmer-directed storage reclamation (delete command); Dangers: dangling pointers, space leaks Automatic storage reclamation (no delete); Removes the dangers
Security features: Stuff can be checked at run-time
package construct provides hierarchical name-space
Fully standardized arithmetic types (e.g. IEEE FP)
Boolean is overloaded intSeparate type boolean
Explicit pointers and explicit dereferencing References (= implicit pointers)
-> (as in ptr -> field) in C++ becomes. (as in obj.field) in Java
References cannot be reassignedReferences are routinely reassigned
Pointer arithmetic, pointer-array duality No pointer arithmetic or duality
Objects can be passed both by value and by reference Objects passed by reference only
Non-objects passed by value only. If you want to change an argument, it must be packaged as an object.
Copy constructor and assignment operatorsNo implicit object copying or assignment
One constructor can't call another in same classOne constructor can call another; constructor can call its super's constructor explicitly
this is pointer to this object (*this usage)this is reference to this object (no *)
DestructorsNo destructors (but finalizers)
Structs No Structs (redundant, use classes)
Unions No Unions (achieve by inheritance)
Bitfield constructNo Bitfields
typedef constructNo typedefs
Function prototypes (e.g. for forward defs)No function prototypes
const variablesNo const
EnumsNo Enums (achieve by final int)
Implicit castingNo implicit down-casting; some implicit up-casting
Functions may be passed as pointersNo functions; Methods cannot be passed (use object hack)
Arrays can be allocated automatically All arrays allocated explicitly (using new)
No built-in array bounds checking Built-in array bounds checking
Exceptions implemented laterExceptions integral to language philosphy
Exceptions are objects
go to allowedNo go to (but adds labeled breakcontinue)
Multiple inheritance allowedNo multiple inheritance
Idiomatic interface inheritance interface is part of language
Pure virtual functions (methods), implicit abstract classesExplicit abstract classes and methods
No universal base classAll classes inherit from class Object
Static polymorphism allows compile-time checkingDynamic polymorphism is inherent
Casting to a relative base class loses identity of derived classCasting to a relative base class retains full identity
Preprocessor available (#define, etc.) No preprocessor
#include header filesno header files; Import packages
Operator overloading encouragedNo operator overloading (but methods can be overloaded)
Templates (parameterized types)No templates
Global variablesStatic variables within classes
Methods and FunctionsMethods and static methods (no functions)
Program invoked as main procedureProgram invoked as a static method
One main for entire programEvery class can have a main
Arguments to main optionalArguments to main always declared
char* strings availableStrings are objects
Unicode characters (16-bit, international)
varargs construct (hack) allowedNo varargs
>>> 0-fill right-shift operator
New modifiers: final, abstract, native, synchronized, transient, volatile


Status quo Distinctions

C++
Java
C++ typically compiledJava designed to run on virtual machine; On-the-fly compilers being introduced
Full portability not realized yet
Highly-developed stream i/o classesRelatively primitive stream i/o classes
No particular windowing classHighly-developed windowing class
HTML integration (Applets), downloadable byte-code
Networking library, URL's, etc.
Outside access to instance variables discouragedAccess to instance variables common (can be confusing)


Hello World Program

Source file: HelloWorld.java

	class HelloWorld 
	{
	  static public void main(String args[]) 
	  {
	  System.out.println("Hello world!");
	  }
	}
Glossary:

Compiling:

        javac HelloWorld.java

Running:

        java HelloWorld


Hello World Applet

Source file: HelloWorldApplet.java

	import java.applet.Applet;
	import java.awt.Graphics;

	public class HelloWorldApplet extends Applet 
	{
	  public void paint(Graphics g) 
	  {
	  g.drawString("Hello world!", 200, 90);
	  }
	}
Note: An applet does not have a programmer-defined main. Instead, it relies on the underlying code to call select methods such as paint.

Glossary:

Source file: HelloWorldApplet.html

        < applet code = HelloWorldApplet.class width=500 height=200 >  < applet >

Compiling:

        javac HelloWorldApplet.java

Running:

        appletviewer HelloWorldApplet.html
or see it run here:


The following example shows off the awt mouse-handling.

EZdraw Example

Here is the source. Note that methods of the derived class over-ride those in class Applet.

Here is the list of methods, generated by javadoc.


Threads

Towers of Hanoi Example

Start method of the applet:

  public class Hanoi extends Applet implements Runnable
    {
    .
    .
    .
  public void start() 
    {
    if( mythread == null )
      {
      mythread = new Thread(this);
      mythread.start();
      }
    else
      mythread.resume();
    }

  public void stop() 
    {
    mythread.suspend();
    }

    .
    .
    .
    }

Calling start on the newly-created mythread will call the run method of the applet, which is essentially a loop with moves interspersed with calls to sleep.

The currently-called start method will return to the browser.

Calling stop (when the browser goes to a different page) will suspend the thread until the browser re-enters this page.

Here is the complete source.


Exceptions

  Hanoi Move(int i, int j)
    {
    try
      {
      spindle[j].add(spindle[i].remove());
      }
    catch(EmptyStackException e)	// assert will not occur
      {
      }
    spindle[i].draw();
    spindle[j].draw();
    return this;
    }

If a method doesn't catch an exception which can be thrown by another method it calls, then the former method must declare that it throws the exception. The compiler will not simply let this pass.


Some Web References


Some Other Applets


Book References