TeachAPCS Microtext

Read and contribute to one of the largest, open-source resources for the AP Computer Science course.


Java

Java is a computer language that a now-defunct Silicon Valley company called Sun Microsystems first released in 1995. Like a spoken language, Java has its own vocabulary and syntax.

Java is based on English so, if you can read English, you can read Java. Its syntax rules are pickier though; it expects every statement to end with a ; and all parens (( and )) and brackets ({ and }) must match. Other computer languages aren't this demanding.

The programmers who wrote Java might say these strict rules make it easier to write legible word and spot errors. Other people think it's just tedious. We'll let you decide how you like Java's syntax rules.

Other resources


ints

ints are whole numbers, or integers, in Java, like 2, -39, or 19391.

Assigning an int to a variable works like this:

int i = 5;
int j = 30395;
int k = -4;

Java stores those values exactly in the computer's memory. FIXME note about bits/bytes/size params?

Other resources


Range of ints

Java can't store every whole number; it can only store ints that fall within a certain range: -2,147,483,648 to 2,147,483,647.

Rather than memorize those numbers, Java proides two constants, Integer.MAX_VALUE and Integer.MIN_VALUE, you can use:

Integer.MIN_VALUE-2147483648
Integer.MAX_VALUE2147483647

doubles

Java calls real numbers, like 3.1415, 4440.31, or 1.6e4, doubles.

When you write doubles, you can use numbers, one decimal place, and scientific notation (like 1.6e4) but can't use commas, percentages, dollar signs, hashmarks, or other non-numeric symbols.

Assigning a double to a variable works like this:

double d = 49592.34;
double e = -0.494;
double f = d + e;

Other resources


Storing doubles

The double type is named after "double precision floating-point numbers," which is a format describing how the computer should store numbers in its memory.

When you assign a real number to a double variable, Java puts in 8 bytes' worth of information. Everything else is dropped.

Though that sounds a little crazy – Java cuts off the number? – it's really that we've programmed computers to act like we do.

What's 1/3 as a decimal? 0.3333333 ... right? Like humans, the computer ran out of space to track all those trailing 3s, so it cuts them off after 8 bytes, hoping that's precise enough for you.

Other resources

  • Berkeley Computer Science: Detailed lecture notes on the IEEE Standard 754 for Binary Floating-Point Arithmetic from 1997
  • Wikipedia: Double-precision floating-point format

NaN

NaN stands for "not a number," and it's what Java returns when a value isn't defined.

You'll run into NaN if you try to do something that's mathematically illegal, like divide by 0.


Casting

Converting between two different data types is called casting, and it looks like this in practice:

(int) 11.0           // = 11
(int) 11.84          // = 11
(double) 11          // = 11.0
(double) 11/2        // = 5.5

Or this generally:

(type) value

Casting has to do with how the computer stores information; it's basically your way of telling the computer "yes, I know I'm changing the type and storing less information here. That's OK."

If you want the computer to store more information than it had been, as when you convert an int to a double, you don't need to cast: the computer simply keeps what you had and appends whatever specificity it needs:

int i = 94;
double d = i;
d;                  // d = 94.0

If you want to store less information, like going from a double to an int, you need to tell the computer you understand you're dropping information – you need to cast.

double d = 94.19;
int i = (int) d;
i;                  // i = 94

Writing (int) is the cast: it's shorthand for "make whatever is on the right of the parentheses into an int."

If you try the same calculation without a cast:

double d = 94.19;
int i = d;
ERROR: Type mismatch: cannot convert from double to int

Java will throw an error because it wants you to be really, really sure you're okay with losing information.

Here's a few other examples:

n(int) n(double) n
444.0
12.91212.9
10/333.333333
2.5 * 12 2727.5

Other resources


Math operators

Java provides five math operators, familiar from mathematics:

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder of integer/floating point division)

Addition, subtraction, and multiplication

Addition, subtraction, and multiplication work like you've seen elsewhere:

2 + 5 = 7
5.2 + 8.1 = 13.3
4 - (-2) = 6
13.23 - 1.179 = 12.051
10 * 8 = 80
4.82 * 4 = 19.28

Division

Division can be trickier because if you're dividing two ints, the answer will also be an int, a whole number. (The decimal is cut off.) If at least one of the numbers is a double, your answer will also be a double.

11 / 2 = 5
// int division; the 0.666666.. is dropped

11.0 / 3 = 3.66666666..
11 / 3.0 = 3.66666666..

Modulus

The modulus operator returns the remainder of dividing the first number by the second:

10 % 3 = 1
20 % 2 = 0
1 % 3 = 1
25.5 % 2.25 = 0.75

Other resources


Order of operations

Math in computer science follows the rules you already know about the order in which calculations should be performed:

  1. First, do things in parentheses
  2. Then, calculate the exponents
  3. Multiply, divide, and modulo afterward
  4. Finally, add and subtract
  5. Cast at the very end.

For example:

2 + 5 * 2               // 12
2 + 8 * 4 % 6 - 4       // 30
5 + 36 % 6 - 10         // 1
(5 + 6) / (11 - 9.0)    // 5.5
(double)(3/4)           // 0.0

Other resources


Operator shorthand

Increment and decrement operators are two special assignment operators that are used to add and subtract 1 from a number. (Why do we care so much about adding and subtracting by 1? They're often used in loops, which we'll look at soon.)

First, increment operators. The following four statements are equivalent:

Increment and decrement operators – assignment shortcuts n = n + 1; n += 1; ++n; n++;

The ++ operator, like the others we've seen, returns a value: the value of n, incremented by 1. Take a look at this example:

int n = 4;
n
4
n+= 2;
n
6
n++;
n
7

Similarly, the following four statements are equivalent: n = n - 1; n -= 1; --n; n--;

Putting the ++ in front (e.g. ++n) is called prefix notation, and putting it at the back (e.g. n++) is called postfix notation. ++ is an operator just like + and it changes the variable's value wherever it's placed. Try this:

int x = 1;
int y = x++;
y;
1
x;
2

int x = 1;
int y = ++x;
y;
2
x;
2

At the end of each block, x is equal to 2, but y is equal to either 1 or 2 depending on where the ++ operator was placed. In the first example, the second line says "give y the value of x, and then increment x" while the second line of the second example says "increment x and give y that new value."


Math class

Java's Math class contains data and procedures helpful when we perform mathematics. You can read all about the Math class in the official Java documentation.

Functions

Here's a few functions built-in to the Math class that might be helpful:

Absolute value

Math.abs(int x) and Math.abs(double x) returns the absolute value of x:

Math.abs(4);             // 4
Math.abs(-98.88);        // 98.88

Exponents

Math.pow(double b, double c) raises b to the c power:

Math.pow(2, 4);         // 16.0
Math.pow(4.4, 1.1);     // 5.102675423469089

Square roots

Math.sqrt(double x) returns the square root of x:

Math.sqrt(16);          // 4.0
Math.sqrt(33.5);        // 5.787918451395113
Math.sqrt(-25.0);       // NaN

If you take the square root of a negative number, Java returns NaN, shorthand for "not a number."

Rounding

Math.round(double x) return the value of x, rounded to the nearest whole number.

Math.round(4.3);        // 4.0
Math.round(-2.4);       // -2.0
Math.round(8904.5);     // 8905.5

Rounding up

Math.ceil(double x) returns the next whole number that's larger than x:

Math.ceil(49.0);        // 49.0
Math.ceil(4.29);        // 5.0
Math.ceil(-85.9);       // -85.0

Rounding down

Math.floor(double x) returns the prior whole number that's smaller than x:

Math.floor(49.0);       // 49.0
Math.floor(4.29);       // 4.0
Math.floor(-85.9);      // -86.0

Finding a smaller value

Both Math.min(double a, double b) and Math.min(int a, int b) return the smaller of a and b:

Math.min(4.3, 2.4);         // 2.4
Math.min(-2.01,-5.4);       // -5.4
Math.min(4, 2);             // 2
Math.min(-2,-5);            // -5

Finding a larger value

Both Math.max(double a, double b) and Math.max(int a, int b) return the smaller of a and b:

Math.max(4.3, 2.4);         // 4.3
Math.max(-2.01,-5.4);       // -2.01
Math.max(4, 2);             // 4
Math.max(-2,-5);            // -2

Random numbers

Math.random() returns a random double between 0 (inclusive) and 1 (exclusive.) It's the same as Random gen = new Random(); gen.nextDouble(); from the Random class:

Math.random();      // 0.753596711450498
Math.random();      // 0.35743909737853485
Math.random();      // 0.1801937322144781

Variables

Java's Math class also has a few constants that might be useful:

e

E returns the value of e, the base of natural logarithms:

Math.E;             //  2.71828

Pi

PI returns the value of pi:

Math.PI;            // 3.141592653589793

Other resources


Casts and division

Casting becomes more important when we're doing math problems because Java's got two ways of doing division:

  1. Floating point division
  2. Integer division

Floating point division

Floating point division is the division you know:

3.0/4           // = 0.75
5/4.0           // = 1.25
1.0/4           // = 0.25

Integer division

Integer division is a special kind of division that computers can do. In integer division, all answers are integers (whole numbers), and any decimals are dropped.

3/4           // = 0
5/4           // = 1
1/4           // = 0

Using each

Integer division happens when all the numbers being divided are integers. Floating point division's used when at least one number's a double.

You can also force floating point division with casts. Just keep in mind the order of operations!

(double) 3/4       // = 0.75
(double) 5/4       // = 1
(double) (1/4)     // = 0.0 because integer division came before the cast

Random numbers

Sometimes when programming, we might want to use random numbers:

  • simulate a dice roll as we're building a game
  • ask the computer to choose a word from a list
  • "flip" a coin and give the result as heads or tails
  • ...

Java's Random class provides tools to make pseudo-random numbers.

Using the Random class

To use the Random class in your program, import java.util.random at the top.

import java.util.random

Making a random generator

In programming, "random" numbers come from random number generators. We can make a generator by making a new Random object:

Random generator = new Random();

It's common to call the Random object generator or gen, but like all other variables, you can call it whatever you like.

Getting random numbers

Your generator can produce random numbers in a few different ways:

Random integers (whole numbers)

nextInt(int n): returns a randomly-selected integer between [0, n-1]. For example, nextInt(10) will return an integer between 0 and 9, inclusive.

generator.nextInt(10);
9
generator.nextInt(10);
7

Random doubles (real numbers)

nextDouble(): returns a randomly-selected double d between 0 (inclusive) and 1 (exclusive), so that 0 <= d < 1

generator.nextDouble();
0.2488107901176655
generator.nextDouble();
0.09949381836031079

Random integers continued (amongst "all" whole numbers)

nextInt(): returns an integer between [Integer.MINVALUE, Integer.MAX

VALUE]
generator.nextInt();
49370236
generator.nextInt();
-22997583

The official Java documentation have information for the Random class' other methods.

Other resources


Using random numbers

Sometimes, we'll use the nextInt(int n) or nextDouble() on its own; other times, we'll need to translate what they give back to a range that's useful.

For example, say you want to pick a random whole number between 0 and 100:

Random gen = new Random();
int i = gen.nextInt(101);

Or you could do it this way:

Random gen = new Random();
double d = gen.nextDouble() * 100;
int i = (int) d;

Or, maybe you're building a dice game, and you need to make and roll a six-sided die in your program:

Random gen = new Random();
int die = gen.nextInt(6) + 1;

Perhaps you're making a program that randomly assigns students test scores (the horror!) between 60 and 100, inclusive of both:

Random gen = new Random();
int i = 60 + gen.nextInt(41);

Sequences of random numbers

If you need more than one random number, use a for loop:

import java.util.Random

...

Random generator = new Random();
for(int i = 0; i < 100; i++){
    int r = 60 + gen.nextInt(41);
    System.out.println(r);
}

93
73
68
85
99
...

booleans

A boolean stores the result of a logical comparison and can take on one of two values: true or false.

Booleans were named after the nineteenth-century mathematician George Boole, who devised an arithmetic system based on the logic of true and false properties.

Booleans help us store a statement's truth or falsehood in a standard way. We evaluate true or false expressions everyday: "do I have my housekeys?" "Should I carry an umbrella?" "Have I called mom yet?"

Creating a boolean

Create a boolean by giving a boolean variable a true or false value:

boolean b = true;
boolean c = (5 < 4);        // c is false
boolean e;                  // e doesn't yet have a value, but it's been initliazed

Comparing booleans

Two booleans are equal if they have the same value; that is, if they are both true or both false. For example:

true == true;                   // true
false == true;                  // false
false != true;                  // true

Values

Suppose we have int x = 4 and int y = 12. What can we say about the following statements?

boolean b = x > y;              
// false, because 4 isn't larger than 12
boolean c = x == y;             
// false, because 4 isn't equal to 12
boolean d = y > x;              
// true, because 12 is greater than 4

Booleans can also be written with more complicated expressions:

boolean e = (20 - 10) > (9 * 1)  // true
boolean f = (39 - 30) * 9 != 81 // false

Other resources


Boolean operators

Relational operators

Booleans respect relational operators:

Operator Example Meaning
< 5 < 10 "5 is less than 10"
> 10 > 7 "10 is greater than 7"
<= 5 <= 10 "5 is less than or equal to 10"
>= 10 >= 7 "10 is greater than or equal to 7"
== 7 == 7 "7 is equal to 7"
!= 8 != 10 "8 is not equal to 10"

Boolean operators

Boolean operators allow you to express statements that combine pieces together.In English, we use words like AND, OR, IS and NOT to do this:

  • "It is raining today and you should carry an umbrella."
  • "I am full or the refridgerator is empty."
  • "Your house is not the same as my house, and mine is better."

Boolean operators replace those words with keywords the computer can understand:

Operator Example Translation
&& rain == true && umbrella == true "It's raining today and you should carry an umbrella"
|| full == true || emptyRefridgerator == true "I am full or the refridgerator is empty."
! yourHouse != myHouse && myHouse > yourHouse "Your house is not the same as my house, and mine is better."

Here's a few examples:

Expression Translation Answer
!true "not true" false
!!false "not not-false" true
!(2 == 2) "2 isn't equal to 2" false
7 > 4 && 8 > 34 "7 is greater than four and 8 is greater than 34" false
7 > 4 || 8 > 34 "7 is greater than four or 8 is greater than 34" true

Other resources


Boolean operator precedence

Boolean operators, like mathematical ones, have an order of operations. When you're solving a boolean expression, follow this ordering:

  1. !
  2. ( and )
  3. == and !=
  4. &&
  5. ||
  6. The relational operators and arithmetic operators.

Let's test that with a few more boolean expressions:

Original Simplified Answer
!true || false false || false false
true || false && true true || false true
true == false && false true == false false
true != false || true true != true false

Other resources


Truth tables

Truth tables are tools to generalize a logic expression, even as its arguments change.

Here's the process behind making a truth table for the && operator:

boolean a = true;
boolean b = true;
a && b;                     // true

a = true;
b = false;
a && b;                     // false

a = false;
b = false;
a && b;                     // false

a = false, b = true;
a && b;                     // false

If we put that information into a table, we get a truth table:

a b (a && b)
true true true
true false false
false true false
false false false

From the truth table, it's easier to see that (a && b) is true only if both a and b are true.

Here's the truth table for (a || b):

a b (a || b)
true true true
true false true
false true true
false false false

(a || b) is true more often than (a && b), as the || operator is more forgiving; only one of a and b are true in order for the entire expression to be true.

Every expression has a truth table. For example, here's one for (!a || b && c):

a b c (!a || b && c)
true true true true
true true false false
true false true false
true false false false
false true true true
false true false true
false false true true
false false false false

Other resources


Strings

A String is a piece of text in Java, and it gets its name from the way it "strings together" letters or numbers.

Strings are one of Java's main data types; unlike other data types, Strings are Objects, not primitives.

Strings are stored as sequences of characters. For example:

String name = "Hi!";

creates a new String called name made up of the characters "H", "i", and "!"

Other resources


Constructing a String

To make a string, you can enclose text on the same line in double quotation marks (" and ") as if they were a primitive:

String favorite = "Computer Science";

Or, you can initialize them as you would an object:

String favorite = new String("Computer Science");

Strings can be empty. Here's two ways to define an empty string:

String empty = "";
String alsoEmpty = new String();

String objects are immutable – there's no way to change them once they've been made – but their references can be reassigned:

String favorite = "Computer Science";
// favorite is "Computer Science"
favorite = "Art History";
// favorite is now "Art History"

The third line reassigns the favorite variable from "Computer Science" to "Art History".

Other resources

  • CodingBat: makeAbba exercise
  • YouTube: String fundamentals
  • YouTube: Making, comparing, measuring, slicing, and searching Strings

String styling

Strings also have a few built-in procedures that let you re-style the characters. Maybe you want to convert all of a String's letters to lower case?

String greeting = "Hello there";
greeting = greeting greeting.toLowerCase();
greeting;
"hello there"

Or upper case?

String greeting = "Hello there";
greeting = greeting.toUpperCase();
greeting;
"HELLO THERE"

Can you write word that assigns the value "New York, NY" to a variable and then store the same value, though in lower case letters, in the same variable?

String city = "New York, NY";
city = city.toLowerCase();
city;
"new york, ny"

What is the output of `"I'm so excited".toUpperCase();"?

"I'm so excited".toUpperCase();
"I'M SO EXCITED"

Concatenating strings

Java uses + to concatenate, or add, strings.

String favorite = "Art History"
favorite = favorite + " is fun!";
favorite                                // "Art History is fun!"

As strings are immutable, concatenation re-assigns the variable's reference rather than changing its value.

String concatenation works so long as all the item's you're assigning can be turned into strings:

String sentence = "My favorite number is ";
int favNum = 3;
String sentence = sentence + favNum;
sentence;                                      // "My favorite number is 3"

Other resources


Measuring strings

Use Java's length() method to measure a string.

Called on: a string

Arguments: None

Returns: the length (number of characters) of the string.

String test = "testing";
test.length();                              // 7
String moreTesting = "testing with spaces!";
moreTesting.length();                       // 20

Other resources


Trimming strings

Getting rid of leading and trailing white space in a string is called "trimming." Trimming strings is often helpful when you work with input from a user of your program.

Called on: the string to be trimmed

Arguments: None

Returns: the string without beginning or trailing white space

Example

String trueSentence = " I have extra spaces! ";
falseSentence = trueSentence.trim();             // "I have extra spaces!";

Strings and characters

Strings are made up of characters, or what Java calls chars. A string's characters are numbered from left to right, starting with 0.

String s = "My phone";
            01234567

In the string "My phone", the M is at index 0, the y at index 1, the at index 2, the p at index 3, etc:

Character M y p h o n e
Index 0 1 2 3 4 5 6 7

Other resources


Replacing parts of Strings

FIXME


Character indices

Use Java's charAt(int) function to find the character at a specifix index.

Called on: a string

Arguments: the index at which you'd like the character

Returns: the character at the index passed as an argument

Example

String book = "handbook";
book.charAt(4);                     // 'b'
book.charAt(0);                     // 'h'

If you pass index that's larger than the string is long, you'll get a StringIndexOutOfBoundsException:

String hello = "Hello!";
hello.charAt(29);
java.lang.StringIndexOutOfBoundsException: String index out of range: 29

Other resources


Searching strings

Use Java's indexOf(String) or indexOf(String, int) function to find out whether one string contains another.

Called on: the "parent" string

Arguments:

  • the String that might be inside the parent string
  • (optional) the index from which to start searching. Defaults to 0.

Returns: the index of the inner string's first character in the parent string. -1 if the inner string wasn't found.

Example

String str = "Hello world!";

str.indexOf("World");
// Return -1 – searching is case-sensitive
str.indexOf("world");               // Returns 7
str.indexOf("world", 10)            // Returns -1
str.indexOf("hi");                  // Returns -1
str.indexOf("Hello world!");        // Returns 0
str.indexOf("!", 10)                // Returns 12

Other resources


Making strings from strings

When a string is made from another string, it is called a substring.

Java provides two methods to make substrings: substring(int beginIndex) and substring(int beginIndex, int endIndex).

Called on: the "parent" string

Arguments:

  • the index at which to begin searching
  • (optional) the index at which to stop searching. Defaults to the string's last index.

Returns: the substring between beginIndex and endIndex or the word's end.

Examples

String word = "racecar";
word.substring(0);              // "racecar"
word;                           // still "racecar"
word.substring(4);              // "car"
word;                           // still "racecar"
word.substring(0, 4);           // "race"
word;                           // "racecar"

Strings can't be modified, so calling (for example) word.substring(4); above creates and returns a new string ("car") but doesn't change the original string ("racecar").

Saving substrings

To save the substring that gets returned, assign it to a variable:

String jewels = "Diamonds, rubies, and emeralds.";
String shorter = jewels.substring(10,16);
jewels;                             // "Diamonds, rubies, and emeralds.";
shorter;                            // "rubies"

Other resources


equals(String)

.equals is a built in method for the String type.

String a = "Hello"; String b = "Hello";

a.equals(b); //Returns true

When comparing two Strings, use .equals rather than ==

String s4 = new String("Hello"); // String object String s5 = new String("Hello"); // String object

s4 == s5; // false, different pointers in heap s4.equals(s5); // true, same contents

== checks if the object points to the same pointer in memory, so if you want to see if two strings have the same content, use the built in .equals method.

Other resources


String comparisons

compareTo(String) compares to calling String object to the String argument and returns a number indicating which String is first in lexigraphical ordering. (Lexigraphical order is the ordering that dictionaries use: A, B, C, ... X, Y, Z, a, b, c, ... x, y, z.)

Which numbers are returned? 0 if the two strings are equal, "something negative" (<0) if the calling string is larger, and "something positive" (>0) if the argument string is larger.

String mTitle = "Jessica";
String mLower = "jessica";
String sTitle = "Stephanie";
String cTitle = "Amy";

mTitle.compareTo(mTitle);
0
mTitle.compareTo(mLower);
-32
mLower.compareTo(mTitle);
32
cTitle.compareTo(mTitle);
-9
cTitle.compareTo(mLower);
-41
sTitle.compareTo(mTitle);
9
sTitle.compareTo(mLower);
-23

Other resources


Escaping strings

Since we denote strings with double quotes (" and "), we need to do something special to save a string with double quotes:

String question = "Which is your \"favorite\" number?";

A backslash escapes a " character. "Escaping" means treating the " as a normal character, rather than as part of the programming language.

What if we want to include include a backslash in our string? By using another backslash to anti-escape the first! For example:

String sentence = "A backslash looks like this: \\.";
sentence;                       // "A backslash looks like this: \."

Strings and new lines

\ escapes quotation marks. Simiarly, \n will create a new line:

String broke = "Here's one line.`\nAnd here's another.";
broke;
"Here's one line.
And here's another."

Printing

When programming, it is useful to print information to the terminal screen/console output window.

Here is a basic example of printing to the screen:

System.out.println("Hello World!");         // prints Hello World! on its own line

The System part of the statement accesses all of the methods/classes associated with the System class. The out part accesses all of the methods/classes related to output. println is a method contained in System.out. It is abbreviated and stands for "Print Line," or "print the following information and then a new line."

The new line comes from outputing a \n, or newline character, which is like pressing enter on your keyboard. You can use the System.out.print method if you do not want to print a newline character by default, like this:

System.out.print("Hello World!");           // prints Hello World! on the line

You might use a print statement if your program takes an integer dollarAmount from the user, then prints the final amount with sales tax / meals tax to the screen.

Other resources

  • YouTube: Input, output, and errors
  • YouTube: Printing Strings and escape characters

return

WRITEME


Reading ints

WRITEME


Reading ints

WRITEME


Declaring variables

Multiple variables can be declared on one line if you'd like to save space. For example:

int first = 5, second;
first;                                      //    5
second;                                     // Uninitialized
second = 10;
second;                                     // 10
int sum = first + second;
sum;                                        // 15

Above, we declared the variables first and second on the same line, but we only initialized first with a value – in this case, the value 5. Though second is a valid variable, it didn't have a value until line 6, which is why the interpreter yelled when we asked it to evaluate its non-existent value on line 4. On line 9, we declared a variable called sum and initialized it with a value – the sum of the values of the variables first and second, which happened to evaluate to 15.

Variables can only have one value at once, but which value they have can change (or vary). For example:

number                                         // 4
number = 10
number                                         // 10

Now, whenever you type number, you'll get back 10, because that's the variable's current value. You might notice we didn't have to tell the interpreter that our number variable is an integer this time. That's because we told the interpreter that number was an integer before, and the interpreter remembered that.


Re-assigning variables

If you're using the variable's value to set the new value, you can shorten the statement

int age = 17;
age = age + 5;              // Age = 22

to

age += 5;                    // Now, age = 22

+= is shorthand for "increment the old value of age by 5 and store the new value in age."

Java has similar assignment operators for the other operations:

OperatorMeaningx before
int x=5;
x after
+=adds and reassignsx+= 510
-=subtracts and reassignsx-= 50
*=multiplies and reassignsx*= 525
/=divides and reassignsx/= 51
%=divides and reassigns the remainderx%= 50

Initializing variables

Java is a strongly typed programming language. This means that every variable must have a data type associated with it. For example, a variable could be declared as one of the eight primitive data types: A byte, short, int, float, double, char, or bool.

You can think of a variable like a container. When we declare variables in Java, we attach a Label to the container. To declare a variable in Java, all that is needed is the data type followed by the variable name:

int thisIsMyIntegerVariable;

In the above example, a variable called "thisIsMyIntegerVariable" has been declared with a data type int. The line ends in a semi-colon. The semi-colon tells the Java compiler that the declaration is complete.


Functions introduction

Functions are ways to group several statements together. Grouping statements into methods could save you time when programming and make your program more legible.

Here's an example of a method. This one adds 2 to whatever it's passed:

addsTwo(int initial){
    return initial + 2;
}

Like math, in programming, functions don't do anything on their own; they just sit there, waiting to be used.

Sometimes in computer science, people say "call a method" to mean "use a function." The two phrasings are equivalent. To call a method, simple write its name and pass it the necessary parameters:

addsTwo(5);         // returns 7
addsTwo(0);         // returns 2
addsTwo(-3);        // returns -1

Calling the addsTwo method made the computer jump into action and run our statement.

Other resources


General form of functions

The general form of any Java function looks like:

<visibility> <returnType> <functionName> (<type parameterName>, <type parameterName> ...){
}

Here's a a more concrete example:

public int addTwo(int favNumber){
    return favNumber + 2;
}

Which could be used like this:

int myNum = 4;
newNum = addTwo(myNum);         // Now, newNum = 6

Let's go through each piece of the general form:

<visibility>

Tells us which objects can call, or use, this method. It can be one of the following keywords:

  • public: all objects can call this method
  • protected: all objects in this class or its subclasses can access this method
  • private: only objects in this class can access the method

Visibility is optional. If you don't specify it, Java defaults to packaged private, meaning it's visible to all classes in the same package

<returnType>

Tells us what type this method will give back. It can be:

  • void
  • int
  • double
  • boolean
  • String
  • Object
  • Or any custom object that you define

<functionName>

What we're calling this function. You can use whatever you like, though it's convention (and helpful to people who might read your code) to choose a verb that describes what the method does.

<parameterList>

A comma-separated list of the parameters the method will use, e.g. int favNum or boolean willRain.


Method signature

The general form of a method signature is:

<methodName>(<parameterTypeList>)

Examples of method signatures are:

celsiusTempConverted(int)
celsiusTempConverted(double)
turnLeft()
turnDegrees(int)
numberTripled(int)

Method names can be the same, but method signatures – the name and the parameter type(s) – must be different.

If a method name takes different parameters, we say that method has been overloaded.


Variable scope

When we're writing functions, we can declare and use variables wherever we like. Consider this example and output:

int test = 10;

public void mainTest(){
    System.out.println("Main test: " + test);
}

public void localTest(){
    int test = 20;
    System.out.println("Local test: " + test);
}

public void paramTest(int test){
    System.out.println("Param test: " + test);
}

public void paramTestFail(int test){
    int test = 4;           // ERROR: duplicate local variable test
    System.out.println("Param test: " + test);
}

mainTest();
Main test: 10
localTest();
Local test: 20
paramTest(30);
Param test: 30

What's happening?

  • Within the scope of the script we've written, test has a value of 10, which was assigned at the top of the script.
  • Within the function localTest(), test has a value of 20, because the int test = 20; assignment supercedes the int test = 10; one performed outside the function.
  • Within the function paramTest, the variable test refers to the function parameter, and it takes on whichever value it's passed. (In this case, it's 30.)
  • The last function, paramTestFail(int), wouldn't compile. Instead, you'll see the error message "duplicate local variable test", which means the compiler's gotten confused by having two int tests. You'll have to rename one of the variables.

Other resources


Returning from methods

public double fahrenheitTempConverted(double celsiusTemp){
    double degreesFahrenheit = 9/5 * celsiusTemp + 32;
    return degreesFahrenheit;
}

Let's step through this word by word:

  • public is the access specifier, and it determines which objects can call the fahrenheitTempConverted function. There's several access specifiers, but for now: public means "anyone can use this function."
  • double is the type of the "thing" the method returns; it's the method's return type. This is just a warning though; to return something from the method, we need to include a return <data> statement somewhere in the method. Otherwise, we'll get a compiler error.
  • fahrenheitTempConverted is the method's name.
  • (double celsiusTemp) is the parameter list. The parameter list is always surrounded by parentheses, and the list's items are separated by commas. If the list is empty, the parentheses remain: (). Parameters are variables, defined only in that method. They're often used to pass information to the function.
  • double degreesFahrenheit = 9/5 * celsiusTemp + 32; and return degreesFahrenheit; is the method body. Each line ends with a semicolon (;) and is a complete Java statement. The method body is surrounded by curly braces.
  • return is a Java keyword that means "send back whatever is on this line." Since we declared the method's return type to be a double, Java expects that whatever follows the return keyword to be a double.

Function visibility

* WRITEME *

Other resources


Overloading methods

Imagine we had two methods to convert a temperature from degrees fahrenheit to degrees celsius. One took in an int and the other a double:

celsiusTempConverted(int degreesF){
    // converted a temperature, stored as an int in degrees fahrenheit, to celsius.
}
celsiusTempConverted(double){
    // converted a temperature, stored as a doubel in degrees fahrenheit, to celsius.
}

This is legal Java; method names can be the same (as these are, celsiusTempConverted) but method signatures – the name and the parameter type(s) – must be different.

If a method name takes different parameters, like celsiusTempConverted above, we say that method has been overloaded. The Java complier uses the parameter types to tell apart overloaded methods. For example:

celsiusTempConverted(32);         // calls the celsiusTempConverted(int) method
celsiusTempConverted(32.3);       // calls the celsiusTempConverted(double) method

Or, more verbose: when you call celsiusTempConverted(32), the Java compiler scans over the methods it can see, looking for something in the format celsiusTempConverted(int). When it finds a match, it calls that method with the parameter you passed (in this case, 32.)

Method signatures don't consider return types, which means you can't have two methods with the same name, same parameters, and different return types. This, for example, would result in a compiler error:

int celsiusTempConverted(int);
double celsiusTempConverted(int);

because Java would interpret both of their signatures as:

celsiusTempConverted(int);

and wouldn't know which to use.

Other resources


Arrays

Arrays are a way to save several pieces of data together.

Let's say we wanted to store a week's worth of temperatures. We could do it with a bunch of variables:

int day1 = 77;
int day2 = 72;
int day3 = 74;
int day4 = 68;
int day5 = 71;
...

But that gets old pretty quickly.

Instead, we can use an array to store all those temperatures at once:

int temps[] = new int[6];
temps[0] = 77;
temps[1] = 72;
temps[2] = 74;
temps[3] = 68;
temps[4] = 71;
...

To retrieve one of the temperature variables, we use the variable name and its index:

temp[0];            // returns 77
temp[4];            // returns 71

As array indices start counting from 0, a seven-item array has indicies 0, 1, 2, 3, 4, 5, and 6 – but not 7!

Other resources


Making arrays

The easiest way to make an array is by enclosing its values in squiggly brackets ({ and }), separated by commas:

int a[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
boolean b[] = {true, false, false};

Arrays can also be made by:

  1. Slowly listing out all the variables, index by index:
    int a[] = new int[10];
            a[0] = 0;
            a[1] = 1;
            a[2] = 1;
            ...
            
  2. Combining the squiggly-bracket shorthand and the new syntax:
    int a[] = new int[]{0, 1, 1, 2, 3, 5, 8};
            

All three are equivalent ways of making an array.


Length of arrays

Arrays remember their own length, which saves you from having to count each element. Each array has a instance variable length:

String[] names = new String[25];
names.length;               // returns 25

An array's .length is a variable, not a method, so you don't need parentheses to use it.


ArrayLists

ArrayLists are another way to store sets of data together.

WRITEME


Adding to an ArrayList

Use the void add(Object o) method to add an Object to an ArrayList.

For example:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("Goodbye");

produces an ArrayList called myList that looks like ["Hello", "Goodbye"]


Inserting into an ArrayList

If there's a particular place, or an index, you'd like to put an item in your ArrayList, you can use the void add(int index, Object o) method.

For example:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("Goodbye");
myList.insert(1, "Hiya");

produces an ArrayList called myList that looks like ["Hello", "Hiya", "Goodbye"] – the "Hiya" string was inserted into the second position (index 1), and everything after was shifted one to the left.


Getting from an ArrayList

To retrieve an item from a particular index of an arraylist, use the Object get(int index) method:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("Goodbye");
myList.get(1);      // will return the String "Goodbye"

From the code above, the ArrayList stored in the myList variable looks like ["Hello", "Goodbye"]. So myList.get(1) will return the String at index 1 (in this case "Goodbye") without changing the list itself.


Removing from an ArrayList

To remove an item at a particular index in an arraylist, use the Object remove(int index) method.

Let's say we set up a list that will look like ["Hello", "Goodbye"]:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("Goodbye");

Now, let's remove the element at index 1:

myList.remove(1);       // Will return the String "Goodbye"

myList will be only ["Hello"].

If we wanted to save the String we removed, we could do that too:

String gone = myList.remove(1);         // Now, gone refers to "Goodbye"

Setting values in an ArrayList

Setting a value in an ArrayList performs an overwrite: it combines an addition and removal.

For example:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("Goodbye");
myList.add("Hi");

produces an ArrayList called myList that looks like ["Hello", "Goodbye", "Hi"]. Now, lets set "Hiya" in index 1:

myList.set(1, "Hiya");

Now, myList looks like ["Hello", "Hiya", "Hi"] – the "Hiya" string was inserted into the second position (index 1), overwriting the "Goodbye" that was there.


ArrayList size

ArrayLists have an int size() method that returns the number of items in the list.

For example:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("Goodbye");
myList.add("Hi");
myList.size();          // returns 3

ArrayList emptiness

ArrayLists have a boolean isEmpty() method that returns true if there's no items in the list.

For example:

ArrayList<String> myList = new ArrayList<String>();
myList.isEmpty();             // returns true
myList.add("Hello");
myList.isEmpty();             // returns false

Clearing an ArrayList

ArrayLists have a void clear() method that removes all the items in the list.

For example:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("Goodbye");

After that code, myList looks like ["Hello", "Goodbye"]

myList.clear();

Now, after clearing the list, myList is empty: ["Hello", "Goodbye"]


Conditional expressions

Conditional expressions allow our code to do different things based on a prior result.

It's like the logic we use every day: "it's cold, so I'll put on a coat"; "if you're running late, text your friend"; "if you're hungry, eat something; otherwise, go outside." In programming, those are known as if-else statements.

We also take repetitive actions. Some of those have an indeterminate end, e.g. "while I'd like to walk, move the left foot, then the right foot, then the left foot .. ", while others have a pre-defined stopping point: "read 2 chapters of the book" or "drive straight for 6 blocks and then turn left."

In programming, the former are mimiced with while loops and the latter with for loops.

Other resources


If-else statements

if and if ... else statements give simple instructions:

if (/* It's cold outside */){
    /* Put on a coat */
}

or

double temperature = 45.3;
if (temperature < 50.0){
    putOnACoat();
}

else statements are used if you want to do something else:

double temperature = 45.3; 
if (temperature < 50.0){
    putOnACoat();
}else{
    goOutside();
}

More generally, if-else statements look like:

if (<expression>){
    <statement>;
}else{
    <otherStatement>;
}

and can include as many "layers" of else ifs as you'd like:

if (<expression>){
    <statement>;
}else if(<otherExpression>){
    <otherStatement>;
}else{
    <anotherStatement>;
}

The <expression> inside the if or else if parentheses should evaluate to either true or false. Think of converting the Java-ish to English as you read it: "if true" or "if x equals 4" makes more sense than, "if 4."

Other resources


Using if-else statements

Here's an if-else statement used in a card-playing program:

import java.util.Random;
...
int HEARTS = 0, DIAMONDS = 1, SPADES = 2, CLUBS = 3;
Random gen = new Random();
int card = gen.nextInt(4);

if(card == HEARTS || card = DIAMONDS){
    System.out.println("You drew a red card!");
}else if(card == SPADES){
    System.out.println("You drew a spade!");
}else if (card == CLUBS){
    System.out.println("You drew a club!");
}

Java only executes the code nested underneath the first true statement. In other words, if the card variable is equal to 0 or 1, it'll print only the statement about drawing a red card; if it's equal to 2, it'll print only the statement about spades, and if it's equal to 3, you'll only see the statement about a club.

Nested if-else statements

You can nest if-else statements too, which can be helpful:

/*  We have two ints, grade (a student's most recent test score) and age (a student's age.)  */

if (grade >= 85){
    if (age >= 18){
        System.out.println("My grade is high, and I'm an adult.");
    }else{
        System.out.println("My grade is high, but I'm not an adult.");
    }
}else{
    System.out.println("My grade is not high.");
}

Longer statements

The statements inside the if blocks can be as many lines as you'd like:

if (<expression>){
    <statement>;
    <anotherStatement>;
    <aThirdStatement>;
}else{
    <statement>;
}

Shorter statements

For short (one line) if-else statements, Java gives you a shorthand:

(condition) ? statementIfTrue : statementIfFalse;

The shorthand is useful when assigning variables:

int a = 5, int b = 4;
int max = (a > b) ? a : b;

or inside a function:

public int max(int a, int b){
    return (a > b) ? a : b;
}

for loops

For loops tell the computer to do something for a set of a variable's values. They're particularly useful when we want the same "thing" done several times in succession.

Let's say, for example, we wanted to print out the numbers 0-5 in order. We could do that with several System.out.println() statement:

System.out.println(0);              //      0
System.out.println(1);              //      1
System.out.println(2);              //      2
System.out.println(3);              //      3
System.out.println(4);              //      4
System.out.println(5);              //      5

But this manual work is precisely the sort of thing for which a computer is well suited.

Here's some code that prints the whole numbers between 1 and 5, inclusive, using a for loop:

for(int i = 0; i < 6; i++){
    System.out.println(i);
}

0
1
2
3
4
5

Here's the general form of a for loop:

for(<initializing>; <control>; <step>){
    <statement>;
}

Let's look at the three pieces in the for loop's parentheses:

  1. Initializing, e.g. int i = 0, is where the counter starts. The variable can be of any type, called anything, and start with any value, though ints called i or j are standard choices.
  2. Control, e.g. i < 6, is a boolean statement that tells us how long to continue the loop. We continue so long as this statement is true. (In this case, as long as i is less than 6.) If you write a control statement that never becomes false, your loop will continue forever – or, at least, until it crashes your program.
  3. Step, e.g. i++, is how we change the value of i after all the code that's in the loop has executed. Even though the step expression appears before the statements inside the loop, the stuff inside the loop is executed first.

All for loops can be re-written as while loops. For example, our for loop above can be re-written as:

int i = 0;
while(i < 6){
    System.out.println(i);
    i++;
}

Other resources


Step expressions

The step expression can be anything that increments or decrements the variable.Here's a few examples

// This loop prints whole numbers between 6 and 1 in descending order
for(int i = 6; i > 0; i--){
    System.out.println(i);
}

// This loop counts up from 0 to 5 using only even numbers
for(int i = 0; i < 6; i += 2){
    System.out.println(i);
}

// This loop prints multiples of 4 between 0 and 16
for(int i = 0; i <= 16; i += 4){
    System.out.println(i);
}

// This loop prints the powers of 2 between 1 and 99
for(int i = 1; i < 100; i *= 2){
    System.out.println(i);
}

Using for loops

Here's a procedure that prints the set of odd integers between 1 and 9:

for(int i = 1; i<10; i+=2){
    System.out.println(i);
}

Here's another procedure that also prints the set of odd integers between 0 and 9:

for(int i = 1; i<10; i++){
    if (i % 2 == 1){
        System.out.println(i);
    }
}

Here's a procedure that sums the numbers between 0 and 100:

int sum = 0;
for(int i = 0; i < 100; i++){
    sum+=i;
}
sum;
4950

Here's another that calculates the factorial of 10, when 10! = 10 * 9 * 8 * ... * 1

int factorial = 1;
for(int i = 10; i > 0; i--){
    factorial *= i;
}
factorial;
3628800

Nested for loops

You can nest, or include, for loops inside of other for loops as well. For example:

for(int i = 0; i < 3; i++){
    for(int j = 0; j < 4; j++){
        System.out.println("i is " + i + " & j is " + j);
    }
}

i is 0 and j is 0
i is 0 and j is 1
i is 0 and j is 2
i is 0 and j is 3
i is 1 and j is 0
i is 1 and j is 1
i is 1 and j is 2
i is 1 and j is 3
i is 2 and j is 0
i is 2 and j is 1
i is 2 and j is 2
i is 2 and j is 3

while loops

While loops ask the program to do something while something else is true. For example:

int age = 15;
while(age < 18){
    System.out.println("Age is " + age);
    age++;
}

"Age is 15"
"Age is 16"
"Age is 17"

Translated into English, we're saying that while age is less than 18: 1. Print a sentence that's "Age is " and then the value of the age variable 2. Increment age by 1. (Remember age++ is the same as age=age+1)

More generally, they look like:

while(<expression is true>){
    <statement>;
}

Other resources


Using while loops

While loops can help perform tasks like summing the numbers between 0 and 50 inclusive:

int i = 0, int sum = 0
while(i < 51){
    sum += i
    i++
}
// At the end for the loop, when i = 51, sum = 1275

break

When you have a loop, you may want to use the break statement to stop the loop early. For instance,

int i = 0;
while (i < 100) {
    i++;
    System.out.println("i is:  " + i);
    if (i == 3) {
        System.out.println("Three? That's probably enough.");
        break;
    }
}

"i is:  1"
"i is:  2"
"i is:  3"
"Three? That's probably enough."

Creating objects

A class is a way to describe a concept. A class can define both fields (nouns) and methods (verbs). Think of it like a blueprint in a factory:

  • The Class is the design or the blueprint. It's the description of what something is and what it can do.
  • Using new tells the computer (the factory in this example) to make a new object or instance based on your design.

Take this Car class, for example:

public class Car {
    private String make;
    private String model;

    /** The Constructor, instructions on how to make a car */
    public Car() {
        // Instructions
    }

    /** A public method. Now anyone can tell a car object to .drive() */  
    public void drive() {
        // TODO figure out how to drive a car
    }
}

Other resources


null

In Java, null is a special keyword that means "empty" or "nothing." It can help you check whether an object hasn't yet received a value:

String empty;
empty == null;              // returns true

String blank = "";
blank == null;              // returns false

Object alsoEmpty;
alsoEmpty == null;          // returns true

Other resources


toString()

Most objects in Java have a toString() method, which returns a String-ified version of the object. This is one of the methods that you will most frequently override, since only you know how to display the objects you construct.

Some things in Java are self evaluating, which means they'll return themselves. You may've realized this initially, when we were evaluating primative data types - ints, doubles, and booleans:

System.out.println(true);           // Prints 'true'
System.out.println(42);             // Prints 42
System.out.println(87.18);          // Prints 87.18

Strings are also self-evaluating:

String greeting = "Hello";
System.out.println(greeting);           // Prints "Hello"
String goodbye = new String("Goodbye");
System.out.println(goodbye);            // Prints "Goodbye"

Arrays and other "container" objects are self-evaluating if they contain self-evaluating objects. For example, an array of booleans is self evaluating, while an array of Cars is not.

Other resources


Identity and equality

Java tests for identity – whether two things are the same – and equality – whether two things hold the same value – differently.

We do this every day; think of two US quarters. Both are equal – they represent the same value ($0.25 US) – but they're not identical – they're two quarters, not one.

The == operator tests for identity:

2 == 2;
true
true == true;
true
true == false;
false
12 == 12.0;
true

The function int equals() tests for equality:

Integer i = new Integer(4);
Integer j = new Integer(4);
i == j;
false
i.equals(j);
true

ADD MORE WRITEME


equals(Object)

Each object, include those you create, has an equals(Object) method that's inherited from the Object superclass.

The default equals(Object) methods checks whether the two objects have the same address in memory. It doesn't care about any of the values the objects have, because the Object superclass can't see those values.

Here's an example, using a Chatterbot object that (assume) we've defined elsewhere.

Chatterbot president = new Chatterbot("Barack");
Chatterbot barack = president;

president.equals(barack);
true

barack = new Chatterbot("Barack");

president.equals(barack);
false;

If we wanted two chatterbots to be the same if they had the same name, we'd have to override the equals(Object) method in our Chatterbot class:

public class Chatterbot{
    // implementation of the Chatterbot

    public boolean equals(Object obj){
      Chatterbot second = (Chatterbot) obj;
      return this.name == second.name;
    }
}

A few things worth pointing out:

  1. The method's signature is equals(Object), not equals(Chatterbot) so we can override the equals(Object) method from the Object superclass. If we change the method signature to equals(Chatterbot), we'll be overloading, not overriding, the method.
  2. We're stuck with a parameter of type Object, but we know it'll always be a Chatterbot – so we cast Object obj to Chatterbot.

Comparable

WRITEME


Classes

WRITEME

Other resources


Class variables

WRITEME


Main method

A method that's required by every Java application because it's the first code Java always runs.

WRITEME

public static void main(String[] args){
    // Your program's code here
}

Wrapper classes

Each of Java's primatives data types – int, double, and boolean – can be "wrapped" in a class and become an object.

In general, wrapping a primitive looks like:

<WrapperClassName> <variableName> = new <WrapperClassName>(<primative>);

and in practice, it looks like:

Double d = new Double(3.45);
Integer i = new Integer(4);
Boolean b = new Boolean(false);

There's wrapper classes for each type of primative:

primitive Wrapper class
boolean Boolean
int Integer
double Double
char Character

Other resources


Converting Wrapped primitives to primitives

While objects can be useful, sometimes we prefer to work with primitives. Here's how we go from a Wrapper class to a primitive:

Integer i = new Integer(4);
int j = i.intValue();
// j now has the value 4

Double d = new Double(5.2);
double e = d.doubleValue();
// e now has the value 5.2

Boolean b = new Boolean(true);
boolean c = b.booleanValue();
// c now has the value true

Java 5.0+ automatically converts between primitives and wrapped objects by autoboxing.


Boolean

The Boolean class is a wraps boolean primitives into Boolean objects.

Creating a Boolean object

The constructor for Boolean objects takes one of four values:

A true or false primitive:

Boolean b = new Boolean(false);
b;                                  // Returns false

A variable of a boolean primitive:

Boolean b = true;
Boolean c = new Boolean(b);
b;                                  // Returns true

Another Boolean object:

Boolean b = new Boolean(false);
b;                                  // Returns false
Boolean c = new Boolean(b);
c;                                  // Returns false

Simple assignment:

Boolean b = true;                 // Returns true; b is a Boolean object
boolean c = true;                 // Returns true; c is a boolean primitive

Double

The Double class wraps primative doubles into Double objects. For example:

Double d = new Double(9.28);
// Now, d has the value 9.28
double e = 0.25;
Double dbl = new Double(e);
// Now, dbl has the value 0.25

Integer

The Integer class wraps primative ints into Integer objects. For example:

Integer i = new Integer(7);
// Now, i has the value 7
int j = 10;
Integer in = new Integer(j);
Now, in has the value 10

Other resources

  • YouTube: Wrapper classes for numbers

Converting between wrapped types

Wrapped primitives can be converted to and from Strings, whereas "normal" primitives can't be. For example:

String s = "159";
int i = Integer.parseInt(s);
// Now, i has the value 159

A few things to notice:

parseInt(String) returns an int, not a wrapped Integer. If we wanted an Integer, we'd have to make it:

String s = "159";
int i = Integer.parseInt(s);
Integer j = new Integer(i);

or more succinctly:

Integer i = new Integer(Integer.parseInt(s));

The String class has another method, valueOf(string), that returns an Integer:

String s = "4884";
Integer i = Integer.valueOf(s);
// i has the value 4884

If we give valueOf(string) a bad String we'll get a runtime exception:

String willBreak = "I'm going to break!";
int i = Integer.parseInt(willBreak);
java.lang.NumberFormatException: for input string s

In practice, there's no difference between valueOf(string) and new Integer(Integer.parseInt(string)); use whichever makes your code easier to read.

Other resources


Converting primitives to strings

Java's static toString(int) and toString(double) methods turn an int, double, or boolean into a String.

int i = 104;
String s = Integer.toString(i);
// s now has the value "104"

double d = 994.4;
String t = Double.toString(d);
// t now has the value "994.4"

More generally, it looks like:

String <stringName> = <WrapperClassName>.toString(<primative>);

static

static variables are attached to the class, rather than any object or instance of the class.

Any object can access, manipulate, or re-write a static variable's value, and then the variable's value changes for all objects in the class.

Other resources


Constant variables

"Constant variables" isn't a misnomer; they actually end up fairly useful to refer to values that don't change. Java indicates a variable can't change with the keyword final.

final double PI = 3.14159265;
final int MAX_CLASS_SIZE = 30;
final String TEACHER_NAME = "Charles Babbage";

final variables can receive one value. If you try to reassign the variable later, you'll get a compile-time error:

final int MAX_CLASS_SIZE = 30;
MAX_CLASS_SIZE = 35;
ERROR The final field MAX_CLASS_SIZE cannot be assigned

It's convention, but not required, that the names of final variables are written in capital letters, with words separated by an underscore (_). This style makes it clear to you and anyone reading your word that these variables can't change.

Other resources


Object-oriented programming

Object-oriented programming is an attempt to make the structure of computer programs more understandable to people (like you!) by encouraging programmers (also like you!) to write programs that mimic the real world.

The base of object-oriented programming is that everything is an object.

Objects are the "things" around us. Some – computers, tables, chairs, cars, T-shirts, on and on – are tangible, and others – a meeting, a date, a list of tasks to be completed – are conceptual.

When programming, you get to set up the objects. That means you can make a blue (attribute) car (object) that flies (procedure) if you want.

Any piece of software, from Google search to your Netflix movie queue, can be broken down into objects. For example: imagine the object that controls Google's search algoirthm can send a message to google.com when it needs user information; imagine the search algorithm calling out, "Hey search box! Send me what the user typed in so I can search for it!" Once the search box responds, the algorithm can go ask its index object – the list of all the websites it knows – what it found.

As you design programs, sometimes you'll find it helpful to mimic real-world objects; other times, conceptual objects that don't exist in the real world will better suit. That's normal. Objects and object-oriented programming is one tool you can use to solve (programming) problems, but it need not be your only tool.

Other resources


Object getters and setters

As you write more programs, you'll run into issues of access control: who or what is allowed to access which parts of the class you're writing.

WRITEME

Other resources


this

this refers to the current object, whatever it is, including all its attributes.

WRITEME


Two-dimensional arrays

Just as we can put ints or Strings in an array, so too can we put arrays in an array. When we put arrays in an array, we say we have a two-dimensional array.

Here's what a two-dimensionsional array might look like:

boolean[][] board = new boolean[5][5];

// [false] [false] [false] [false] [false] 
// [false] [false] [false] [false] [false] 
// [false] [false] [false] [false] [false] 
// [false] [false] [false] [false] [false] 
// [false] [false] [false] [false] [false] 

board[2][1] = true;

// When assigning to an array, start counting rows first, then columns, and remember each starts at 0.

// [false] [false] [false] [false] [false] 
// [false] [false] [true] [false] [false] 
// [false] [false] [false] [false] [false] 
// [false] [false] [false] [false] [false] 
// [false] [false] [false] [false] [false] 

board [4][2] = true;

// [false] [false] [false] [false] [false] 
// [false] [false] [true] [false] [false] 
// [false] [false] [false] [false] [true] 
// [false] [false] [false] [false] [false] 
// [false] [false] [false] [false] [false] 

board.length;
5

board[0].length;
5
board[1].length;
5
board[4].length;
5

A single for loop is the best tool to cycle through a one-dimensional array, and nested for loops are the best tools to cycle through a two-dimensional array:

int[][] counts = new int[2][2];

counts[0][0] = 0;
counts[0][1] = 1;
counts[1][0] = 2;
counts[1][1] = 3;

// Which looks like:
// [0] [1]
// [2] [3]

for(int i = 0; i < counts.length; i++){
    for(int j = 0; j < counts[i].length; j++){
        System.out.println(counts[i][j] + " for i: " + i + " and j: " + j);
    }
}

0 for i: 0 and j: 0
1 for i: 0 and j: 1
2 for i: 1 and j: 0
3 for i: 1 and j: 1

Can you construct a 10 x 10 two-dimensional array that alternates between boolean values of true and false in each square? When you're done, your program should look like:

// [false] [true] [false] [true] [false] [true] [false] [true] [false] [true]
// [true] [false] [true] [false] [true] [false] [true] [false] [true] [false]
// [false] [true] [false] [true] [false] [true] [false] [true] [false] [true]
// [true] [false] [true] [false] [true] [false] [true] [false] [true] [false]
// [false] [true] [false] [true] [false] [true] [false] [true] [false] [true]
// [true] [false] [true] [false] [true] [false] [true] [false] [true] [false]
// [false] [true] [false] [true] [false] [true] [false] [true] [false] [true]
// [true] [false] [true] [false] [true] [false] [true] [false] [true] [false]
// [false] [true] [false] [true] [false] [true] [false] [true] [false] [true]
// [true] [false] [true] [false] [true] [false] [true] [false] [true] [false]

boolean[][] board = new boolean[10][10];
for(int i = 0; i < board.length; i++){
    boolean first = i % 2 == 1;
    for(int j = 0; i < board[i].length; i++){
        board[i][j] = first;
        first = !first;
    }
}

Other resources


Interface

WRITEME

Other resources


Comparable interface

FIXME


External Resources

Java is open-ended, and you can include code written by others in your program. You might want to do this if someone else has written a better or easier way of accomplishing something your project should do, like picking out a random number for a dice game.

If you use an external resource, you'll have to understand its API, or Application Programming Interface. APIs tell you which methods can be accessed, how to access them, and what you'll get back. They don't tell you how the developer implemented the methods though.

Java has APIs, which you use every time you use one of its classes, like Double, Integer, String, or Boolean. Java imports those classes into your project automatically. You'll need to import nearly all other APIs to your project directly.

For example, you can import the Random class – which helps calculate random numbers - by putting this at the top of your program:

import java.util.Random;

Or more generally:

import java.<packageName>.<subpackageName>.<className>;

Packages are groups of related classes "packaged" together. Packages serve the same purpose as folders on your computer or phone: they make specific classes easier to find.

Other resources


Inheritance

WRITEME

Other resources


super

When implementing inheritance, it's sometimes useful for a child class to call its parent's methods. With the super keyword, we can do just that.

You can use super to do anything the parent could. You can use this in any method or function on a child class.

In Constructors

In Java, if a you extend a class without a zero-argument constructor, you'll need to use one of the parent's constructors before making your object. For example:

public class Person {
    // We'll let whoever makes a 'person' specify a name
    private String name;

    public Person (String name) {
        this.name = name;
    }
}


public class Student extends Person {
    // We don't need to specify a name.
    // Person defines it for us!
    private School school;

    public Student(String name, School school) {
        // Note how we don't need a matching constructor, we just have to make our parent class happy
        super(name);
        this.school = school;
    }
}

Overriding

super is especially useful when overriding methods to extend behavior. For example:

public class Person {
    private String name;

    public Person (String name) {
        this.name = name;
    }

    public void morningRoutine() {
        // Wake up
        // Eat breakfast
    }
}


public class Student extends Person {
    private School school;

    public Student(String name, School school) {
        super(name);
        this.school = school;
    }

    // This next annotation reminds us that we're changing what our parent class does.
    @Override
    public void morningRoutine() {
        // hit snooze

        // If we left this out, we'd never wake up!
        super.morningRoutine();
        // make sure bag is packed
        // go to school
    }
}

Other resources


Extends

Java uses a keyword extends to link a subclass to its superclass. WRITEME

Other resources

  • YouTube: Subclasses, extends, and superclass
  • YouTube: Common Java classes: Object, Integer, Double, Random, Math, List, and ArrayList

Debugging

Debugging is the process of finding and fixing bugs, or errors, in a computer program.

Here's a few common bugs:

  • Are the variables of the correct type? (Are you ever using ints where doubles would suit better?)
  • Are your control statement brackets matched accurately, with the right code inside the brackets? And no extra code inside the brackets?
  • If your variables have default initial values, are those defaults correct?
  • Can you explain all the lines in your program?

Debugging math

If NaN pops up unexpectedly, there's probably an error in your math. One way to debug math errors is by evaluating expressions piece by piece. For example:

int students = 10 * 10;
int tables = 4 / 4 - 1;
int studentsPerTable = students / tables;
System.out.println("studentsPerTable is " + studentsPerTable);  // prints NaN

Let's go through all the variables:

System.out.println("students is " + students);
"students is 100"

System.out.println("tables is " + tables);
"tables is 0"       // Ah ha!

If we look at the line that declared the tables variable again:

int tables = 4 / 4 - 1;

Oops – we missed a set of parentheses, and it should've been:

int tables = 4 / (4 - 1);

Legibility

A legible program is one whose meaning is clear when it's read by someone who didn't write it. (Or, soemtimes, by you; code has a nasty habit of turning into gibberish when it's left alone for a few hours.) The goal of a legible program is that people and computers can read it.

Using sensible variable and method names is one of the fastest ways to make your code more legible. Here's a few hints:

  1. Use verb phrases for methods that perform an action or change a variable, e.g. convertTemperatureToCelsius
  2. Use descriptive nouns for variables, e.g. double dinnerTime or boolean isRaining or int playersAge.
  3. Java convention is writing variables with multiple words in camelCase: remove the spaces, lower case the first word, and capitalize the first letter of all the subsequent words.

Other resources


Decomposition

Decoposition is another trick that might make your program more understandable to humans. To decomose a problem is to break it into smaller, simpler pieces.

WRITEME

Other resources


Contribute, edit, and comment on exercise resources on our mailing list or in our Github repository

Join list Visit repository