CS 208 s21 — Java vs C

1 Video

Here is a video lecture for the material outlined below. It contains sections on

  1. High-level differences (0:27)
  2. Arrays (7:18)
  3. Strings (15:08)
  4. Objects (18:53)

The Panopto viewer has table of contents entries for these sections. Link to the Panopto viewer: https://carleton.hosted.panopto.com/Panopto/Pages/Viewer.aspx?id=cf036874-777f-4392-88a1-ac7001616dc4

2 Java vs C

  • integers, floats, doubles, pointers have the same representation as C
    • pointers are called references in Java, and are much more constrained
      • no pointer arithmetic, casting must obey subtyping rules, etc.
    • Java specification fixes the sizes of all types
      • e.g., long is 64 bits regardless of machine
  • Object-oriented language
    • can define new classes, use inheritence, Object versions of primitive types (e.g., double and Double)
  • Another layer between the language and the system as compared to C
    • Java compiles to machine code for the Java Virtual Machine (JVM)
    • The JVM fetches, interprets, and executes these instructions much like the CPU
    • The JVM is implemented in C++, so it's generating the x86-64 instructions to have the CPU execute the Java code

2.1 Arrays

  • Java initializes elements
  • Java arrays keep length in an immutable field (array.length)
    • immutable means the value cannot be changed (i.e., arrays have a fixed length)
  • every access triggers a bounds check
    • exception if access is out-of-bounds (a Java exception, not an OS exception)
  • will checking the array length as part of a loop be a big performance hit?
    • Length field is likely in cache
    • Compiler may store length field in register for loops
    • Compiler may prove that some checks are redundant
      • e.g., if the compiler can determine the loop variable is always within the array bound, it doesn't need to check those array accesses

java-c-array.png

2.2 Strings

  • Java uses two-byte Unicode instead of ASCII
    • can represent most of the world's alphabets
  • no null terminator
  • String objects are read-only
  • As befits an object-oriented language, a lot of string functionality is provided via String class methods rather than functions that take a string (as in the C library)

java-c-string.png

2.3 Objects

  • data structures always stored by reference, never inline

java-c-object.png

  • virtual method table (vtable) provides pointers to class methods
    • each instance stores a pointer to its vtable