Java
do-while
This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Protected
We set the brand attribute in Vehicle to a protected access modifier. If it was set to private, the Car class would not be able to access it.
Throwing error
You can throw custom errors like: throw new ArithmeticException("Access denied - You must be at least 18 years old.");
Enum
a special "class" that represents a group of constants (unchangeable variables, like final variables) enum Level { LOW, MEDIUM, HIGH } Level myVar = Level.MEDIUM; Try it Yourself »
Abstract class
abstract class Animal { public abstract void animalSound(); public void sleep() { System.out.println("Zzz"); } } class Pig extends Animal { public void animalSound() { System.out.println("The pig says: wee wee"); } }
Primitive data type
all lowercase specifies the size and type of variable values, and it has no additional methods
Inheritance
class Car extends Vehicle ( with protected String brand = "Ford";) Car objects can use Vehicle variables and methods
Arraylist
class is a resizable array, which can be found in the java.util package. has a regular array inside it. When an element is added, it is placed into the array. If the array is not big enough, a new, larger array is created to replace the old one and the old one is removed. You want to access random items frequently You only need to add or remove elements at the end of the list import java.util.ArrayList; ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.get(0); cars.set(0, "Opel"); cars.remove(0); cars.size(); Collections.sort(cars);
HashSet
collection of items where every item is unique import java.util.HashSet; HashSet<String> cars = new HashSet<String>(); cars.add("Volvo"); cars.contains("Mazda");
Interface
completely "abstract class" that is used to group related methods with empty bodies interface Animal { public void animalSound(); public void run(); } class Pig implements Animal { public void animalSound() {System.out.println("The pig says: wee wee"); } public void sleep() { System.out.println("Zzz"); } } Java can do multiple inheritance, but not multiple classes class DemoClass implements FirstInterface, SecondInterface {..}
Continue
continues with the next iteration in the loop.
Type casting
double myDouble = 9.78d; int myInt = (int) myDouble;
Final Class
final class Vehicle No other classes can inherit from it
Final variable
final int myNum = 15;
Loop through items in iterable
for (String i : cars) { System.out.println(i); }
Files
import java.io.File; File myObj = new File("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!");
Input
import java.util.Scanner; Scanner myObj = new Scanner(System.in); String userName = myObj.nextLine(); //.nextInt() and stuff exist
Read file
import java.util.Scanner; File myObj = new File("filename.txt"); Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) { String data = myReader.nextLine(); System.out.println(data); } myReader.close();
Assign multiple vars
int x = 5, y = 6;
Encapsulation
make sure that "sensitive" data is hidden from users. To achieve this, you must: declare class variables/attributes as private; provide public get and set methods to access and update the value of a private variable
Wrapper class
provide a way to use primitive data (int, short, float, char, etc) types as objects ArrayList<Integer> myNumbers = new ArrayList<Integer>();
Class constructor
public class Main { int x; public Main(int y) { x = y; }
Ide setup
public class MyClass { public static void main(String[] args) { } }
Basic method
static void myMethod() { // code to be executed } static means that the method belongs to the Main class and not an object of the Main class. static void myMethod(String fname)
HashMap
store items in "key/value" pairs import java.util.HashMap; HashMap<String, String> capitalCities = new HashMap<String, String>(); capitalCities.put("England", "London"); capitalCities.get("England"); for (String i : capitalCities.keySet()) { System.out.println("key: " + i + " value: " + capitalCities.get(i)); }
Linkedlist
stores its items in "containers." The list has a link to the first container and each container has a link to the next container in the list. To add an element to the list, the element is placed into a new container and that container is linked to one of the other containers in the list. You only use the list by looping through it instead of accessing random items You frequently need to add and remove items from the beginning, middle or end of the list import java.util.LinkedList; LinkedList<String> cars = new LinkedList<String>(); cars.add("Volvo"); More efficient methods to access first and last items
Switch
switch(expression) { case x: // code block break; } The default keyword specifies some code to run if there is no case match:
boolean
true, false
Try Catch
try {...} catch(Exception e){...} finally {//executes no matter which of above runs}
Logical operators
&& ||
Class
Blueprint for creating objects. a class should always start with an uppercase first letter, and that the name of the java file should match the class name. public class Main { int x = 5; } Main myObj = new Main(); System.out.println(myObj.x);
Iterator
Can be used for any collection import java.util.Iterator; //cars is collection Iterator<String> it = cars.iterator(); System.out.println(it.next()); it.remove(); while(it.hasNext()) { System.out.println(it.next()); }
Create file
File myObj = new File("filename.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); } else { System.out.println("File already exists."); }
Polymorphism
Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways. Ex: calling on inheriting classes with the same name of function will call the more local scope function (myDog function rather than Animal)
Max value
Math.max(x,y);
Random
Math.random() returns a num in [0,1)
Inner Classes
Nested class To access the inner class, create an object of the outer class, and then create an object of the inner class Can be private or protected can also be static, which means that you can access it without creating an object of the outer class OuterClass.InnerClass myInner = new OuterClass.InnerClass(); can access attributes and methods of the outer class:
Non-primitive data type
Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot. A primitive type has always a value, while non-primitive types can be null. A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter. The size of a primitive type depends on the data type, while non-primitive types have all the same size.
Static vs public
Static can be accessed without creating an object of the class, unlike public, which can only be accessed by objects myStaticMethod(); // Call the static method // myPublicMethod(); This would compile an error Main myObj = new Main(); // Create an object of Main myObj.myPublicMethod(); // Call the public method on the object
ternary
String result = (time < 18) ? "Good day." : "Good evening."; variable = (condition) ? expressionTrue : expressionFalse;
Variables
String, char, boolean, float
Arrays
String[] cars; String[] cars = {"Volvo", "BMW"}; arr.length int[][] myNumbers = { {2, 3, 4}, {5, 6, 7} };
System.out.println("hi");
Modifiers
-Public: The class is accessible by any other class -default: only accessible by classes in the same package. This is used when you don't specify a modifier -Private: The code is only accessible within the declared class -Protected: code is accessible in the same package and subclasses -final: class cannot be inherited by other classes -abstract: The class cannot be used to create objects
Comments
// /* multi */
index method
txt.indexOf("i");
Length
txt.length()
txt to uppercase
txt.toUpperCase()
concatenate methos
txt1.concat(txt2);