Java

The Java Language

  • Compiled language
    • Source code is saved to .java text files which are then compiled into binary .class files
  • Strongly typed language
    • All variables must be declared and have a defined type. When passing values as arguments, the types must match or otherwise be converted.
  • All code must reside in classes
    • All functions/methods must be members of a class. Each project/app must have at least one class.
  • Libraries
    • Platform API and other libraries are added to the projects build/class path. Classes to be used from those libraries are referenced in Java code with import statements.

Hello world

  • Console application
    public class MyMainClass {
      public static void main(String[] args) {
        System.out.println("Hello, world!");
      }
    }
    
  • main
    • Entry point of a console application is the first static member function named main (class can have any name you want). Other platforms based on Java will have other entry points.
  • System.out
    • System.out is the standard output stream. Anything written to this stream will be displayed in the console when the application is run (or shown in the console window pane of Eclipse).

Variables

  • Declare and assign values
    int kilometers = 45;
    double speed = 6.45;
    double time = kilometers/speed;
    String name = "Alice";
    String text = name + " is my name";
    
  • Convert between types
    String text1 = "45";
    int num1 = Integer.parseInt(text1);
    String text2 = Integer.toString(num1);
    int num2 = Integer.valueOf(text2);
    String text3 = String.valueOf(num2);
    

Boxing

  • Java differentiates between
    • Primitive types like int and double
    • Class types like Integer, Double and String
  • Primitive types are very fast
    • No object overhead
    • Can't call methods on them
  • Class types are always objects with methods
  • Boxing
    • Java can automatically wrap a primitive type into its corresponding class type when calling methods etc. This is called autoboxing.

Formatting numbers in a String

  • Build a string from text and numbers with formatting
  • Java follows the C/C++ formatting placeholders and codes of the printf function
    • Placeholders start with %
    • Placeholder character must match value type
      • %d for whole numbers (int)
      • %x for whole numbers (int) in hexadecimal system
      • %f for floating point numbers (float and double)
      • %s for strings
    • Codes between % and type character can specify options
  • Example
    double fraction = 2.0/3.0;
    int whole = 123;
    String msg = String.format("One value is %.2f and the other is %d", 
      fraction, whole);
    

Selection

  • if-else-statement
    if (age>=35 && age<55)
      log.i("Alice is middle aged");
    if (name.equals("Bob"))
      log.i("You are Bob!");
    else
      log.i("You are someone else!");
    
  • Conditional operator
    Boolean isRetired = age >= 65;
    String desc = age < 18 ? "Young" : "Adult";
    

Iteration

  • while-statement
    int pos = 0;
    while (name[pos]!=" ") {
      pos++;
    }
    
  • for-statement
    for (int pos = 0; pos<name.length; pos++) {
    }
    

Methods

  • A sequence of statements to execute when called
  • Arguments can be used to customize each call
  • Methods can return a single value
    • void means that no value is returned
  • Example
    public float calcSpeed(float kilometers, float seconds) {
      float km_per_hour = kilometers / (seconds/3600);
      return km_per_hour;
    }
    

Classes

  • A collection of data and methods called members
  • A member can be
    • public - all code can access it
    • internal - only code inside the same package can access it
    • protected - only derived classes' code can access it
    • private - only the class itself can access it
    • If nothing else is specified, internal is the default
  • Construction
    • A special method without return type is called a constructor
    • Automatically called when new objects of the class are created

Classes Example

  • Definition
    class MyClass extends BaseClass {
      private int _count;
      public MyClass() {
        _count = 0;
      }
      public void doSomething() {
        _count++;
      }
      public int getCount() {
        return _count;
      }
    }
    
  • Usage
    MyClass obj = new MyClass();
    obj.doSomething();
    System.out.println("The count is " + obj.getCount());
    

Arrays

  • Declare and allocate
    String[] names = new String[5];
    names[0] = "Alice";
    names[1] = "Bob";
    
  • Declare and initialize
    int[] values = new int[] { 1, 2, 3, 5, 8, 13, 21 };
    

Generics

  • Single class can handle many different types
  • Dynamic arrays
    ArrayList<String> names = new ArrayList<String>();
    names.add("Alice");
    names.add("Bob");
    

Dictionary

  • Map keys to values
    HashMap<String, int> map = new HashMap<String, int>();
    map.put("Alice", 45);
    map.put("Bob", 100);
    

Exceptions

  • Exceptions are thrown by code or the runtime when errors occur
    • Exceptions can be caught by your own code in a try/catch-block
    • Exceptions declared on a method must be caught
  • Several different exceptions can be caught in the same try/catch-block
  • Example
    try {
      FileStream file = new FileStream("testfile.txt");
      file.close();
    }
    catch (IOException error) {
      System.out.println("Error in Input/Output: " + error.getMessage());
    }
    catch (Exception error) {
      System.out.println("Some other error: " + error.getMessage());
    }