Java datatypes
Variable Basics
String name; // declare String name = "will"; // declare/assign name = "will" // assign String fullname = "will" + " pittman";Java name rules (variables, classes, methods, ...).
[a-z$_][a-zA-Z$_]*
.TODO:
converting between types
Implied Types
"abc" // String 0.1 // double 0.1d // double 0.1f // float 1 // int
Basic Datatypes
String name = "will"; int age = 30; float height = 5.11; char initial = 'j'; boolean deceased = false;
Boolean
TODO:
what counts as true, what counts as false
Numbers
byte num = 127; // whole numbers from -128 to 127 short num = 32767; // whole numbers from -32,768 to 32,767 int num = 2147483647; // whole numbers from -2,147,483,648 to 2,147,483,647 long num = 9223372036854775808; // whole numbers from -9,223,372,036,854,775,808 to 9,223.372,036,854,775,808 float num = 3.141592; // fractional numbers from 3.4e−038 to 3.4e+038. Sufficient for storing 6 to 7 decimal digits double num = 3.141592653589793; // fractional numbers from 1.7e−308 to 1.7e+038. Sufficient for storing 15 decimal digits
Strings
See: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html
String name = "will"; String lastname = "pittman"; String fullname = name + " " + lastname; // concatenation name.length(); // num characters name.toUpperCase(); name.toLowerCase(); name.indexOf('l'); // index of first occrrence of 'l' name.substring(1, 2); // 'il' (slice of string after 1st occurrence of 't') (like name[1:2])String.format("name: %s age: %d", "will", 33); // string formatting %b // boolean (supports any type, null vs non-null) %c // unicode char %d // integer %n // platform-specific line separator %s // string (supports any type) %a // floating point %e // floating point (scientific-notation) %f // decimal number <source lang="java">
Collections
Arrays
An array is a fixed-size collection of items that all share the same type.
import java.util.Arrays; import java.util.stream.Stream; new String[0]; // initialize empty string array String[] classmates = {"alex", "courtney", "sam"}; int[][] nested_array = {{1,2,3}, {4,5,6}}; {1, 2, 3}.length // size of array ages[1]; // get item in array Arrays.binarySearch(classmates, "alex"); // item in array Stream<String> = Arrays.stream(classmates); // convert array to streamLists
WARNING:
list is an abstract base-classimport java.util.List; import java.util.Arrays; // instantiation List list = List.of("a", "b", "c"); List list = new ArrayList(); // generic list List<String> list = new ArrayList<String>; // specific list list.add("alex"); list.add(0, "courtney"); list.remove("alex"); list.remove(0); list.toArray(); list.stream();There are also a few subtypes of Lists. Generally, it is considered more sane to use Lists if possible, since coding to this interface enables you to use any one of them.
ArrayList
ArrayLists are almost a bare implementation of List.They are dynamically sized, and can be slower to add/remove items since the list directly refers to items, like with an Array.
import java.util.ArrayList ArrayList<String> letters = ArrayList.of("a", "b", "c"); letters.clone(); // shallow copy letters.forEach(i -> System.out.println(i)); // letters.trimToSize(14); letters.LinkedList
A linkedlist stores references to objects in the list. Add/Remove operations are very fast, but it can use more memory.Streams
Streams are almost essential for processing any collection. A stream will allow you to iterate over items in a collection, filtering it, manipulating it, and converting the stream back into a useful datatype.
Almost every method on a stream returns another stream. Think of it like shellscript pipelines.
import java.util.Arrays; import java.util.stream.Stream; Stream friends = Stream.of("alex guthrie", "courtney guthrie", "sam scott"}; List<String> guthries = friends .filter(friend -> friend.endsWith("guthrie")) .collect(Collectors.toList()); System.out.println(guthries); #> {"alex guthrie", "courtney guthrie"}some other useful methods
// loop stream.peek(friend -> System.out.println(friend)); // run on each item (stream can still be used in pipeline) stream.forEach(friend -> System.out.println(friend); // run on each item (destroys stream) // conversion stream.collect(Collectors.toList()); // convert to list stream.toArray(String[]::new); // convert to String[] stream.iterate() // functional operations stream.map(Class::method); // run method on each item stream.filter(x -> x.endsWith("y")); // filter results stream.reduce((x, y) -> x + y); // combine all items (ex: {1,2,3} == 1 + 2 + 3) // boolean checks on items stream.allMatch(r -> r == true) stream.anyMatch(r -> r == true)HashMap
import java.util.HashMap; // define hashmap HashMap<String, String> hmap = new HashMap<String, String>(); hmap.put("1", "one"); hmap.put("2", "two"); System.out.println(hmap); >>> {1=one, 2=two} hmap.get("1"); // iterate over hashmap import java.util.Set; import java.util.Iterator; Set set = hmap.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry mentry = (Map.Entry)iterator.next(); System.out.print("key is: "+ mentry.getKey() + " & Value is: "); System.out.println(mentry.getValue()); }
Enums
enum Level { LOW, MEDIUM, HIGH } Level level = Level.MEDIUM; System.out.println(level);
Callables
java.util.function
contains the various classes representing callables.methods
with return value
import java.util.function.Function; Function<YourClass, ReturnClass> func = YourClass::method; func.apply(); // call methodwithout return value
import java.util.function.Consumer; Function<ReturnClass> func = YourClass::method; func.accept(); // call methodstatic methods
with return valueimport java.util.function.Supplier; Supplier<ReturnClass> func = YourClass::method; func.get(); // call method