CS 124 Java functions

This page contains all the objects, functions, methods, and their required input types that are included in the CS 124 course.

syntax

assert Boolean : String; 

instance instanceof Object instance -> Boolean

try {
} catch (Exception e) { //Exception = Exception, NumberFormatException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
}

throw new Exception(String); //Exception = IllegalArgumentException, etc. 

basic objects and methods

System.out.println()

java.util.Objects
Objects.hash(model, odometer)
Objects.toString(object)

object.equals(object)
object.hashCode()

Integer.parseInt()
Integer.MAX_VALUE

Character.toString(char)

Math
Math.sqrt(double) -> double
Math.pow(double, double) -> double

array[]
array.length

String
string.length()
string.sort()
string.IndexOf(int)
string.charAt(int)
string.toUpperCase()
string.toLowerCase()
string.split(String)
string.contains(String)
string.trim()
string.endsWith(String)
string.substring(int, int)
string.toCharArray()

java.util.Arrays
Arrays.asList(array) -> List
Arrays.fill(int, )
Arrays.toString(array) -> String
Arrays.sort(array)
copyOf(array, int)
Arrays.copyOfRange(array, int, int)

java.util.Date
date.getTime()

java.time.Instant 
Instant.now() -> Instant
instant.plusSeconds(60)

java.util.Random
Random() -> Random
random.nextLong(long)
random.nextInt(int)
random.nextFloat(float)
random.nextDouble(double)
random.nextBoolean()

java.math.BigInteger
BigInteger(String) -> BigInteger
bigInteger.add(bigInteger)

java.util.List
java.util.ArrayList
ArrayList<>() -> List<>
list.get(int)
list.set(int, )
list.add()
list.remove(int)
list.size()

java.util.Map
java.util.HashMap
HashMap<>() -> Map<, >
map.put()
map.get()
map.keySet()
map.entrySet() -> Map.Entry<, >

Map.Entry<, >
entry.getKey()
entry.getValue()

java.util.Set
java.util.HashSet
HashSet<>() -> Set<>
set.contains()
set.add()

copyO


com.fasterxml.jackson.databind.ObjectMapper
ObjectMapper() -> ObjectMapper
mapper.writeValueAsString(object) -> String
mapper.readValue(String, Object.class) -> Object

Class and Interface copied from cs124.org

class Person {
  String name;
  double age;
  Person(String setName, double setAge) {
    name = setName;
    age = setAge;
  }
  // Useful for really new people, like babies
  Person(String setName) {
    name = setName;
    age = 0.0;
  }
}
Person geoff = new Person("Geoff", 41.05);
// Lily is my niece. Super cute. Probably not into Java yet.
Person lily = new Person("Lily");
System.out.println(geoff.age);
System.out.println(lily.age);

// inheritance

public class Pet {
  protected String name;
  public Pet(String setName) {
    name = setName;
  }
  public String getName() {
    return name;
  }
}
public class Dog extends Pet {
  private String breed;
  public Dog(String setName, String setBreed) {
    super(setName);
    breed = setBreed;
  }
  public String getBreed() {
    return breed;
  }
  @Override
  public String toString() {
    return "A dog named " + name + " is a " + breed;
  }
}
Dog chuchu = new Dog("Chuchu", "mutt");

// Interface

interface Simple {
  int simple(int first);
}
public class Simpler implements Simple {
  public int simple(int first) {
    return first + 1;
  }
  public void simpler() { }
}
public class Another implements Simple {
  public int simple(int first) {
    return first - 1;
  }
  public void another() { }
}
Simple simple = new Simpler();
System.out.println(simple.simple(1));
simple = new Another();
System.out.println(simple.simple(1));

// Comparable

// interface OurComparable {
//   int compareTo(Object other);
// }

public class Example implements Comparable {
  private int value;
  public Example(int setValue) {
    value = setValue;
  }
  @Override
  public String toString() {
    return "Example with value=" + value;
  }
  @Override
  public int compareTo(Object o) {
    Example other = (Example) o;
    return value - other.value;
  }
}
Example example = new Example(8);
Example second = new Example(10);
Example third = new Example(10);
System.out.println(second.compareTo(third));

// Iterable, Iterator

import java.util.Iterator;
import java.util.Random;

// Random int Iterable
public class RandomIterable implements Iterable, Iterator {
  private final Random random = new Random();
  private final int size;
  public RandomIterable(int setSize) {
    assert setSize > 0;
    size = setSize;
  }
  private int count;
  public Iterator iterator() {
    count = size; // because size is not initialized outside the function
    return this;    
  }
  public boolean hasNext() {
    return count > 0;
  }
  public Object next() {
    count--;
    return random.nextInt() % 32;
  }
}
RandomIterable iterable = new RandomIterable(8);
for (Object value : iterable) {
  System.out.println(value);
}

// Anonymous class

//--------------- A typical class ----------------
public class Person {

  public String getRole() {
    return "Person";
  }
}

// Person person = new Person();
// System.out.println("Normal class example 1: " + person.getRole());

public class Student extends Person {
  @Override
  public String getRole() {
    return "Student";
  }
}
Person student1 = new Student();
System.out.println("Normal class example 2: " + student1.getRole());

//----------- Anonymous class example ------------
Person teacher = new Person() {
  @Override
  public String getRole() {
    return "Teacher";
  }
};

// Person janitor = new Person() {
//   @Override
//   public String getRole() {
//     return "Janitor";
//   }
// };

System.out.println("Anonymous class example 1: " + teacher.getRole());

//-------------- Anonymous class example (interface) ---------
interface Hobby {
  String getHobby();
}

Hobby tennis = new Hobby() {
  @Override
  public String getHobby() {
    return "tennis";
  }
};

System.out.println("Anonymous class interface example 1: " + tennis.getHobby());


/* Summary

Declaring an anonymous class
Person teacher = new Person() { ..... };
1. new - "new" operator
2. Person - the interface or class you are implementing/ extending
3. () - if required: arguments for the constuctor in the paranthesis
4. {...} - body of the class definition within the braces
5. ; - semicolon since this is still an expression


Uses
1. Single use cases
2. Instantiate interface

Restrictions/ Limitations
1. Anonymous classes don't have a name
2. Can't provide constructor
3. Can only implement or extend a class one at a time
*/

// Lambda expression 

interface Modify {
  int modify(int value);
}

Modify first = (value) -> value + 1;

System.out.println(first.modify(10)); // 11

// Amother Lambda expression

interface IncludeValue {
  // Return true if the value should be counted
  boolean include(int value);
}
int countArray(int[] values, IncludeValue includeValue) {
  int count = 0;
  for (int value : values) {
    if (includeValue.include(value)) {
      count++;
    }
  }
  return count;
}

int[] array = {1, 2, 5, -1};

System.out.println(countArray(array, v -> v % 2 != 0));
System.out.println(countArray(array, v -> v >= 0));
System.out.println(countArray(array, v -> v % 3 == 0));

// Generic

public class Example<E extends Comparable<E>> {
  private E value;
  public Example(E setValue) {
    value = setValue;
  }
}
Example<String> example = new Example<>("test");

// Stream

import java.util.stream.Stream;
public class Dog {
  private String name;
  private int age;
  public Dog(String setName, int setAge) {
    name = setName;
    age = setAge;
  }
  public String getName() {
    return name;
  }
  public int getAge() {
    return age;
  }
}
int totalAge = Stream.of(new Dog("Chuchu", 16), new Dog("Lulu", 4), new Dog("Shadow", 1))
    .mapToInt(dog -> dog.getAge())
    .sum();
System.out.println(totalAge);

long count = Stream.of(1, 2, 5)
    .filter(e -> e % 2 != 0)
    .count();
System.out.println(count);

String sum = Stream.of(1, 2, 5)
    .map(e -> "" + e)
    .reduce("", (a, b) -> { 
      return a + b; 
    });
System.out.println(sum);

Last Updated on 12 months by Yichen Liu