In many ways, learning a programming language is like learning a second or third spoken language. It can actually be a little trickier because many of the words in a programming language can look like words from a spoken one, but mean something entirely different.
Obviously, this can be quite alienating, which can make the learning curve on learning your first programming language rather steep. We've put this together this kind of cheat sheet you can use to remind yourself of the basics. Don't feel like you need to read this review through start to finish; use the table of contents below to jump to the section where you need refreshing.
This is a top-down first cut at the rules of Java. This only covers the most basic constructs of the language and how it works. We will add to this over time and build up to get closer to the full language. There are a few things you should know for reading this document. Items that are in italics are defined as one of the elements in the syntax. I have used [square brackets] to denote things that are optional. The exception to this will come with arrays (not in this section) where square brackets are used in the actual Java syntax. I use the vertical pipe — |
(Shift-\) — to signal if something can be one of two or more options.
All of the code we write in Java goes inside classes. Wombat, Leaf, and Dot are all their own class. Classes work like blueprints for making objects. Inside of the class, we put methods, which define what the objects of that class can do, and member data, which defines what objects of that class know/store. The class can also contain constructors, which are special methods that get called when a new object is built from this class. The extends
clause is optional and gets used if this class inherits from another class. In Greenfoot, the classes that we deal with often inherit from Actor or World. This means that they can function as an Actor or a World in the code. (For example, a class that inherits from Actor can be used in any method that takes an Actor as an argument.)
You can also write notes to yourself in the code that don't have to follow proper Java syntax. These are called comments. There are two types of comments in Java. A single line comment is denoted by //
. Anything after the //
on that line is considered a comment. Multiline comments begin with a /*
and end with */
. Everything between those is part of the comment. Comments are ignored by Java so you can write whatever you want in them.
public class
Name [extends
ClassType] {
[Constructors]
[Methods]
[MemberData]
}
Here is a simple little example of a class. This one doesn't do much, but it demonstrates the three things that you can put inside of a class.
public class
SimpleClass {
public
SimpleClass(int
v) { // Constructor
value=v;
}
public int
getValue() { // Method
return
value;
}
private int
value; // Member data
}
Java is fairly flexible about naming. Valid Java names have to start with a letter or underscore followed by any number of letters, underscores, or numbers.
public
ClassName([Type1 name1[,Type2 name2, ...]]) {
[Statements]
}Constructors are written like methods named the same as the class and without a return type (not void
, just nothing). This is called automatically whenever
appears in the code. You can have as many constructors as you like, provided each has a different number and/or type of arguments (thus, the constructor used will depend on what arguments you fill in for new
ClassName(...);ClassName(...)
).
public class
Dot {
public
Dot() {
setImage("blue_dot.png"
);
color = "Blue"
;
positionX = getX();
positionY = getY();
}
private
String color;
private int
positionX;
private int
positionY;
}
public
returnType name([Type1 name1[,Type2 name2, ...]]) {
[Statements]
}This defines a method with the given name. The argument list is in the (parentheses). It is a comma separated list with zero or more type-name pairs. Like constructors, multiple methods may share the same name if they have a different number or types of arguments.
public class
Person {
public void
setDetails(String n) {
name = n;
}
public void
setDetails(int
hgt, int
wid) {
height = hgt;
weight = wid;
}
public
String listDetails() {
System.out.println(name);
System.out.println(height);
System.out.println(weight);
}
private
String name;
private int
height, weight;
}
private
Type name[=expression];This defines a class level variable with the specified name and type. Note that the initial value doesn't have to be specified.
public class
Wombat {
private
String favoriteColor;
private int
numLeavesEaten = 0; // member data; 'private' means it cannot be directly accessed by another class.
}
Constructors and methods (as seen above) have a sequence of statements inside of {curly braces}. As a general rule, curly braces are used in Java to group lines of code. When a method is called in Java, the statements in that method are executed one at a time in order from the top of the method to the bottom. At this point we will only consider five types of statements in Java. So any place that you can have a statement, you can have one of these five. More statement types will be introduced later on.
This declares a variable of the given type with the specified name. You can think of variables as boxes that can hold a value. The box is labeled with the name we give it and it can only hold things of the proper type. What you can have for type is described after all the statement types are introduced.
A variable can only be used in a certain "scope". The scope of a variable runs from the point at which it was declared down to the close curly brace that ends the code block it is declared in. Consider the following example method.
public void
foo() {
int
a=5;
{
int
b=8;
// Point 1
}
// Point 2
}At point 1 you could use either a
or b
. However, the scope of b
is only inside the inner curly braces so you can't use b
at point 2, only a
.
This stores the value of an expression in the variable with the given name. The variable must be in scope. So it either has to be declared in the current method above this line or it should be a class level variable. In order for this to work, the types need to match.
int
three = 3;
boolean
fact = true
;
String cake = "Chocolate"
;
int
nine = three*three;
There are two distinct formats to calling methods:
The objectExpression
is any expression whose type is an object type. The methodName
must be a valid name of a method on that type. The expression is often just the name of a variable, but it can itself be a method call that returns an object.
public class
Maze extends
World {
public void
removeOneWall() {
List<Wall> walls = getObjects(Wall.class
);
removeObject(walls.get(0));
}
}
The second format is used for static
methods. For these we don't need an object, we just put the name of the class in front of the dot. The Greenfoot class has only static methods in it so you call them with a format like Greenfoot.getRandomNumber(3);
.
public class
SomeMath {
public static int
addition(int
a, int
b) {
return
a+b;
}
private static int
FOUR = Math.addition(2,2);
}
return
[expression];This statement stops the execution of a method and returns the value of the specified expression. If the method has a void return type, then there isn't an expression. Otherwise the there must be an expression and the expression type must match the return type of the method or be convertible to it.
// Note: no one in their right mind would ever—ever—write password authentication this way.
public
String matchPassword(String password) {
if
(password.equals("sLiZzaCkS!"
)) {
return
"Password correct! Access granted!"
;
}
else
{
return null
;
}
}
Any place a single statement is expected in Java, it can be replaced by multiple statements inside of curly braces. They don't all have to be on the same line as I have typed it here.
The concept of type has come up at a few points above. Types in Java are basically grouped into two distinct categories: primitive (primitive-type) and object (class-type). We will now look at what those entail.
boolean
| char
| int
| double
| void
These are the only primitive types we will interact with this semester. See the list below for specific details and usages of each primitive type.
int
cupcakes;int
numGuests = 12;double
daves;double
numPizzasIAte = 2.5;char
see;char
c = 'c'
;
/* Notice the single quotes (') around the letter 'c'.
This tells Java that 'c' is a letter and not a variable name. */
true
or false
.boolean
fact;boolean
lie = false
;// 'fact' is now false;
// 'lie' is now true;
void
.This is the name of a class. It can be one that you have written or one that is in an library. Class names typically start with a capital letter and have each new word capitalized. They follow the normal rules for Java names.
String s = new
String("This is a string."
);
The last topic that will be covered on this page is expressions. An expression is anything in Java that has a value.
int
num = 5;
boolean
fact = true
;
num = num + 5; // num now equals 10.
if
(fact) { … } // 'fact' evaluates as true.
int
a = 5;
double
approxPi = 22/7;
"Hi, mom."
is a string literal.null
keywordString s; // s can't be used for anything yet.
s = null
; // s can now be used to compare to other String objects as nothing.
public int
addition(int
a, int
b) {
return
a+b;
}
int
sum = addition(1,2); // sum equals 3
Symbol | Name | Description | Example code | Example result |
---|---|---|---|---|
= | Assignment | Sets the left-side variable equal to the right side value. | int a;int b = 2;a = b; | a is equal to 2. |
+ | Addition | Performs addition between two numbers. | int a=3;int b=2;int c=a+b; | c = 5 |
+ | Concatenation | Combines two strings together. (Looks just like addition.) | String s1="My pants" ;String s2= " are on fire" ;String concat=s1+s2+ "." ; | concat = "My pants are on fire." Notice the leading space on s2. |
– | Subtraction | Performs subtraction between two numbers. | int a=3;int b=2;int c=a-b; | c = 1 |
* | Multiplication | Performs multiplication between two numbers. | int a=3;int b=2;int c=a*b; | c = 6 |
/ | Division | Performs division between two numbers. | double a=3;double b=2;double c=a/b; | c = 1.5 |
% | Modulo (Remainder division) | Returns the remainder of a division operation. | int a=3;int b=2;int c=a%b; | c = 1 |
new | New | Used to make a new object of the specified type. In general,
| Dot d = new Dot();String s = new String("Hello" ); | d points to a Dot object. s points to a String object, initialized as "Hello". |
Now we will run through a few simple examples of code in Java that demonstrate the rules written above. These examples show complete classes. See if you can figure out what they do. If you can't, copy them over into Greenfoot and try running them.
public class
SimpleMath {
public int
addition(int
a, int
b) {
return
a + b;
}
public int
subtraction(int
a, int
b) {
return
a - b;
}
public int
multiplication(int
a, int
b) {
return
a * b;
}
/*
* Note that the argument and return types used here are double.
* If type int was used instead, this operation would not return the decimal part of the answer.
*/
public double
division(double
a, double
b) {
return
a / b;
}
public int
modulo(int
a, int
b) {
return
a % b; // Returns the remainder of a divided by b.
}
public void
printAnswers() {
System.out.println(addition(3,2));
System.out.println(subtraction(3,2));
System.out.println(multiplication(3,2));
System.out.println(division(3,2));
System.out.println(modulo(3,2));
System.out.println(subtraction(addition(multiplication(3,2),2),modulo(3,2));
}
}
/*
* This class creates an actor that moves around the screen.
* Change which method is called in act to get different types of behaviors.
*/
public class
Walker extends
Actor {
public void
act() {
walkLeft();
stepCount=stepCount+1;
}
public void
walkLeft() {
setLocation(getX()-1,getY());
}
public void
walkUp() {
setLocation(getX(),getY()-1);
}
public void
stairStep() {
int
dx=stepCount%2;
int
dy=(stepCount+1)%2;
setLocation(getX()+dx,getY()+dy);
}
public void
walkInRectangle() {
int
dx=((dir+1)%2)*(dir-1);
int
dy=(dir%2)*(dir-2);
setLocation(getX()+dx,getY()+dy);
dir=(dir+stepCount/5)%4;
stepCount=stepCount%5;
}
private int
stepCount=0;
private int
dir;
}
public class
BankAccount {
// This first method is a constructor
public
BankAccount(String n) {
name=n;
}
public void
deposit(int
dollars,int
change) {
cents=cents+(100*dollars+change);
}
public void
withdraw(int
dollars,int
change) {
cents=cents-(100*dollars+change);
}
public int
getBalance() {
return
cents;
}
public
String getFormattedBalance() {
return
"$"
+(cents/100)+"."
+(cents%100);
}
private
String name;
private int
cents;
}