Java Review

When preparing for Java coding interview and implementing codes on Leetcode, I find it useful to have some of the most frequently used things written down in an “aid sheet”, just like this one.
This Java Review includes following contents:

  • I/O
  • Data Types
  • Regular Expressions
  • Methods and Classes
  • Running Java from command line
  • Some Classes and usages

Standard I/O

In: Scanner

1
2
3
4
5
Scanner sc = new Scanner(System.in);
Scanner sc = new Scanner(new File("filename.txt"));
while(sc.hasNext()) {
String tmp = sc.next();
}

Out: System.out
System.out.println(String s);
System.out.print(String s);
System.out.format(String s);

File I/O

In: File + ObjectInputStream

1
2
3
4
5
6
7
8
9
10
import java.io.*;
try {
FileInputStream fin = new FileInputStream("input.txt");
ObjectInputStream oin = new ObjectInputStream(fin);
Type t = (Type)oin.read();
oin.close();
fin.close();
} catch (IOException e) {
e.printStackTrace();
}

Out: File + ObjectOutputStream
1
2
3
4
5
6
7
8
9
10
import java.io.*;
try {
FileOutputStream fout = new FileOutputStream("output.txt");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.write(obj);
out.close();
fout.close();
} catch (IOException e) {
e.printStackTrace();
}

Data Types

  • 8 Primitive types
    • byte: 8-bit signed integer, $[-2^7, 2^7)$
    • short: 16-bit signed integer, $[-2^{15}, 2^{15})$
    • int: 32-bit signed integer, $[-2^{31}, 2^{31})$
    • long: 64-bit signed integer, $[-2^{63}, 2^{63})$
    • float: 32-bit floating point.
    • double: 64-bit floating point.
    • boolean
    • char: 16-bit Unicode character. Minimum value is \u0000
  • Reference types
    • String and Character
    • Wrapper classes: Byte, Double, Integer, Float, Short, Long.
    • Whatever defined in your own class.

Instance vs. Class (static) variables

Modifier Types

  • Access modifier
    • public
    • protected
    • private
    • (Package control)
  • Non-access modifier
    • static
    • final

Array vs. ArrayList

Array

1
2
3
int[] myarray = new new int[];
int[] myarray = {0, 1, 2, 3, 4};
L = myarray.length;

ArrayList
Note that ArrayList can only accept reference data types.
1
2
3
4
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(23333);
al.get(0);
L = al.size();

Regular Expressions

See this tutorial for details and official documentation for regular expression patterns. Following is an example of java.util.regex usage.

1
2
3
4
5
6
7
8
import java.util.regex.Pattern;
import java.util.regex.Match;

Pattern p = Pattern.compile("abc");
Matcher m = p.matcher(line);
if (m.find( )) {
System.out.println(m.group(0));
}

Methods and Classes

  • Everything is a Class in Java
  • Each file should contain only one public class (it can contain inner class though), with the file name equal to its class name. You can put multiple Classes in one file, but there can only be one main class, the public class
    For example, following is HelloWorld.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public class HelloWorld{

    private String msg;

    public HelloWorld() {
    msg = "123";
    }

    public void printMsg() {
    System.out.println(msg);
    }

    public static void main(String[] args) {
    HelloWorld hw = new HelloWorld();
    hw.printMsg();
    }
    }

  • To compile and run the Java file HelloWorld.java in command line, use following command. If you have NetBeans or Eclipse, there are more direct ways (click on the “run” button).
    1
    2
    javac HelloWorld.java
    java HelloWorld
  • Each Java class should have a public static void main(String[] args) method, and a constructor method without return type.

Some Useful Classes

I’m only listing some most useful methods (AFAIK up till now) for the basic programming problems. Remembering these methods can free us from consulting the API documentations during programming competitions.

public class Arrays extends Object

Doc
void sort()
void asList()
void binarySearch()

public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable

Doc
Constructor
ArrayList()
ArrayList(Collection<? extends E> c)
ArrayList(int initialCapacity)
Methods
boolean add(E e)
void add(int index, E Element)
void clear()
Object clone() Shallow copy
boolean contains(Object o)
E get(index)
int indexOf(objext o)
boolean isEmpty()
Iterator<E> iterator()
int lastIndexOf(Objext o)
ListIterator<E> listIterator()
ListIterator<E> listIterator(int index)
E remove(int index)
boolean remove(Object o)
boolean removeAll(Collection<?> c)
E set(int index, E element) Replaces the element
int size()
Object[] toArray()
<T> T[] toArray(T[] a)
void trimToSize()

public final class String extends Object implements Serializable, Comparable, CharSequence

Constructor
String()
Using StringBuilder
Methods
char charAt(int index)
String concat(String str)
boolean contains(CharSequence s)
boolean contentEquals(CharSequence cs)
boolean equals(Object o)
static String format(String format, Object... args)
byte[] getBytes() Encodes this String into a sequence of a charset.
int indexOf(int ch) first occurence
boolean isEmpty()
int length()
boolean matches(String regex)
String replace(char oldChar, char newChar)
String replace(CharSequence target, CharSequence replacement)
String split(String regex)
String startsWith(String prefix)
String substring(int begin)
String substring(int begin, int end)
String toLowerCase()
String toUpperCase()
String trim() Removes leading and trailing whitespaces
static String valueof(Object obj)

public class HashSet extends AbstractSet implements Set, Cloneable, Serializable

Constructor
HashSet()
HashSet(Collection<? extends E> c)
HashSet(int initialCapacity)
HashSet(int initialCapacity, float loadFactor)
Methods
boolean add(E e)
void clear()
Object clone()
boolean contains(Object o)
boolean isEmpty()
Iterator<E> iterator()
boolean remove(Object o)
int size()

public class HashMap extends AbstractMap implements Map, Cloneable, Serializable

Constructor
HashMap()
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
HashMap(Map<? extends K,? extends V> m)
Methods
void clear()
Object clone()
boolean containsKey(Object key)
boolean containsValue(Object value)
Set<Map.Entry<K,V>> entrySet()
V get(Object key)
boolean isEmpty()
Set<K> keySet()
V put(K key, V value
void putAll(Map<? extends K, ? extends V> m)
V remove(Object key)
int size()
Collection<V> values()

public class PriorityQueue extends AbstractQueue implements Serializable

Constructor
PriorityQueue()
PriorityQueue(Collection<? extends E> c)
PriorityQueue(int initialCapacity)
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
PriorityQueue(PriorityQueue<? extends E> c)
PriorityQueue(SortedSet<? extends E> c)
Methods
boolean add(E e)
void clear()
Comparator<? super E> comparator()
boolean contains(Object o)
Iterator<E> iterator()
boolean offer(E e) Insert
E peek()
E poll() Retrieves and removes the head of the queue
int size()
Object[] toArray()
<T> T[] toArray(T[] a)