Java
Table of Contents
This is a list of various important and miscellaneous Java features that is helpful throughout the course.
1. Compiling Programs
Java programs must first be compiled and then run:
javac [program].java && java [program]
2. Variables
2.1. Primitive Types
Variables in Java must be declared with their type. Once that type is set, the type of that variable can never change. Additionally, types are checked and type errors are thrown at compile-time. The following are primitive types in Java:
int x = 0; // integer
boolean b = true; // boolean
double d = 3.14; // decimal values
String s = "Hello, world!"; // strings
char c = 'h'; // single characters
2.2. Strings
String s = "hello";
s += " world";
s += 5; // can add anything to strings (will be converted)
s += "abc".repeat(3);
int sLength = s.length();
String substr = s.substring(1, 5);
char c = s.charAt(2);
if (s.indexOf("hello") != -1) {
System.out.println("\"hello\" in s");
}
for (int i = 0; i < s.length(); i++) {
char letter = s.charAt(i);
System.out.println(letter);
}
3. Operators
3.1. Mathematical Operators
int a = 1 + 2 // addition
int b = 2 - 1 // subtraction
int c = 3 * 4 // multiplication
int d = 4 / 3 // floor division
double e = 4 / 3 // division
int f = 4 % 3 // modulus (1)
int g = (1 + 2) * (3 + 4) // association
double h = Math.pow(2, 10) // exponentiation
3.2. Comparison Operators
1 < 2 // less than
1 <= 2 // less than or equal to
2 > 1 // greater than
2 >= 1 // greater than or equal to
1 == 1 // equals to
2 != 1 // not equal to
3.3. Boolean Operators
true && true // and (true)
false || true // or (true)
!true // not (false)
4. Functions
4.1. Defining Functions
Code in Java must be located inside of a function. We use curly braces to start and end functions:
int larger(int x, int y) {
if (x > y) {
return x;
} else {
return y;
}
}
Notice that the function has parameters whose types must be declared. Additionally, functions must also have a return type in front of the function name.
5. Conditional Statements
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
6. Iteration
6.1. while
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
6.2. for
for (int i = 0; i < 10; i ++) {
System.out.println(i);
}
// for-each loops
List<String> L = new ArrayList<>();
L.add("a");
L.add("b");
L.add("c");
for (String s: L) {
System.out.println(s);
}
7. Data Structures
7.1. Arrays
void main() {
String[] x = new String[5];
int[] y = {1, 2, 3, 4, 5}; // can also initialize with braces
x[0] = "a";
x[1] = "b";
System.out.println(x[0]);
}
7.1.1. 2D Arrays
int[][] pascalsTriangle;
pascalsTriangle = new int[4][]; // an array of 4 arrays
pascalsTriangle[0] = new int[]{1};
pascalsTriangle[1] = new int[]{1, 1};
pascalsTriangle[2] = new int[]{1, 2, 1};
pascalsTriangle[3] = new int[]{1, 3, 3, 1};
int[][] x;
int[][] matrix;
x = new int[4][];
matrix = new int[4][4]; // an array of 4 arrays of length 4
7.2. Lists
import java.util.ArrayList;
import java.util.List;
void main() {
List<String> L = new ArrayList<>(); // must choose a type of List
L.add("a");
L.add("b");
L.add("c");
L.set(0, "z");
System.out.println(L.get(0));
System.out.println(L.size());
if (L.contains("a")) {
System.out.println("a in list");
}
}
7.3. Maps
import java.util.HashMap;
import java.util.Map;
void main() {
Map<String, Integer> m = new HashMap<>();
m.put("cat", 103);
m.put("dog", 5);
int numCats = m.get("cat");
int noEntry = m.getOrDefault("fish", 0);
System.out.println(m.size());
if (m.containsKey("cat")) {
System.out.println("cat in map");
}
for (String key: map.keySet()) {
System.out.println(key);
}
}
7.4. Abstract Data Types
A List is an abstract concept of a list, the programmer must choose a specific type of List implementation. While the most common type of List is ArrayList, but LinkedList is also sometimes used.
Many data structures in Java are like this: the List is known as the abstract data type, whereas the ArrayList and LinkedList implementations are known as a concrete implementation.
8. Classes
Classes provide a blueprint for instances of that class:
class Dog {
int size; // instance variable
Dog(int s) { // constructor
size = s;
}
void makeNoise() { // instance method
if (size < 10) {
System.out.println("yip");
} else if (size < 30) {
System.out.println("bark");
} else {
System.out.println("woof");
}
}
Dog maxDog(Dog otherDog) {
if (otherDog.size > size) {
return otherDog;
}
return this; // uses `this` to reference itself
}
static void main() {
Dog d = new Dog(1000);
d.makeNoise(); // invocation of the makeNoise method
}
}
The instance variables that the class was defined with must be obeyed by all instances of that class. New instances of Dog will contain only the size instance variable.
To create a new instance of a class, we must write a declaration, instantiation, and assignment:
void main(String[] args) {
Dog smallDog; // declaration
new Dog(20); // instantiation
smallDog = new Dog(5); // instantiation and assignment
Dog hugeDog = new Dog(150); // declaration, instantiation and assignment
smallDog.makeNoise();
hugeDog.makeNoise();
}
8.1. Accessing Classes
Classes can be accessed from other files in Java without importing the file itself. Java automatically scans all folders from a list to see if the desired class exists.
8.2. Static
Static methods are methods for a class, not an instance of that class:
static Dog maxDog(Dog d1, Dog d2) { // no `this` in a static method
if (d1.size > d2.size) {
return d1;
}
return d2;
}
Additionally, these static methods can be used without the class being instantiated. However, they cannot access their own instance variables, they must do so through another instance.
Classes can also have static variables, which similarly can also be always accessed using the class name, not an instance name.
8.3. Access Control
We can restrict access to classes and class variables by using the private keyword instead of
public. By setting something as private, we restrict the use of that item to within the class.
8.4. Nested Classes
public class SLList {
public class IntNode {
int item;
IntNode next;
public IntNode(int item, IntNode next) {
this.item = item;
this.next = next;
}
}
IntNode first;
public SLList(int first) {
tihs.first = new IntNode(first, null);
}
// ...
}
9. Enums
public enum Direction {
UP,
DOWN,
LEFT,
RIGHT
}
10. Packages
Java does not allow us to have two classes with the same name in a project, because when we reference its name, it does not know which one we are referring to. However, if we add a package, we change the canonical name to have the package name in front of the class.
Additionally, Java won't look at every folder on your computer. Instead, it looks only at a list of paths called the CLASSPATH.