Java at Breakneck Speed

A Tour of Must-Know Java Data Structures and Operations

Photo by Steve Johnson on Unsplash

Introduction

This article can help you if you’re already familiar with Java and you need to:

  1. Prepare for interviews, or
  2. Reacquaint yourself with the language after a period away from Java e.g. moving from frontend to a backend project.

Each part consists of a “drill” that explores important operations of a few common Java data structures.

Names of variables and methods are kept deliberately short to minimize the amount of typing required to complete the code exercises.

What This Article Is Not

This article is about learning by doing and doesn’t offer thorough explanations of the operations used. You’re left to explore these operations in more detail in your own time.

Setup

You can work with Java immediately using an online IDE such as Repl.

On the top left-hand side, click the Create button and search for Java in the Template dropdown list as shown below, then click Create Repl.

(You can also follow these instructions to install the latest version of Java on your computer, and download an IDE such as Eclipse or Netbeans).

Click the Run button — the console should print “Hello World”:

To make it quicker (and easier to read), print to the console using this method:

static void o(Object x) {
System.out.println(x);
}

To test this out, change the main method as follows to print the sum of two numbers:

public static void main(String[] args) {
o(2 + 2);
}

Next, copy and paste the following imports above the Main class:

import java.lang.Math;
import java.util.*;

Now, add the following overloaded method to print arrays nicely:

static void o(String[] x) {
o(Arrays.toString(x));
}

Your code should look like this:

import java.lang.Math;
import java.util.*;
class Main {
public static void main(String[] args) {
o(2 + 2);
}

static void o(Object x) {
System.out.println(x);
}
static void o(String[] x) {
o(Arrays.toString(x));
}
}

We’re now ready to begin the drills!

Please note the following:

  • The result of code execution is placed on the right after //.
  • Any code that throws an exception is marked with 🔥.

Basic Control Flow

Update the body of the main method to print the following:

int a = 1;
int b = 2;

if (a < b) o("a < b");
else if (a == b) o("a = b");
else o("a > b"); // 'a < b'

while (a < 3) {
o(a);
a++;
} // 1
// 2
int[] y = { 1, 2 };for (int i = 0; i < y.length; i++)
o(y[i]); // 1
// 2
for (int j : y)
o(j); // 1
// 2
for (int j : y) {
if (j == 1) continue;
o(j);
} // 2
for (int j : y) {
if (j == 2) break;
o(j);
} // 1

Number

o(5/2);                           // 2
o(5.0/2); // 2.5
o(5/2.0); // 2.5
o(5%2); // 1
o(Math.pow(5, 2)); // 25.0
o(((Object)1).getClass()); // class java.lang.Integer
o(((Object)1.1).getClass()); // class java.lang.Double
o((int)1.1); // 1
o((float)1); // 1.0
o(Math.round(1.4)); // 1
o(Math.round(1.5)); // 2
o(Math.rint(1.4)); // 1.0
o(Math.rint(1.5)); // 2.0
o(Math.round(1.14 * 10) / 10.0); // 1.1
o(Math.round(1.15 * 10) / 10.0); // 1.2
o(Math.abs(-1)); // 1
o(Math.floor(1.1)); // 1.0
o(Math.ceil(1.1)); // 2.0
o(Math.sqrt(4)); // 2.0
o(Math.E); // 2.718281828459045
o(Math.exp(2.0)); // 7.38905609893065
o(Math.log(2.0)); // 0.6931471805599453
o(Math.log(8) / Math.log(2)); // 3.0
Integer x = 1;
o(x.floatValue()); // 1.0
o(x.doubleValue()); // 1.0
Double y = 10e6;
o(y.intValue()); // 10000000
o(y.longValue()); // 10000000
o(y.shortValue()); // -27008
o(y.byteValue()); // -128
o(x.compareTo(0)); // 1
o(x.compareTo(1)); // 0
o(x.compareTo(2)); // -1
o(x.equals(1)); // true
o(x.equals(1.0)); // false
o(x.equals((short)1)); // false
o(Integer.valueOf(1)); // 1
o(Double.valueOf(1)); // 1.0
o(Integer.valueOf("1")); // 1
o(Integer.valueOf("11", 2)); // 3
o(Integer.toString(1)); // "1"
o(Double.toString(1)); // "1.0"
o(Integer.parseInt("1")); // 1
o(Integer.parseInt("1.0")); // 🔥
o(Double.parseDouble("1")); // 🔥
o(Double.parseDouble("1.0")); // 1.0

Character

Character is a wrapper class for a char field, used to store a single character.

o(Character.isLetter('a'));       // true
o(Character.isDigit('1')); // true
o(Character.isWhitespace(' ')); // true
o(Character.isUpperCase('A')); // true
o(Character.isLowerCase('a')); // true
o(Character.toUpperCase('a')); // 'A'
o(Character.toLowerCase('A')); // 'a'

String

Strings are collections of characters used to store text.

String x = "Abac";o(x.length());                    // 4
o(x.toUpperCase()); // "ABAC"
o(x.toLowerCase()); // "abac"
o(x.replace('A','X')); // "Xbac"
o(x); // "Abac"
o(x.startsWith("a")); // false
o(x.startsWith("A")); // true
o(x.endsWith("c")); // true
o(x.charAt(1)); // "b"
o(x.charAt(4)); // 🔥
o(x.lastIndexOf("a")); // 2
o(x.substring(1)); // "bac"
o(x.substring(1,4)); // "bac"
o(x.substring(1,5)); // 🔥
o("b".compareTo("a")); // 1
o("b".compareTo("b")); // 0
o("b".compareTo("c")); // -1
o("a".compareTo("A")); // 32
o("a".compareToIgnoreCase("A")); // 0
o("a".concat("b")); // "ab"
o((" ab").trim()); // "ab"
StringBuffer sb =
new StringBuffer("a");
o("a".contentEquals(sb)); // true
char[] ch = {'a', 'b'};
String str = "";
o(str.copyValueOf(ch)); // "ab"
String str1 = new String("a");
String str2 = str1;
String str3 = new String("a");
String str4 = new String("A");
o(str1.equals(str2)); // true
o(str1.equals(str3)); // true
o(str1.equals(str4)); // false
o(str1.equalsIgnoreCase(str4); // true
String[] y = "a-b".split("-");
o(y) // "[a, b]"

Array

An Array holds a specified number of values of a single type.

String[] x = { "b","a" };Arrays.sort(x);o(x)                                               // "[a, b]"o(Arrays.binarySearch(x, "a"));                    // 0
o(Arrays.binarySearch(x, "c")); // -3
o(Arrays.equals(x, new String[] { "a", "c" })); // false
Arrays.fill(x,"c");
o(x); // "[c, c]"

List

The List interface is a contract for an ordered collection, implemented by the ArrayList as follows:

List x = new ArrayList();
x.add(1);
x.add("a");
o(x.toString());
o(x); // "[1, a]"
o(x.get(1)); // "a"
o(x.get(2)); // 🔥
o(x.indexOf("a")); // 1
o(x.indexOf('c')); // 1
o(x.subList(1,2)); // "[a]"
o(x.subList(1,3)); // 🔥
o(x.set(1,"c")); // "a"
o(x); // "[1, c]"
o(x.remove(1)); // "a"
o(x); // "[1]"

Set

A set is a collection that contains no duplicate elements.

Set<String> x = new HashSet<String>();o(x.add("a"));                   // true
o(x.add("a")); // false
x.add("b");
o(x); // "[a, b]"
o(x.size()); // 2
o(x.contains("a")); // true
o(x.remove("a")); // true
o(x.remove("c")); // false
x.clear();
o(x.isEmpty()); // true

SortedSet

A SortedSet also orders the elements in a set.

x.add("b");
x.add("a");
o(x.first()); // "a"
o(x.last()); // "b"
o(x.subSet("a","b")); // "a"
o(x.headSet("a")); // "[]"
o(x.headSet("b")); // "[a]"
o(x.tailSet("a")); // "[a, b]"
o(x.tailSet("b")); // "[b]"
Iterator it = x.iterator();while (it.hasNext()) o(it.next()); // "a"
// "b"

Map

A Map is an object that maps keys to values, where each key is unique.

x.put("a", 10);
x.put("b", 20);
o(x); // "{a=10, b=20}"
o(x.entrySet()); // "[a=10, b=20]"
o(x.get("a")); // 10
o(x.get("c")); // null
o(x.keySet()); // "[a, b]"o(x.containsKey("a")); // true
o(x.containsValue(10)); // true
o(x.put("a", 15)); // 10
o(x); // {a=15, b=20}
x.clear();
o(x.isEmpty()); // true

SortedMap

A SortedMap also orders the elements in a map.

SortedMap<String, Integer> x = new TreeMap<String, Integer>();x.put("b", 20);
x.put("a", 10);
o(x); // "{a=10, b=20}"o(x.firstKey()); // "a"
o(x.lastKey()); // "b"
for (Map.Entry<String,Integer> e : x.entrySet()) {
String key = e.getKey();
Integer value = e.getValue();

o(key + " : " + value); // "a : 10"
// "b : 20"
}
Set s = x.entrySet();
Iterator i = s.iterator();

while(i.hasNext()) {
Map.Entry m = (Map.Entry)i.next();
o(m.getKey() + " : " + m.getValue());
}
// "a : 10"
// "b : 20"

Stack

A Stack is a last-in-first-out (LIFO) stack of objects; like a stack of dinner plates, where the last plate added to the pile is the first one to be removed.

Stack<String> x = new Stack<String>();
x.push("a");
x.push("b");
o(x); // "[a, b]"
o(x.search("b")); // 1
o(x.peek()); // "b"
o(x.pop()); // "b"
o(x); // "[a]"

x.pop();
o(x.empty()); // true

Queue

A Queue is a first-in-first-out (FIFO) stack of objects; like a queue of people waiting to be served.

Queue<Integer> x = new LinkedList<>();x.add(1);
x.add(2);
x.add(3);
o(x); // "[1, 2, 3]"
o(x.size()); // 3
o(x.contains(1)); // true
o(x.contains(4)); // false
for (Integer z : x) o(z); // 1
// 2
// 3
Iterator<Integer> i = x.iterator();
while(i.hasNext()) o(i.next()); // 1
// 2
// 3
o(x.peek()); // 1
o(x); // "[1, 2, 3]"
o(x.poll()); // 1
o(x); // "[2, 3]"
x.remove();
x.remove();
o(x.size()); // 0
o(x.poll()); // null
o(x.remove()); // 🔥

To demonstrate what happens when we attempt to add elements to a queue with a capacity, add the following import:

import java.util.concurrent.LinkedBlockingQueue;

Now add the following code to show the difference between add and offer methods:

Queue<Integer> y = new LinkedBlockingQueue<Integer>(2);y.add(1);
y.add(2);
o(y.size()); // 2
o(y.offer(3)); // false
y.add(3); // 🔥

Thanks for reading! Let me know what you think in the comments section below, and don’t forget to subscribe 👍

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
George Marklow

George is a software engineer, author, blogger, and abstract artist who believes in helping others to make us happier and healthier.