Chapter preview

Chapter 5

Learning Java

The Java programming language is heavily used in big data applications like Apache Cassandra and Elasticsearch. In this chapter, we describe Java starting with compilation, types, operators, I/O, control flow, etc., and concluding with object-oriented programming and other features. We cover parallel programming using Java in Chap. 10.

Note: The examples below are abridged; the book contains more details.

  1. Compilation
  2. Types, Variables, and Scope
  3. Primitive and Non-Primitive Types
  4. Arrays
  5. Multidimensional Arrays
  6. Ragged Multidimensional Arrays
  7. Classpath
  8. Strings
  9. Functions
  10. Classes - Part I
  11. Classes - Part II
  12. Classes - Part III
  13. Inheritance
  14. Interfaces
  15. Generics
  16. ArrayList
  17. HashMap

Compilation

HelloWorld.java

public class HelloWorld { 
   public static void main(final String[] args) {
      System.out.println("Hello, World!");
   }
}

compilation.sh

# Compile HelloWorld.java (Java code) into byte code
javac HelloWorld.java  
# The byte code now resides in the file HelloWorld.class
# Execute byte code file in JVM using the java program 
# (omit .class suffix)  
java HelloWorld

Types, Variables, and Scope

public class UninitializedVariableExample {
  public static void main(final String[] args) {
    final int a = 3;
    final int b;
    final int c;

    System.out.println(a); // ok; prints 3
    b = 3;
    System.out.println(b); // ok; prints 3
    System.out.println(c); // error: c is not initialized
  }
}

Primitive and Non-Primitive Types

import java.util.Date;

public class DateExample {
  public static void main(final String[] args) {
    final Date date1 = new Date(); // define a new object date1
    final Date date2 = date1; // point date2 to date1
    
    // print both objects
    System.out.println(date1);
    System.out.println(date2);
    // Both objects date1 and date2 refer to the same memory 
    // Modifying date2 changes date1 as well
    date2.setTime(1);
    // print both objects
    System.out.println(date1);
    System.out.println(date2);
  }
}

Arrays

public class ArrayExample {
  public static void main(final String[] args) {
    final int n = 10;
    final int[] ar = new int[n];

    for (int i = 0; i < ar.length; i++) {
      ar[i] = i;
    }
    for (final int e : ar) {
      System.out.print(e + " ");
    }
  }
}

Multidimensional Arrays

public class MultidimensionalArrayExample {
  public static void main(final String[] args) {
    final int[][] ar = new int[10][10];

    for (int i = 0; i < ar.length; ++i) {
      for (int j = 0; j < ar[i].length; ++j) {
        ar[i][j] = i * 10 + j;
      }
    }

    for (int i = 0; i < ar.length; ++i) {
      for (int j = 0; j < ar[i].length; ++j) {
        System.out.print(ar[i][j] + " ");
      }
      System.out.print("\n");
    }
  }
}

Ragged Multidimensional Arrays

public class RaggedMultidimensionalArrayExample {
   public static void main(final String[] args) {
     final int[][] ar = new int[10][];

     for (int i = 0; i < ar.length; ++i) {
       ar[i] = new int[i + 1];
       for (int j = 0; j < ar[i].length; ++j) {
         ar[i][j] = i * 10 + j;
       }
     }

     for (int i = 0; i < ar.length; ++i) {
       for (int j = 0; j < ar[i].length; ++j) {
         System.out.print(ar[i][j] + " ");
       }
       System.out.print("\n");
     }
  }
}

Classpath

# modifying the class path in bash, using : as separator 
# (period corresponds to current directory)
export CLASSPATH=/home/joe/classes:/home/jane/classes:.

# alternatively, the class path can be passed as an 
# argument to java
java -cp /home/joe/classes:/home/jane/classes:. program.java

Strings

public class HelloWorld {
  public static void main(final String[] args) {
    final String greeting = "Hello";
    
    System.out.println(greeting);
    System.out.println(greeting.charAt(2));
    System.out.println(greeting.equals("Hello"));
    System.out.println(greeting.substring(0, 3) + "p");
   }
}

Functions

public class FunctionArgumentExample {
  private static void foo1(int a) {
    a = 1;
  }
  
  private static void foo2(final int[] arr) {
    arr[0] = 1;
  }

  public static void main(final String[] args) {
    final int a = 3;
    final int[] b = new int[1];

    System.out.println("primitive variable a before foo1: " + a);
    foo1(a);
    System.out.println("primitive variable a after foo1: " + a);
    b[0] = 3;
    System.out.println("b[0] before foo2: " + b[0]);
    foo2(b);
    System.out.println("b[0] after foo2: " + b[0]);
  }
}

Classes - Part I

class Point {
  private double x = 0;
  private double y = 0;

  public Point() {} // empty constructor

  public Point(final int x, final int y) {
    this.x = x;
    this.y = y;
  }

  public void setX(final double x) {
    this.x = x;
  }

  public void setY(final double y) {
    this.y = y;
  }

  public double getX() {
    return this.x;
  }

  public double getY() {
    return this.y;
  }

  public void reflect() {
    this.x = -this.x;
    this.y = -this.y;
  }

  public String toString() {
    return "(" + this.x + ", " + this.y + ")";
  }
}

public class PointExample {
  public static void main(final String[] args) {
    final Point p = new Point(1, 2);

    System.out.println(p);
    p.reflect();
    System.out.println(p);
  }
}

Classes - Part II

// { autofold
class Point {
  private double x = 0;
  private double y = 0;

  public Point() {} // empty constructor

  public Point(final int x, final int y) {
    this.x = x;
    this.y = y;
  }

  public void setX(final double x) {
    this.x = x;
  }

  public void setY(final double y) {
    this.y = y;
  }

  public double getX() {
    return this.x;
  }

  public double getY() {
    return this.y;
  }

  public void reflect() {
    this.x = -this.x;
    this.y = -this.y;
  }

  public String toString() {
    return "(" + this.x + ", " + this.y + ")";
  }
}
// }

public class PointExample2 {
  public static void main(final String[] args) {
    Point p1 = new Point(1, 2);
    Point p2 = p1;
    
    p2.reflect(); // p1 is also modified
    System.out.println(p1);
  }
}

Classes - Part III

class Point {
  private double x = 0; // initialization during field definition
  private double y;
  {
    y = 2;  // initialization block	
  }
}

Inheritance

class Parent { // superclass
  private int a;
  
  public Parent(final int a) {
    this.a = a;
  }
}

class Child extends Parent { // subclass
  private int b;
  
  public Child(final int a, final int b) {
    super(a); // call to constructor of class Parent
    this.b = b;
  }
}

public class InheritanceExample {
  public static void main(final String[] args) {
    // Define an object of class Parent
    final Parent a = new Parent(3);
    // Define an object of class Child
    final Child b = new Child(1, 3);
    // Polymorphism: a Parent object refers to a Child object
    final Parent c = b;
    final Child d;
    
    if (c instanceof Child) { // check if c points to class Child
      // Cast the object referred to by c to type Child
      d = (Child) c;
    }
  }
}

Interfaces

interface Interface {
  int foo();
}

class Concretion implements Interface {
  public int foo() {
    return 1;
  }
}

Generics

class Point<T> {
  private T x;
  private T y;

  public Point(final T x, final T y) {
    this.x = x;
    this.y = y;
  }

  public String toString() {
    return "(" + this.x + ", " + this.y + ")";
  }
}

public class GenericsExample {
  public static void main(final String[] args) {
    Point<Double> p = new Point<>(3.0, 1.0);

    System.out.println(p);
    System.out.println(new Point<>(4, 2));
    System.out.println(new Point<>(1.3, 4.2));
    System.out.println(new Point<>("x", "y"));
  }
}

ArrayList

import java.util.ArrayList;

public class ArrayListExample {
  public static void main(final String[] args) {
    final ArrayList<Double> a = new ArrayList<>();
    
    // Insert three elements
    a.add(1.0);
    a.add(3.0);
    a.add(2.0);
    
    // Traverse collection and print elements
    for (final double d : a) {
      System.out.print(d + " ");
    }
    System.out.println();
    
    a.set(1, 3.5); // modify 2nd element
    // Print 2nd element (random access)
    System.out.println(a.get(1));
    // Traverse collection and print elements
    for (final double d : a) {
      System.out.print(d + " ");
    }
    System.out.println();
  }
}

HashMap

import java.util.HashMap;

public class HashMapExample {
  public static void main(final String[] args) {
    HashMap<String, Double> hm = new HashMap<>();
    
    // Insert three elements
    hm.put("John", 1.0);
    hm.put("Mary", 3.0);
    hm.put("Jane", 2.0);

    System.out.println(hm); // print all entries
    hm.remove("Jane"); // remove an entry
    System.out.println(hm); // print all entries
    // Lookup based on key
    System.out.println("John: " + hm.get("John"));
  }
}