Java - KeynesYouDigIt/Knowledge GitHub Wiki

Java

  • main is what will run if you run the program
  • Works left to right, but uses precedence for math
  • System is part of the java.lang package, which is automatically imported
  • final makes something a constant, and uses THIS_CONVENTION
  • You can cast with parentheses - double someNumber = (int) 2.1 + 3.4
  • if/else, switch, while, for, logic operators are all the same as JS
  • For each loop: for (int value : values){
  • Calling printLn with an object calls its toString method
    • The default implementation displays the type of the object and prints its hex address
  • Source code is stored in /usr/lib/jvm/.../lib/src.zip
  • When there are no more references to an object, it gets deleted in the next round of garbage collection
  • Constructors have no return type (not even void), and don't use static
  • this is optional inside instance methods
  • Avoid null- give variables values on initialization, make separate signatures for optional values, using the Optional API. They're only OK as attributes in classes because they're unlikely to leak out.
  • Just assign properties in constructors. If you have more work to do, use a factory.
  • Gradle, maven, and bazel are build tools
  • Rely on enums instead of booleans

Vocab

  • Package = Related classes. Token -> Expression -> Statement -> Method -> Class -> Package
  • Composition is regular arrow in UML, inheritance is solid arrow

Installing

  • sudo apt install openjdk-11-jdk-headless

Hello World

// HelloWorld.class
public class HelloWorld {
  public static void main(String[] args){
    System.out.println("Hello, World!");
  }
}
javac HelloWorld.class
java HelloWorld

Types

Primitives: int, double, char, boolean

  • int
    • Integer.parseInt(string)
  • String - Compare with .equals, not ==. Are objects, are immutable.
  • double - Default float
  • boolean
  • char - Get from string with .charAt(position), cast with (char) from unicode
  • null - No object, trying to call something on it causes a NullPointerException

Wrapper classes: Integer, Boolean, Character, Long. Give methods to primitives, come from java.lang. Values are immutable. The same number or string is only stored once.

Standard Classes

  • Random - random.nextInt(exclusiveSize)
  • BigInteger - BigInteger.valueOf(1000000000000), uses methods like .add() instead of operators
  • BigDecimal
  • Point - From java.awt.Point, has x/y coordinates, can calculate distance
  • StringBuilder - More efficient than concatenating separate strings (use .append())

Collections:

  • List - Ordered collections with stable indexing order.
    • ArrayList - ArrayList<Type>. Contains .add(item), .remove(index), .get(index), .size(), and .isEmpty()
    • LinkedList
  • Map - Key:Value relationships, only unique keys.
    • HashMap - Unordered
    • LinkedHashMap - Ordered
    • TreeMap - Sorted
    • Set - Only the keys

Arrays

  • You have to declare a variable with the type, and then allocate memory for it with new.
  • Must all be the same type
  • Are initialized to empty values of that type
  • Printing the reference looks like [I@a3243c- "Array of integers at memory address a3243c"
  • Can stringify with Arrays.toString(array)
  • Can clone with Arrays.copyOf(array, array.length)
  • Stored as references
// Explicitly sized
int[] numbers = new int[4];

// Implicitly sized and assigned
int[] numbers = {1, 2, 3, 4}

Classes

public class SomeClass extends SomeSuperClass {
  private int someValue;

  public SomeClass(){
    super();
    this.someValue = 0;
  }

  public SomeClass(int someValue){
    super(someValue);
    this.someValue = someValue;
  }

  public int getSomeValue(){
    return this.someValue;
  }

  public void setSomeValue(int someValue){
    this.someValue = someValue;
  }
}

Exceptions

try {
  if (true){
    throw new WhateverError
  }
} catch (WhateverError error){
  // Handle it
}

Testing

  • JUnit has a display name generator that take snake-cased long names and prints them with spaces
import junit.framework.TestCase;

public class SomeTest extends TestCase {
  public void testSomething(){
    assertEquals(1, SomeClass.getOne())
  }
}

JavaDoc

Use for classes, interfaces, fields, and methods.

/**
 * Some class description
 * @author Kyle Coberly
*/

/**
 * Some method description
 * @param someParam the parameter being passed in
 * @return true if high, false if low
*/

JVM

Ways to crash the JVM:

  • Not enough RAM
  • Not enough disk space
  • Too many file descriptors open
  • Creating too many threads
  • Tweak a .class file
  • kill -9 the PID
  • Open too many sockets
  • Run code without verifying it
  • Use the Unsafe class to tweak memory, etc.

More!

Questions

  • Why are some types uppercase and others lowercase?
    • It's whether they are primitives or objects
  • How is an ArrayList different than an array?
  • Can a class be anything other than public?
  • What are streams?
  • What are checked exceptions, and why do Java devs hate them so much?
  • How do annotations work?
  • What is a bean?
⚠️ **GitHub.com Fallback** ⚠️