Monday, May 22, 2017

Java refresher

Java version of hello world is like this:
import java.util.*;
public class vanilla {
    public static void main(String args[]) {
    System.out.println("hello world");
  1. java.util is the basic package of Java, which contains many useful classes such as Arrays, ArrayList, Date, HashMap, Hashtable, LinkedList, Random, Set, List. A full description is here.
  2. class is usually public so it can be called. The class name is the same with the java file name. Because we usually have multiple classes work together, a project is build.
  3. There will be a main method, which is also usually public. So the java application runs by the main method.
  4. System is one of the classes in java.lang package, which is the default. A full list of the package is here.
Because Java is compile-run 2-step language, so:
  • we don’t have interactive IDE like Jupyter notebook, Matlab or R studio.
  • It is a production language. It is static type so you declare data type of each variable.
  • It trades development time for run time.
For convenience, I only write the code snippet inside the main method.

2 types of for-loop and array

int [] numbers = {10, 20, 30, 40, 50}; //list of int
for(int x : numbers ) {
    System.out.print( x +"\t");
String [] names = {"James", "Larry", "Tom", "Lacy"};  // list of String
for( String name : names ) {
    System.out.print( name + ",");
} // enumerate style: enhanced
for (int i=0; i<5;i++){
}  // incremental style: traditional
conditional operator Exp1 ? Exp2 : Exp3;


System.out.printf("The value of e is %.4f%n", Math.E);
System.out.printf("sqrt(%.3f) is %.3f%n", x, Math.sqrt(2));
note: printf is formatted print so %.3f means the float variable is formatted as 3 digits after the decimal point.%n is used to create a new line.


String Str = new String("");
for (String word: Str.split("-")) {
} // iterate to print an array of string
s.substring(0,2) // get first 2 letters.

pass array to method

public static void printArray(int[] array) {
   for (int a :array) {
      System.out.print(a + " ");
printArray(new int[]{3, 1, 2, 6, 4, 2});

regular expression

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
   public static void main( String args[] ) {
      String line = "This order was placed for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)"; // 3 groups
      Pattern r = Pattern.compile(pattern);
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + );
         System.out.println("Found value: " + );
         System.out.println("Found value: " + );
      }else {
         System.out.println("NO MATCH");

args input

public class CommandLine {
   public static void main(String args[]) { 
      for(String s:args) {

file IO

public class vanilla {
    public static void main(String args[]) throws IOException{
        FileReader in = new FileReader("input.txt");
        FileWriter out = new FileWriter("output.txt");
        int c;
        while ((c = != -1) {
} package has a lot of paired classes to perform input and output in terms of streams.
  • Byte Streams: 8-bit bytes. FileInputStream, FileOutputStream
  • Character Streams: 16-bit unicode. FileReader, FileWriter
  • Standard Streams: InputStreamReader, System.out.println

Directories operation

File d = new File("/tmp/user/java/bin");
d.mkdirs(); //create a directory and all parent directory

File a = new File("/tmp");
String[] paths = a.list();  // list all files, directories
for (String path: paths){

read and parse csv file

This is for a simple case, which you use split() to parse the csv file.
String csvFile = "country.csv";
String line = "";
BufferedReader buffer = null;
try {FileReader file = new FileReader(csvFile);
     buffer= new BufferedReader(file);
    while ((line = buffer.readLine()) != null) {
        String[] words = line.split(",");
        for (String s:words ) {
            if (s.equals("\"China\"")){System.out.println("hello");}
}  catch (IOException e) {e.printStackTrace();}

array vs ArrayList

  1. array such as int[] nums= int[5] has fixed size, but arraylist such as ArrayList<Integer> nums = new ArrayList<Interger>() has elastic size.
  2. array is easy to use and storage efficient but has limited functionality
int[] nums= {1,2,3};

ArrayList<Integer> n = new ArrayList<Integer>();
double array size:
int [] nums = new int[100];
int size = 0;  // track of current size
value [size] = value;
if (size>= nums.length){
  nums = Arrays.copyOf(nums, 2*nums.length);
}  // from java.util.Arrays package
System.out.println(Arrays.toString(nums)) // use string to print
  1. String can be converted to chars by s.toCharArray(), or you access individual char using s.chartAt(i)
  2. length of string is s.length() but length of array is a.length, length of ArrayList is al.size()


import java.util.Scanner;
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(;
String username = scanner.nextLine();
System.out.println("Your username is " + username);
You can use while(scanner.hasNextDouble()) to check user input for continuous input.

add external jar in intell j

file ->project structure -> modules -> dependecne => +JARs

java system property

java.util.Properties props = System.getProperties();


IntelliJ is my favourite. BlueJ is also nice due to its class-module visualization.

Downloading BlueJ