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: Scanner1
2
3
4
5Scanner sc = new Scanner(System.in);
Scanner sc = new Scanner(new File("filename.txt"));
while(sc.hasNext()) {
String tmp = sc.next();
}
Out: System.outSystem.out.println(String s);
System.out.print(String s);
System.out.format(String s);
File I/O
In: File + ObjectInputStream1
2
3
4
5
6
7
8
9
10import 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 + ObjectOutputStream1
2
3
4
5
6
7
8
9
10import 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
Array1
2
3int[] 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
4ArrayList<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
8import 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, thepublic class
For example, following is HelloWorld.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public 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
2javac 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
Docvoid sort()
void asList()
void binarySearch()
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable
Doc
ConstructorArrayList()
ArrayList(Collection<? extends E> c)
ArrayList(int initialCapacity)
Methodsboolean add(E e)
void add(int index, E Element)
void clear()
Object clone()
Shallow copyboolean 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 elementint size()
Object[] toArray()
<T> T[] toArray(T[] a)
void trimToSize()
public final class String extends Object implements Serializable, Comparable, CharSequence
ConstructorString()
Using StringBuilder
Methodschar 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 occurenceboolean 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 whitespacesstatic String valueof(Object obj)
public class HashSet extends AbstractSet implements Set, Cloneable, Serializable
ConstructorHashSet()
HashSet(Collection<? extends E> c)
HashSet(int initialCapacity)
HashSet(int initialCapacity, float loadFactor)
Methodsboolean 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
ConstructorHashMap()
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
HashMap(Map<? extends K,? extends V> m)
Methodsvoid 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
ConstructorPriorityQueue()
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)
Methodsboolean add(E e)
void clear()
Comparator<? super E> comparator()
boolean contains(Object o)
Iterator<E> iterator()
boolean offer(E e)
InsertE peek()
E poll()
Retrieves and removes the head of the queueint size()
Object[] toArray()
<T> T[] toArray(T[] a)