> Java Rules 1

· How To Use

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.

· Table of Contents

· Introduction

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.

· Parts of Classes

→ Class overview

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 }

→ Names

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.

→ Constructors

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

→ Methods

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

→ MemberData

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

· Inside methods

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.

→ Statement

VariableDeclaration | Assignment | MethodCall | ReturnStatement | CodeBlock

→ VariableDeclaration:

Type name[=expression];

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.

→ Assignment

name=expression;

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;

→ MethodCall

There are two distinct formats to calling methods:

objectExpression.methodName([expression1 [, expression2, ...]]);

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

ClassName.methodName([expression1 [, expression2, ...]]);

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

→ ReturnStatement

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

→ CodeBlock

{ [statements] }

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.

· Types of Variables

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.

→ Type

PrimitiveType | ClassType

→ PrimitiveType

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
Used to store an integer value, positive, negative, or zero.
int cupcakes;
int numGuests = 12;
cupcakes = numGuests;
double
Used to store a decimal point number.  Can be greater, less than, or equal to zero.
double daves;
double numPizzasIAte = 2.5;
daves = numPizzasIAte;
char
Used to store a single character, a - z, A - Z, or punctuation.
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. */

see = c;
boolean
Used to store a truth value, either true or false.
boolean fact;
boolean lie = false;
fact = lie; // 'fact' is now false;
lie = !lie; // 'lie' is now true;
void
Only used as a return type to indicate that the method does not return anything.  You cannot declare a variable of type void.

→ ClassType

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

· Expressions

The last topic that will be covered on this page is expressions.  An expression is anything in Java that has a value.

→ Possible expressions

Variable name
The name of a variable evaluates to the value currently stored in that variable.
int num = 5;
boolean fact = true;
num = num + 5; // num now equals 10.
if(fact) { … } // 'fact' evaluates as true.
Numeric literal
Numbers are expressions.  You can represent integer values or decimal fractions as you normally would.
Very large or very small numbers are written using scientific notation of the form 1.234e56 which is the number 1.234*1056, a rather large number indeed.
int a = 5;
double approxPi = 22/7;
String literal
String literals can be any sequence of characters enclosed in double quotes.
"Hi, mom." is a string literal.
The null keyword
This can be the value for any object type when we don't have a valid object.
String s; // s can't be used for anything yet.
s = null; // s can now be used to compare to other String objects as nothing.
Method call
A method call for any method that returns something other than void is an expression.
public int addition(int a, int b) {
   return a+b;
}
int sum = addition(1,2); // sum equals 3
Operator expression
Java supports different mathematical and logical operators.  Most will join two different expressions.  Some operate on one expression and one uses three expressions.  This is a list that includes most of the ones we are likely to use (so far).

→ List of operators

SymbolNameDescriptionExample codeExample result
=AssignmentSets the left-side variable equal to the right side value.int a;
int b = 2;
a = b;
a is equal to 2.
+AdditionPerforms addition between two numbers.int a=3;
int b=2;
int c=a+b;
c = 5
+ConcatenationCombines 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.
SubtractionPerforms subtraction between two numbers.int a=3;
int b=2;
int c=a-b;
c = 1
*MultiplicationPerforms multiplication between two numbers.int a=3;
int b=2;
int c=a*b;
c = 6
/DivisionPerforms 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
newNewUsed to make a new object of the specified type.
In general, new ClassName([args, if any]);
Dot d = new Dot();
String s = new String("Hello");
d points to a Dot object.
s points to a String object,
 initialized as "Hello".

· Examples

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.

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