Skip to main content
Logo image

Section C.16 J1: Intro to Java

Synopsis.

  • Start with comparison of C and Java.
    C Java
    struct class
    container object
    function method
    pointer reference
    malloc new
    free garbage collection (no leaks, no dangling pointers)
    unsigned
    undefined behavior
    sanitizer totalized semantics
  • Outline basic compilation process. .java \(\to\) .class \(\to\) JVM
  • Overview over Types. Base types vs reference types.
    • Cannot take address of base type variables, cannot allocate them on the heap, lifetime determined by scopes.
    • No * and &.
    • Reference types are classes and arrays.
    • Allocated with new, life time governed by garbage collection.
    • A reference either contains “null” or references a live object.
  • Intro arrays.
    • Array contains elements and length.
    • You can query the length with “.length”.
    • Cannot increase the length, use “ArrayList” for array lists.
    • No multi-dimensional arrays.
    • String is a class that consists of character array.
  • First simple example: HelloWorld, compile manually with “javac” and run with JVM “java”.
  • Switch to IDE. Start with “Vec2” example. Use C program to motivate classes.
    • Proper way of encapsulation in C: Header file with anonymous struct, set of functions, first parameter is always ptr to struct that represents data structure.
    • In Java, you have more syntactic sugar. You can put functions/methods inside the class, “this” is implicit first parameter: reference to object of class.
    • Objects need to be constructed: Introduce constructors, default constructors.
    • Add main method and run example.
    • Add “Rectangle” class. How does it interact with “Vec2”? Encapsulate fields using getters and setter. Motivation: Can change internal implementation of “Vec2” to polar coordinates.
  • Show that setters are also a good means of asserting class invariants (Fraction example, setDenominator).

Sections Covered.