or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
![image alt](https:// "title") | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | Emoji list | ||
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Syncing
xxxxxxxxxx
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
Any contribution to this note is welcome! You can leave comments on the side, or you can just click on the edit link or the edit button up there↗︎ 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 :).
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 insideSystem
, andprintln()
method is responsible for printing a line of text.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:
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 IDEs (Integrated Development Environment)
A few recommendations:
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 compilehelloWorld.java
, run:You will get a
helloWorld.class
file. This is the compiled code. You can run the compiled file using:Printing
System.out.print();
prints without creating new lineSystem.out.println();
prints and creates new lineComments
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:
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:
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
boolean
to hold true or false valueint
to store integerchar
for one character enclosed by'
sdouble
for decimal numbersbyte
long
short
float
To declare (i.e. create) these variables, use the syntax
<type> <variable name> = <target value>;
as in:One can also declare a variable without assigning a value
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.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:
Constants
If you want to lock a variable so that its value doesn't change, stick the
final
keyword before the declaration.Math Operations
Basics
You can do math with the variables. Some operations include
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.
Increments and Decrements
Even easier to add or subtract 1
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
Notice that we have four major things.
The Fields
String name;
andint 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 thethis
keyword. For example: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:Now we will have an
album
object with its name being"avaJ"
and its rating being1
.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:
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 thethis
keyword to get variables from the instance.The general structure of a method looks like:
<accessibility>
can either beprivate
orpublic
private
methods are accessible only from the classpublic
methods are accessible from any class<return type>
is the data type being returned by the function using thereturn
keywordthis.name
looks likepublic String getName()
<argument type>
and<argument>
specifies the input that the method takesthis.name
method looks likepublic void getName(String newName)
Accessor methods returns field value(s) inside the object, allowing someone to "access" the information inside. Example:
Mutator methods changes the field values inside the object. Example:
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:
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>)
The output looks like:
Dot notation
We can can use
.
to access something inside an object or class. For the album example:The output:
Logical Operations
Comparing stuff
Comparisons yield a boolean output.
Logic stuff
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
shorthand
If else syntax
standard version
shorthand
if else if syntax
standard version
standard version
Loops
While Loop
this runs as long as
condition
is true.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 starti < 5
is the condition for the loop to keep runningi++
is ran after each iterationFor each loop
This goes through every element of an array
Keywords
Use the
break;
statement to jump out of a loopThe Strings Class
As said, String is a fancy object data, it has many methods for making life easier.
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.
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>}
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>]
Access element at index using
<array name>[<index>]
as in2 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.
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:
An ArrayList can be created like this (using String as datatype and books as variable name):
Since an ArrayList instance is an object, it has useful built in methods
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 classBank
.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:
Credits
Note contributors (draft, review, edit, etc.):
References