zettelkasten

Search IconIcon to open search
Dark ModeDark Mode

Java Notes / AP CSA

#course #programming #computer-science #writing/guide #torefactor

An overlap of an AP course. Java programming as quick as possible.

[version:: 0.3]

H2 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!

H3 A note to contributors

Any contribution to this note is welcome! You can leave comments on the side, or you can just click on this link to edit everything. Note that this file is written in markdown; you can learn the basic syntax here. Your edits will be updated live on the published note here.

Do credit yourself in the Credits section at the very bottom :).

H2 General

H3 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.

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:

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.

H3 Writing Code

There are many tools out there for writing Java code, ranging from lightweight text editors to feature-rich IDEs (Integrated Development Environment)

A few recommendations:

H3 Running Code

Java is a compiler language, meaning that a thing called compiler will turn your Java code into 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:

javac helloWorld.java

You will get a helloWorld.class file. This is the compiled code. You can run the compiled file using:

java helloWorld

H3 Printing

  • System.out.print(); prints without creating new line
  • System.out.println(); prints and creates new line

H2 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:

// 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 /".');

H2 Variables and Data Types

See AP CSP 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.

H3 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:

// 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

// declare without assigning value
int mystery;

H3 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.

// Make a String
String motto = "Don't Panic";

H3 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:

// bad code
boolean dead = "probably";

H3 Constants

If you want to lock a variable so that its value doesn’t change, stick the final keyword before the declaration.

// You can't change this awesome String
final String theTruth = "Only entropy comes easy";

H2 Math Operations

H3 Basics

You can do math with the variables. Some operations include

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)

H3 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.

H3 Self operation

What if you want a variable to operate with itself?—Fancy operators.

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;

H3 Increments and Decrements

Even easier to add or subtract 1

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--;

H2 Class and Objects

H3 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

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.

H4 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:

public class Bank{
	private double asset; // this is a private variable
}

H4 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:

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:

...
	public Album(String name, int rating) {
		...
	}
	public Album(String name) {
		...
	}
...

H4 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:

<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:

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:

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:

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()

H4 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.

H3 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>)

// ... (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:

Album: avaJ
Rating: 1
switching album
Album: tpircSavaJ
Rating: 3

H3 Dot notation

We can can use . to access something inside an object or class. For the album example:

// ... (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:

avaJ

H2 Logical Operations

H3 Comparing stuff

Comparisons yield a boolean output.

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

H3 Logic stuff

// 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;

H4 Order of operation

() -> ! -> && -> ||

If forget, just parenthesis everything.

H3 Control Flow

See AP CSP if you don’t know what this is

H4 If syntax

standard version

if (condition){
	// do something
}

shorthand

if (condition)
	// one line something

H4 If else syntax

standard version

if (condition){
	System.out.println("meow"); // one line statement
} 
else {
	// do something else
}

shorthand

if (condition)
	System.out.println("meow"); // one line statement
else
	System.out.println("meooooow"); // one line statement

H4 if else if syntax

standard version

if (condition1){
	// do something
} else if (condition2) {
	// do something else
} else {
	// if none of them done
}

standard version

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

H2 Loops

H3 While Loop

this runs as long as condition is true.

while (condition) {
  // do something
}

H3 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
for (int i = 0; i < 5; i++) {
	// do something
}

H3 For each loop

This goes through every element of an array

for (int length : lengths) {  
    // do something with the book
}

H3 Keywords

Use the break; statement to jump out of a loop

H2 The Strings Class

As said, String is a fancy object data, it has many methods for making life easier.

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

H2 Arrays

H3 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.

Index0123
Element350537

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>}

// 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>]

// 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

// 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

H3 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.

// 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;

H2 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:

import java.util.ArrayList;

An ArrayList can be created like this (using String as datatype and books as variable name):

ArrayList<String> books = new ArrayList<String>();

Since an ArrayList instance is an object, it has useful built in methods

// 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"

H2 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:

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(...);
	}
}

H2 Credits

Note contributors (draft, review, edit, etc.):

  • Leon Lu

H2 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