Java

=Classes= Every java program needs at least one class to run. Classes are templates that are used to create objects, and to define object data types and methods.

Create a class
Class className{} Before the class you can specify the accessibility by using keywords.

=Objects= Objects are instances of a class.

Create an object
Flower daisy = new Flower; Where flower is the name of the class.

=Methods= A method is a task that an object of a class performs. A method is a piece of code that can execute something. It can be build first to represent certain commands. The main method is like the ground level so other methods can be executed in the main method. There are also standard methods already in Java like the print method.

Create a method
public void nameMethod{} Example: public void startEngine { System.out.println("Starting the car!"); System.out.println("Vroom!"); }
 * public means that other classes can access this method.
 * The void keyword means that there is no specific output from the method. So the first two words describe the method.
 * Within the curly brackets the commands that the method will be able to perform are written.

Create the main method
public static void main(String[] args) {}

Call a method
To call a method you can use: class.method;

Add parameter / constructor method
Parameters that will be accessible outside of the scope of the method can be created within the brackets. The method with the same name as the class is the constructor method. Example: class Car {

String color;

public Car(String carColor) { color = carColor; }

public void startRadio(String station) { System.out.println("Turning on the radio to " + station + "!"); System.out.println("Enjoy!"); }

public static void main(String[] args){ Car myCar = new Car("red"); myCar.startRadio("Meditation Station"); } }

String Methods
Returns the number of characters in the string. Syntax: String str = "Hello World!"; System.out.println(str.length); //This will print 12 concatenates one string to the end of another string. Concatenation is the operation of joining two strings together. Syntax: String name = "Code"; name = name.concat("cademy"); System.out.println(name); //This will print Codecademy The concat operation doesn't change the variable as you can see it only works when it's being reassigned like in the example. This method can check if a string is the same and returns a boolean. Since the primitive equality operator == can't be used on a string. Syntax: String flavor1 = "Mango"; String flavor2 = "Peach"; System.out.println(flavor1.equals("Mango")); // prints true System.out.println(flavor2.equals("Mango")); // prints false Does the same as equals, but isn't case sensitive. This method can check the indices of the first occurrence of a character or substring. Indices starting at 0. If the method doesn't find what it's looking for it will return -1 Syntax: String letters = "ABCDEFGHIJKLMN"; System.out.println(letters.indexOf("C")); //this will print 2 substring String letters = "ABCDEFGHIJKLMN"; System.out.println(letters.indexOf("EFG")); //this will output 4 Returns the character located at a String‘s specified index. When specifying an index outside of the range of the String the method will return an error. Syntax: String str = "qwer"; System.out.println(str.charAt(2)); //this will return e This method can extract a piece of a string based of specified indices. Syntax one argument: String line = "The Heav'ns and all the Constellations rung"; System.out.println(line.substring(23)); //this will print Constellations rung Syntax two arguments: String line = "The Heav'ns and all the Constellations rung"; System.out.println(line.substring(23, 38)); //this will print Constellations So the first argument is the index of the starting character and the second argument is the index-1 of the last character in the substring. Returns the string value converted to uppercase. Syntax: String input = "Cricket!"; String upper = input.toUpperCase; // stores "CRICKET!" Returns the string value converted to lowercase. Syntax: String input = "Cricket!"; String upper = input.toLowerCase; // stores "cricket!" Returns true if a specified substring is found within the string. Syntax: languageName.contains("Chinese"); //returns true or false
 * length
 * concat
 * equals
 * equalsIgnoreCase
 * indexOf
 * charAt
 * substring
 * toUpperCase
 * toLowerCase
 * contains

print line
System.out.println; This will print out anything that is between the brackets. It can take variables and text and you can combine multiple things to print with the + sign. If you want to print a text it should be between "".

=Inheritance= Using already defined methods and fields from a parent class in a child class.

define an inheritance
Inheritance works with the extends keyword. Example: class Shape {

// Shape class members

}

class Triangle extends Shape {

// additional Triangle class members

}

Inheriting the constructor
When inheriting the constructor method is also taken from the parent.

Set instance fields of the child
Example: class Triangle extends Shape {
 * using the supermethod you can fill in the inherited instance fields by placing the arguments in the same order as for the parent. This is useful when you want to have certain instance fields to be predefined for every instance of the child class.

Triangle { super(3); }

// additional Triangle class members

} Here the Shape class has an instance field called numSides. Since all the Triangle objects need to have three sides the super method is used to fill that in for the inherited instance field. class Triangle extends Shape {
 * You can also overwrite the constructor method of the child this way the parent class constructor is not being leveraged.

Triangle { this.numSides = 3; }

// additional Triangle class members

}

overwriting a method
You can do some modifications to an inherited method in the child class. The following attributes need to stay the same: Example: class BankAccount {
 * Method name
 * return type
 * number and type of parameters

protected double balance;

public void printBalance { System.out.println("Your account balance is $" + balance); }

}

class CheckingAccount extends BankAccount {

@Override public void printBalance { System.out.println("Your checking account balance is $" + balance); }

} The @Override keyword informs the compiler that we want to override a method in the parent class. If the method doesn’t exist in the parent class, we’ll get a helpful error when we compile the program.

child classes in arrays
to make an array of child classes: Monster dracula, wolfman, zombie1;

dracula = new Vampire; wolfman = new Werewolf; zombie1 = new Zombie;

Monster[] monsters = {dracula, wolfman, zombie1};

to use the array in a for-each loop for (Monster monster : monsters) {

monster.attack;

}

=Keywords= Keywords can be put before declarations of methods, variables of classes to specify things about them.

public
Accessible to: Class, package, child class, global.

protected
Accessible to: Class, package, child class.

no modifier
Accessible to: Class, package.

private
Accessible to: Class.

final
If we add final before a parent class method’s access modifier, we disallow any child classes from changing that method. This is helpful in limiting bugs that might occur from modifying a particular method.

=Loops=

while loop
A while loop will run over and over while a condition is true. When a condition won't evaluate to true at some point by running the code over and over you will create an infinite loop and your program will crash. Example: while (silliness > 10) {

// code to run

}

for loop
The for loop is a shorter way of incrementing with loops. The following example will run the code five times: for (int i = 0; i < 5; i++) {

// code that will run

} Example of a for loop using an Array: for (int i = 0; i < secretCode.length; i++) {

secretCode[i] += 1;

} Example of a for loop using an ArrayList: for (int i = 0; i < secretCode.size; i++) {

int num = secretCode.get(i); secretCode.set(i, num + 1);

}

for each loop
For-each loops allow you to directly loop through each item in a list. Syntax: for (String inventoryItem : inventoryItems) {

System.out.println(inventoryItem);

}

=Random Numbers= Java has a utility for random numbers. Example: // Importing the Random library import java.util.Random;

class LuckyFive { public static void main(String[] args) { // Creating a random number generator Random randomGenerator = new Random; // Generate a number between 1 and 6 int dieRoll = randomGenerator.nextInt(6) + 1; } }

=Debugging=

Syntax error
Errors found by the compiler These are like coding grammar errors. Things like missing symbols or misspelled variables. When the compiler sais there are a 100 errors it doens't neccesary mean there are so many errors usually the first one is the real error and the following ones are caused by that. Example: Debug.java:8: error: ';' expected This means a semi-colomn is missing on line 8.

Run-time error
Errors that occur when the program is running. It happens when a compiled program (so without syntax errors) asks the computer to do something it can't reliably do. Runtime errors are things like missing files or zero divisions.

Logic error
Errors found by the programmer looking for the causes of erroneous results.

Exeptions
Exceptions are the conditions that occur at runtime and may cause the termination of the program. When an exception occurs, Java displays a message that includes the name of the exception, the line of the program where the exception occurred, and a stack trace. The stack trace includes:
 * The method that was running
 * The method that invoked it
 * The method that invoked that one
 * And so on...

ArithmeticException
Something went wrong during an arithmetic operation; for example, division by zero.

NullPointerException
You tried to access an instance variable or invoke a method on an object that is currently null.

ArrayIndexOutOfBoundsException
The index you are using is either negative or greater than the last index of the array.

FileNotFoundException
Java didn’t find the file it was looking for.

Exeption Handling
You can test certain parts of the code with the try and catch words. defines a block of code to be tested. defines the block of code to be executed when an error occurs. Example: try {
 * try
 * catch

// Block of code to try

} catch (NullPointerException e) {

// Print the error message like this: System.err.println("NullPointerException: " + e.getMessage);

// Or handle the error another way here

} Example of chaining exeptions together: try {

// Block of code to try

} catch (NullPointerException e) {

// Code to handle a NullPointerException

} catch (ArithmeticException e) {

// Code to handle an ArithmeticException

} Example of using the debugging method: public class Debug {

public static void main(String[] args) { int width = 0; int length = 40; try{ int ratio = length / width; } catch (ArithmeticException e){System.err.println("ArithmeticException: "+e.getMessage);} } }