Image goes here
Java
CptS 355 - Programming Language Design
Washington State University

Java Features

  • object-oriented, imperative
  • C/C++-like (C++ ++ --)
  • safe, robust, multithreaded, architecture independent: a major goal was to be able to distribute compiled code over the world-wide-web, but this has been less successful than Java's creators hoped.
  • no pointers (only implicit references)
  • no undefined or architecture dependent features: this is very important if code is to run on many different kinds of computers and the language is to be implemented by many different groups. For example, a Java int is always 32-bit two's complement. In C, the meaning of int depends on the implementation: it might be 8, 16, 32, or 64 bits.
  • static scoping, static typing, C-like precedence and associativity, short circuit evaluation: you will find Java's low-level syntax quite familiar after C.
  • no operator overloading (but does have method overloading),
  • eager (left to right) evaluation of parameters,
  • strongly typed, hybrid implementation with a virtual machine,
  • run-time memory mangament: explicit allocation and implicit deallocation (garbage collection)
  • heap-dynamic objects (only), reference types (all objects), no dangling pointers, no memory leaks.

The Java Virtual Machine (JVM)

A Java source program (e.g., Foo.java) is compiled to a class file (Foo.class) containing machine instructions called byte codes for the Java Virtual Machine. Compilation is performed by the javac program -- the Java compiler. Class files are (supposed to be) portable across different implementations of the JVM. To run a class file use the java program to start the JVM executing your class file.

There are different implementations of JVM for different computer architectures and operating systems. Different implementors of JVMs have different goals for performance as well.

The advantages of compiling code for the JVM instead of native code for a particular computer include:

  • The JVM has much more safety checking at the byte-code level than most hardware architectures have for their machine instructions. This is important if you are going to accept code sent to you over the net.
  • Byte-codes may be more compact than machine code for some kinds of hardware (especially so-called RISC hardware).
  • The class file design supports dynamic loading and linking of code which was a much bigger deal when Java was created than it is now when many of these ideas are common in so-called dynamic libraries for C and C++.
The primary disadvantage of byte-codes is that the JVM must execute several machine instructions to interpret each byte-code instruction. However, techniques such as just-in-time compilation (JIT) have been developed that allow the JVM to translate byte-code to native code and save it for re-use. Much effort has gone into JIT technology over the last 10 years.

Java's approach, using JVM, can also be contrasted to the Python approach which also uses byte codes. Unlike Java, Python does not separate the compiler and virtual machine into separate programs: there is just the python command. Python translates python source code files to byte code and then executes what it has just compiled. It also may save a copy of the compiled code for Foo.py in file Foo.pyc to save itself the trouble of recompiling. But this is just an optimization. There is no attempt in Python to make the compiled files portable between implementations or to ensure that it is safe to accept a compiled file that you got from someone else.

C/C++ features not in Java and what to do instead

  • structures: use objects. Objects are not required to have methods--they can also just package together data.
  • unions: there are two cases. If the union is really a union of high-level types, for example to allow a container to hold objects of different types, you can use objects with a common superclass. If the C union is being used to let you look at bit patterns of data of one type as if it were another type there is no way to do it easily in Java. In general such code is unsafe.
  • functions: use static methods of a class
  • function pointer parameters: use object parameters
  • multiple inheritance: for multiple subtyping use Java interfaces which resemble classes without any associated implementation. Because there is no implementation the difficulties that arise with multiple inheritance are avoided.
  • operator overloading: can't do it
  • pointers: Java objects and arrays are always represented by references which are pointer-like in some ways but do not support pointer arithmetic (which would be unsafe). There is no way to create pointers to values of base types like int, char, boolean, float.

Hello World

import java.io.*
// Helloworld.java
//   compile using 'javac Helloworld.java'
// This is a hello world example!
class HelloWorld {   
  // The main method prints "hello world"
  //   args are command line args
  public static void main (String args[]) {
    // I/O is done using streams
    System.out.println("Hello World!");
    return;  // optional
  }
}
Note that every program must have at least one class. By default the main method is called when Java first runs. main must be static and public. "static" means it stays with the class (not an object method, but a class method). static methods can be invoked using a class qualification, e.g., the following calls the main method in the Helloworld class.
   Helloworld.main()
By convention, the class Helloworld must be in the file Helloworld.java.

Compiling and Running Java

Java code is complied into JVM (Java Virtual Machine) code by the Java compilier (javac).
   javac Helloworld.java
will produce Helloworld.class. If Helloworld.java imports another class, that class will be automatically compiled as well. Standard libraries are automatically imported (and are precompiled). In the above program, java.io.* is a standard library. To run the resulting program, start the JVM on the class containing the main method, e.g.,
   java Helloworld
will start with main in the Helloworld class.

Comments

Two varieties
 // I am one line comment
 /* I am a 
       multi-line comment
 */

Classes

  • a class is a prototype
  • typical example
  • public class Name {
      public int method1(arg_type arg, ...) { }
      public static int method2(arg_type arg, ...) { }
      ...
    }
    
  • static methods remain with class

Javadoc

Javadoc is the Java API Documentation system. It can produce HTML output of the documentation in your program.
/**
* TauZamanSystem is the entrance point for 
* TauZaman services. It contains methods, which provide
* services to interact with further Calendar related 
* services. It contains all repositories, which will be 
* used as database for all services.
*
* @author Curtis Dyreson and Bedirhan Urgun
* @version 0.1 03/03/02
* @see tauzaman.calendricsystem.CalendricSystemRepository
* @see tauzaman.calendar.CalendarRepository
* @see tauzaman.field.FVSupportRepository
* @see tauzaman.property.PropertyRepository
* @status design complete, implementation complete
*/
public class TauZaman {

  /**
  * Create a determinate granule at the default Granularity
  * @param p - count of granules
  *
  * @throws TauZamanException if any abnormal condition occurs 
  * when setting this Granule's default Granularity
  **/ 
  public Granule createGranule(TimeValue p) 
         throws TauZamanException {
      ....
  }

Data Types

  • similar to C
     short   16-bit two's complement   Short integer
     int     32-bit two's complement   Integer
     long    64-bit two's complement   Long integer
     float   32-bit IEEE 754           Single-precision floating point
     double  64-bit IEEE 754           Double-precision floating point
     char    16-bit Unicode character  A single character
     boolean true or false             A boolean value (true or false)
  • reference types - Strings, arrays, classes, interfaces
  • no pointers, struct, or unions

Variable Declarations

  • similar to C: type name
      int i;
      String s;     // a string is an object
      float x, j;
    
  • initialization similiar to C
      int i = 3;
    
  • scope is within declaring block

Java Operators

C-like
This table summarizes Java's binary arithmetic operations: 

  Operator    Use        Description
    +     op1 + op2     Adds op1 and op2
    -     op1 - op2     Subtracts op2 from op1
    *     op1 * op2     Multiplies op1 and op2
    /     op1 / op2     Divides op1 by op2
    %     op1 % op2     Computes the remainder of dividing 
                         op1 by op2

Flow of Control

C-like
  if (x == 34) {... } else {...}

  for (i = 0; i < length; i++) {...}

  switch (month) {
    case 1:  System.out.println("January"); break;
    ...
    default: ....
    }

  while (x != 23) {...};

Arrays

Arrays are objects
   int[] arrayOfInts = new int[10]

   for (int j = 0; j < arrayOfInts.length; j ++) {
     arrayOfInts[j] = j;
     System.out.println("[j] = " + arrayOfInts[j]);
     }

Strings

A string is an object.
  • String is immutable/StringBuffer is mutable
      String joe = new String("hello how are you");
      // Alternatively
      String joe = "hello how are you";
    
  • + is concatenation, automatic conversion
      count = 23;
      System.out.println("Input has " + count + " chars.");
    

I/O - output

import java.io.*;
class PersonalHello {
  public static void main (String args[])
    {
      byte name[] = new byte[100];
      int nr_read = 0;

      System.out.println("What is your name?");
      try {
        nr_read = System.in.read(name);
        System.out.print("Hello ");
        System.out.write(name,0,nr_read);
      }
      catch (IOException e) {
        System.out.print("I'm Sorry.  I didn't catch your name.");
      }
    }
}

I/O - input

  static int getNextInteger() {
  
    String line;
  
    DataInputStream in = new DataInputStream(System.in);
    try {
      line = in.readLine();
      int i = Integer.valueOf(line).intValue();
      return i;
    }
    catch (Exception e) {
      return -1;
    }
  } // getNextInteger ends here
(c) 2003 Curtis Dyreson, (c) 2004-2006 Carl H. Hauser           E-mail questions or comments to Prof. Carl Hauser