# Java Notes / AP CSA
#literature-note/courses #programming #computer-science #writing/guide #torefactor
An overlap of an [[Advanced Placement MOC|AP]] course. Java programming as quick as possible.
[version:: 0.3]
## About this note
The author assumes knowledge in [[AP CSP]] as well as an understanding of the relevant programming concepts like class and objects. This note is therefore intended for syntax review only.
Other things might be underexplained so be sure to investigate if anything is confusing (a simple google search usually gets you what you need to know). Also, do not assume everything is correct. I probably made mistakes but I'll try to fix them. In fact [you can be the one who fixes them](#A-note-to-contributors)!
### A note to contributors
==Any contribution to this note is welcome!== You can leave comments on the side, or you can just click on **[the edit link](https://hackmd.io/@chaosarium/ap-csa-notes/edit?both)** or the **edit button up there↗︎** to edit everything. Note that this file is written in [markdown](https://www.wikiwand.com/en/Markdown); you can learn the basic syntax [here](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax). Your edits will be updated live on the published note [here](https://hackmd.io/@chaosarium/ap-csa-notes).
Do credit yourself in the [Credits](#Credits) section at the very bottom :).
## General
### Hello World
Hello world is the tradition when you start to learn a programming language. The goal is to get something printed in the **console** (viz. the text area where the computer outputs information). Hello world gets a bit tricky in Java as a simple print **statement** (viz. code that tells the computer to perform an action). Btw all Java statements need to end with a `;`.
Let's try the print statement. Here, `System` is class from the Java core library, `out` is the output control inside `System`, and `println()` method is responsible for printing a line of text.
```java
System.out.println("Hello, world!");
```
Does it work? Nope. This is because java likes class, but our single print statement is not a class. To make it work, we do this:
```java
public class helloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
```
Run it, it works! So what's going on here? Well, it's a java thing that everything it runs must have a `main()` method. This is where the programmes initiates. The detail of the four lines that wrap around our print statement can be ignored for now.
### Writing Code
There are many tools out there for writing Java code, ranging from lightweight text editors to feature-rich **IDE**s (Integrated Development Environment)
A few recommendations:
- [IntelliJ](https://www.jetbrains.com/idea/)
- [[VSCode]]
### Running Code
Java is a **compiler** language, meaning that a thing called compiler will turn your Java code into **[machine code](https://www.wikiwand.com/en/Machine_code)** before your code gets executed.
You don't need to know this for the AP exam, but the AP course doesn't teach you how to be a developer. You need to know this if you want your Java skill to be useful.
The `javac` command is for compiling a `.java` file. For example, to compile `helloWorld.java`, run:
```zsh
javac helloWorld.java
```
You will get a `helloWorld.class` file. This is the compiled code. You can run the compiled file using:
```shell
java helloWorld
```
### Printing
- `System.out.print();` prints without creating new line
- `System.out.println();` prints and creates new line
## Comments
**Comment** in your code allows you to write something about your code. The Java compiler ignores everything in the comment. You can do comments this way:
```java
// This is a one line comment
System.out.println("some code"); // this is a comment behind a line of code
/*
This is a multi line comment.
This syntax looks somewhat like CSS comment, if you get what I mean.
*/
// The following line is written by a crazy person
System.out.println('I love "rm -rf /".');
```
## Variables and Data Types
See [[AP CSP#Big Idea 2 Data]] if you don't know what this is.
Variables store data. There could be different types of data. Data in Java could be subdivided this way:
- **primitive data type** can be thought of like plain data without anything fancy. For example an integer or a character.
- **Object** as data like a String (a fancy way to say text) that is defined on top of primitive types. This can get as fancy as you want it to be. String is the only fancy data we will deal with now
You can do more research to see how these two types are different in a lower level. Basically, primitive types use less computational resources but objects are more flexible.
### The primitive types
- Major ones
- `boolean` to hold true or false value
- `int` to store integer
- `char` for one character enclosed by `'`s
- `double` for decimal numbers
- Other ones you probably don't need to worry about
- `byte`
- `long`
- `short`
- `float`
To **declare** (i.e. create) these variables, use the syntax `<type> <variable name> = <target value>;` as in:
```java
// declaring variables
int age = 5;
char letter = 'z';
double score = 2.5;
boolean status = true;
```
One can also declare a variable without assigning a value
```java
// declare without assigning value
int mystery;
```
### String
String is special since it's an Object of multiple characters. The type `String` is capitalised to indicate the difference. A string is enclosed in `"`s when declared.
```java
// Make a String
String motto = "Don't Panic";
```
### Static Typing
Unlike some other language, java variables need to stick to the declared type, meaning that conflicting type and variable like this will break:
```java
// bad code
boolean dead = "probably";
```
### Constants
If you want to lock a variable so that its value doesn't change, stick the `final` keyword before the declaration.
```java
// You can't change this awesome String
final String theTruth = "Only entropy comes easy";
```
## Math Operations
### Basics
You can do math with the variables. Some operations include
```java
int a = 2;
int b = 42;
int result;
result = a + b; // adds the two numbers
result = b - a; // subtracts
result = a * b; // multiply
result = b / a; // divide
result = b % a; // modulo (viz. the reminder after division)
```
### Order of operation
parentheses -> multiplication -> division -> modulo -> addition -> subtraction
If you don't remember this, a good strategy is to just put parentheses until there's no confusion.
### Self operation
What if you want a variable to operate with itself?—Fancy operators.
```java
int x = 42;
// the evolution
x = x + 3; // make x equal to x + 3
x += 3; // fancy way to add 3 to x
// similar trick for other ones
x -= 1;
x *= 4;
x /= 1;
x %= 5;
```
### Increments and Decrements
Even easier to add or subtract 1
```java
int x = 42;
// the evolution
x = x + 1; // make x equal to x + 1
x += 1; // fancy way to add 1 to x
x++; // even fancier way to increment 1
// same thing for decrement
x--;
```
## Class and Objects
### Class
A **class** can be thought of as a concept. There could be multiple manifestation (named **object**) of the same concept, just like there could be different models of iPhone.
A class looks like this
```java
public class Album {
// some variables associated with objects of this class. These can be thought of fields on a spreadsheet that one needs to fill out for each record
String name;
int rating;
// constructor function; this creates the objects and assigns the values.
public Album(String name, int rating) {
this.name = name;
this.rating = rating;
}
// functions that objects will have. It's able to access the variables associated with the instance using the this keyword.
public void get_value() {
System.out.println("Album: " + this.name);
System.out.println("Rating: " + this.rating);
}
// main method is the thing that runs
public static void main(String [] args) {
System.out.println("oops i'm not doing anything. only a class is defined but no object is created");
}
}
```
Notice that we have four major things.
#### The Fields
`String name;` and `int rating;` are properties associated with each album. They are values stored inside each instance of the object. The objects can have different values at each field, but they all have the same fields like all albums have a title.
Using the `private` keyword before the variable can make it only accessible from within the method using the `this` keyword. For example:
```java
public class Bank{
private double asset; // this is a private variable
}
```
#### The Constructor
The constructor method `public Album(String name, int rating)` is named the same as the name of the class. It allows you to create objects while assigning variables to the fields in those objects every time you create them.
To create a class, we use the `new` keyword. Example:
```java
Album album = new Album("avaJ", 1);
```
Now we will have an `album` object with its name being `"avaJ"` and its rating being `1`.
A class *can* have multiple constructors provided that they have different parameters. This can make constructing a class more flexible. For example, this works because they have different parameters:
```java
...
public Album(String name, int rating) {
...
}
public Album(String name) {
...
}
...
```
#### Methods
Like `get_value()`, methods within class is actions that this class or its instances can do. It can take parameters, it can return something, and it can use the `this` keyword to get variables from the instance.
The general structure of a method looks like:
```plain
<accessibility> <return type> <method name>(<argument type> <argument>) {
}
```
- `<accessibility>` can either be `private` or `public`
- `private` methods are accessible only from the class
- `public` methods are accessible from any class
- `<return type>` is the data type being returned by the function using the `return` keyword
- For example, a public method that returns the instance variable `this.name` looks like `public String getName()`
- `<argument type>` and `<argument>` specifies the input that the method takes
- For example, a public method that changes the `this.name` method looks like `public void getName(String newName)`
**Accessor** methods returns field value(s) inside the object, allowing someone to "access" the information inside. Example:
```java
public class Bank{
private double asset; // this is a private variable
// An accessor
public double getAsset() {
return this.asset;
}
}
```
**Mutator** methods changes the field values inside the object. Example:
```java
public class Bank{
private double asset; // this is a private variable
// A mutator
public void setAsset(int newAsset) {
this.asset = newAsset;
}
}
```
**Static** methods can be ran without having to create a task. This is helpful when we want to directly use a method in a class. Example:
```java
public class Bank{
// A static method
public static int addMoney(int amount1, int amount2) {
return amount1 + amount2;
}
}
```
One can just use the method by calling `Bank.addMoney()`
#### The main method
This is where the code starts running. Just use the `public static void main(String [] args) {}` template for this and it should work.
### Objects
A Class serves as a template for creating objects. We can do so in the `main` method using the syntax `<Class name> <object name> = new <Class name>(<variables for constructor function>)`
```java
// ... (only main method shown here)
public static void main(String [] args) {
// create an instance of Album with its information
Album album = new Album("avaJ", 1);
// create another instance Album with some different properties
Album newAlbum = new Album("tpircSavaJ", 3);
// print the values for the fields of the first album
album.get_value();
System.out.println("switching album");
// print the values for the fields of the second album
newAlbum.get_value();
}
// ...
```
The output looks like:
```text
Album: avaJ
Rating: 1
switching album
Album: tpircSavaJ
Rating: 3
```
### Dot notation
We can can use `.` to access something inside an object or class. For the album example:
```java
// ... (only main method shown here)
public static void main(String [] args) {
// create an instance of Album with its information
Album album = new Album("avaJ", 1);
// go inside the album object, take its name, and print it
System.out.println(album.name);
}
// ...
```
The output:
```text
avaJ
```
## Logical Operations
### Comparing stuff
Comparisons yield a boolean output.
```java
int a = 2;
int b = 42;
boolean result;
result = a > b; // check if a is greater than b
result = b < a; // check if a is smaller than b
result = a >= b; // check if a is greater or equal to b
result = b <= a; // check if a is less or equal to b
result = b == a; // check if they are equal
result = b != a; // check if they are not equal
```
### Logic stuff
```java
// And operator
boolean result = condition1 && condition2;
// Or operator
boolean result = condition1 || condition2;
// Not operator
boolean result = !condition1;
// Combine to make something fancy
boolean result = !(condition1 && condition2) || condition3;
```
#### Order of operation
`()` -> `!` -> `&&` -> `||`
If forget, just parenthesis everything.
### Control Flow
See [[AP CSP]] if you don't know what this is
#### If syntax
standard version
```java
if (condition){
// do something
}
```
shorthand
```java
if (condition)
// one line something
```
#### If else syntax
standard version
```java
if (condition){
System.out.println("meow"); // one line statement
}
else {
// do something else
}
```
shorthand
```java
if (condition)
System.out.println("meow"); // one line statement
else
System.out.println("meooooow"); // one line statement
```
#### if else if syntax
standard version
```java
if (condition1){
// do something
} else if (condition2) {
// do something else
} else {
// if none of them done
}
```
standard version
```java
if (condition1)
System.out.println("meow"); // one line statement
else if (condition2)
System.out.println("meooooow"); // one line statement
else
System.out.println("meooooooooow"); // one line statement
```
## Loops
### While Loop
this runs as long as `condition` is true.
```java
while (condition) {
// do something
}
```
### For loop
This is essentially a neater version of the while loop. There are three statements in the parenthesis.
- `int i = 0` is ran at the start
- `i < 5` is the condition for the loop to keep running
- `i++` is ran after each iteration
```java
for (int i = 0; i < 5; i++) {
// do something
}
```
### For each loop
This goes through every element of an array
```java
for (int length : lengths) {
// do something with the book
}
```
### Keywords
Use the `break;` statement to jump out of a loop
## The Strings Class
As said, String is a fancy object data, it has many methods for making life easier.
```java
String str = new String("My grandfather picks up quartz and valuable onyx jewels.");
System.out.println(str.length()); // returns the length of the string -> 56
System.out.println(str.substring(3,5)); // returns a segment from the string starting from and index and ending on an index -> "gr"
System.out.println(str.substring(3)); // returns a segment from the string starting from an index and ending at the string's end -> "grandfather picks up quartz and valuable onyx jewels."
System.out.println(str.indexOf("grandfather")); // find where the first occurance of something is and return its index. -> 3
System.out.println(str.indexOf("grandmother")); // Returns -1 if not found -> -1
System.out.println(str.equals("Send 60 dozen quart jars and 12 black pans.")); // returns true if two strings are equal -> false
System.out.println(str.compareTo("Send 60 dozen quart jars and 12 black pans.")); // returns some distance between the two strings using alphabetical comparison -> -6
```
## Arrays
### 1 D Arrays
Arrays allow allow you to store a series of similar data. The elements in an array are indexed by a number starting from 0. An array could represent something like the following. Notice that each element in the array is of the same data type.
| **Index** | 0 | 1 | 2 | 3 |
| -------- | --- | --- | --- | --- |
| **Element** | 3 | 50 | 53 | 7 |
There are a few ways to create an array. A direct declaration uses the syntax `<data type>[] <array name> = {<element 1>, <element 2>, ..., <element n>}`
```java
// declare an integer array
int[] frequencies = {3, 50, 53, 7};
```
One can also create an empty array first. Arrays in Java **cannot be resized**, so we need to define how large the array is from the start. The syntax goes like `<data type>[] <array name> = new <data type>[<array length>]`
```java
// make empty array
int[] frequencies = new int[4];
// then we can asign values to the elements in the array
frequencies[0] = 3
frequencies[1] = 50
frequencies[2] = 53
frequencies[3] = 7
```
Access element at index using `<array name>[<index>]` as in
```java
// print element at index 2 of the array
System.out.println(frequencies[2]); // -> 53
// we can also use the [<index>] notation to change the value of a specific element
frequencies[2] = 54;
System.out.println(frequencies[2]); // -> 54
```
### 2 D Arrays
2D array can be thought of as an array of arrays. It has two levels and is useful for representing two dimensional data.
```java
// creating a 3D array
int[3][4] matrix = new int[3][4];
// direct creation
int[2][2] identity = {{1, 0}, {0, 1}};
// index and change it with two numbers
matrix[1][1] = 10;
```
## ArrayList
ArrayList is a more flexible type of array. It can be resized, and it can store object. ArrayList needs to be imported before they are used with this line of code:
```java
import java.util.ArrayList;
```
An ArrayList can be created like this (using String as datatype and books as variable name):
```java
ArrayList<String> books = new ArrayList<String>();
```
Since an ArrayList instance is an object, it has useful built in methods
```java
// define an ArrayList to be played around
ArrayList<String> books = new ArrayList<String>();
// add an element using the .add(E obj) method. This returns true
books.add("The Egg"); // add a book
books.add("A Murder Mystery"); // add another book
books.add("The Dumb Programmer"); // add another book
// get the size of the ArrayList using the .size() method, which returns an integer
System.out.println(books.size()) // -> 3
// add to a certain index using .add(int index, E obj); this doesn't return anything
books.add(1, "The Great Java Mishap"); // insert book to position 1, while pusing everything behind it up an index
// the .set(int index, E obj) method allows you to change an element at a position; this returns the old object there
books.set(1, "The Great Java Escapade"); // -> "The Great Java Mishap"
// access an element using the .get(int index) method
books.get(1); // -> "The Great Java Escapade"
// use .remove(int index) to remove something at a certain index, shifting elements left to fill the gap, returning the removed element
books.remove(2); // -> "A Murder Mystery"
```
## Inheritance
Inheritance allows you to create a new class by importing features from another class. For example, `CommonwealthBank` could be a **child class** of its **parent class** `Bank`.
The `super()` method refers to the parent constructor, we can use it as part of the constructor in a child class.
How this works in code:
```java
class Bank {
// usual banking stuff
}
class CommonwealthBank extends Bank {
// do everything a Bank does but add special things that CommonwealthBank does.
// construct using the parent constructor
CommonwealthBank() {
super(...);
}
}
```
## Credits
Note contributors (draft, review, edit, etc.):
- Leon Lu
## References
1. https://codingbat.com/java
2. https://runestone.academy/ns/books/published/csawesome
3. https://www.codecademy.com/learn/learn-java
4. https://programmingwithmosh.com/wp-content/uploads/2019/07/Java-Cheat-Sheet.pdf
5. https://apstudents.collegeboard.org/ap/pdf/ap-computer-science-a-java-quick-reference_0.pdf