Introduction to Java with Fun, Graphics, and Games
Student Qualifications
- Logical thinking and math skills
- Facility with computers
- A computer running macOS, Windows, or Linux
Class Description
This class provides a fun introduction to Java, which is one of the most popular programming languages.
Class Projects
In this class, we’ll create projects like these, while learning the elements of the language:
- text adventure games
- 2D and 3D graphics and animation
- probability simulations
- memory, math, and word games
What You’ll Learn
You’ll learn how to:
- create and run Java programs using several powerful development tools (which are free for students)
- use data, such as where a player is in a game, or how fast a rocket is moving, or the names of students in a class
- use randomness, for games and simulations
- write high-quality, efficient code with good style
- use loops, to, for example, make thousands of stars in a star field simulation
- use conditions, to, for example, take different actions depending on the inventory of a player in a game
About the Teacher
Dave Briccetti is a computer programming teacher for kids, professional software developer, community technology and music volunteer, open source software developer, creator of educational videos, and blogger. He uses and teaches several languages, including Python, JavaScript, Scala, Java, and Ruby. He started using Java in 1995.
Resources
- Dave’s Java Lessons Github repository
- Dave’s Multi-Language Cheat Sheet
- Oracle
- Processing
- JetBrains IntelliJ IDEA download page
- repl.it
- Edabit online coding challenges
- CodeInGame online coding challenges
Preparing for the Class
Please do the following before the second session:
- Install Processing and IntelliJ IDEA
- Start with the free trial with IDEA and then go to the JetBrains Products for Learning
page and get a free student license
- Select Apply With Official Document
- Start with the free trial with IDEA and then go to the JetBrains Products for Learning
page and get a free student license
Running the Examples
In repl.it
- From the Github repository, find an example and click on “Raw” so you can see it in a simpler format
- Select all (Cmd+A, Ctrl+A), then copy.
- Create a Java repl
- Paste, replacing any code already there
- Remove the line at the top containing the package statement
- Change the name of the class to Main
- Run
In IntelliJ IDEA
- Create a new project from version control
- Paste in this address: https://github.com/dcbriccetti/java-lessons
- You should be able to navigate among and run the examples
Part One
Session One
Getting acquainted and your goals
Learning Java
- Hello, world
- Hello, graphical user interface
- Hello, graphics with Processing
- Short demo of how you can learn Java while programming fun graphics and animations
- Interaction
- Using Scanner to get input
- Conditions, Example 2
Summary
We
- learned how to use println to create text output from our programs, and to use Scanner to get input
- saw what a desktop Java program might look like, with a button and a label
- saw that using Processing, we can write Java programs that make interesting art and simulations
- learned two ways to use conditions, the conditional operator and the if statement
- wrote a high/low guessing program
Session Two
Review of Session One material
New Material
Exercises
Interaction (println and Scanner)
- Display a message
- Get some input
- Do something with the input
Loops
- Old style
- Using an old-style “for” loop, print the numbers from 5 to 7.
- “for each”
- Create an array of strings with at least 2 words
- Print each word on its own line
Summary
We quizzed on and reviewed the previous session’s material, practiced with interaction and loops, learned how computers represent characters using ASCII, learned about functions, arguments, and parameters, then did some problems on Edabit, and finally studied and modified a simple text adventure game. Mr. Briccetti demonstrated some features of a version control system.
Session Three
- Review
- Caesar Cipher
- Graphics with Processing
- functions
- loops
- Fetching web pages
- Continuing the Adventure game
Summary
We reviewed how computers represent characters as numbers using ASCII, and practiced converting between characters and their ASCII values (‘a’ to 97 and back, for example). We saw that we can shift characters (a ‘z’ into a ‘y’, for example) by subtracting from their ASCII values, and that with this approach we can implement the Caesar Cipher.
Making graphics and animations is a fun way to practice our programming skills, so we ran the Processing application and developed a sketch that changed colors, and eventually made a simulation of a field of stars.
We ran code that fetches the contents of a web page. We’ll build on this idea of fetching useful information from the web later.
We briefly revisited the adventure game.
Session Four
Session Five
Review Problems
Use the example programs, and your notes from earlier sessions to help you solve these problems.
Numbers over a Threshold
- Ask the user for a threshold between 1 and 100 and save it in an int,
threshold
- Make a loop than runs 20 times, and in it:
- Generate a random integer between 1 and 100
- Print the number if it is greater than the threshold
- Display the average of all the random numbers, and the average of those numbers greater than the threshold
Types
Operators
Interactive Debugging
Processing
Cube of Cubes
Summary
We worked the Numbers over a Threshold problem and reviewed a couple of solutions. We then looked at commonly-used types and operators. Finally, we created a cube of cubes in Processing.
I recommend Oracle’s Java Tutorials to help with any subjects needing further explanation. Language Basics, for example.
Session Six
Focus on IntelliJ IDEA
IDE Features Trainer Plugin
Quiz on Last Session’s Material
Review Problem
Use the example programs, and your notes from earlier sessions to help you solve this problem. Write this program using IDEA.
Pounds to Kilograms
Your old-fashioned U.S. relatives keep giving you weights in pounds, but you use the International System of Units (aka SI) so you need to convert those archaic values to kilograms. You know that a kilogram is 2.204623 pounds, and a pound is 0.4535924 kilograms. Write a function to do the conversion, and in a loop:
- Ask for a weight in pounds
- Call the function to convert the value
- Print the result
Object-Oriented Programming
Introduction
Summary
We attempted to get everybody going with IDEA, but didn’t quite get there. Some installed the IDE Features Trainer Plugin so they could become more proficient with IDEA’s powerful features. We wrote the Pounds to Kilograms program, noting things like:
- using meaningful identifier names
- whether to use int, float or double
- how to extract a constant to eliminate a magic number
We learned how to create an IDEA project from someone’s Github repository. We began the complex subject of object-oriented programming, using cookie cutter -> cookie and blueprint -> house analogies. We ran a simple program under the debugger to watch it execute the constructor and another method, and we observed the code setting a field (aka instance variable).
Session Seven
Review
More Object-Oriented Programming
Adventure Game
Summary
We reviewed some basic elements like println
,
if
, and loops, then reviewed object-oriented
programming, using TalkingMammal
and its subclass,
SingingMammal
as examples.
We observed that the Adventure
class now has a
Place
class, with two instance variables (aka “fields”), name
and description
. We added a “stop” command to make
the main loop terminate. Then we removed the original
places (farm, town, and airport) and transitions, and
made our own.
Finally, we added an Event
class with fields
probability
and description
.
Part Two
Session One
Changes to Adventure Game
Create New Project from the Github Repository
Explain or Ask a Question
Object-Oriented Programming Exercises
Learning IDEA
View -> Tool Windows -> Learn
Do many of these exercises
Summary
Dave Briccetti showed improvements to our adventure game,
and we had a few rounds of “Explain a line or ask a question”,
which helped us better understand the code. We created a new
IDEA project from Dave’s Github repository, and then created
a new, empty Java project and did exercises there, creating
a Robot
or similar class with a greet
method, and a name
parameter in a constructor.
Dave tried to persuade the students that it’s worth spending
some time learning to use IDEA’s productivity features. We
installed the IDE Features Trainer
plugin, so that students
can select View -> Tool Windows -> Learn
and be guided
through learning and practicing many of the features.
Session Two
Changes to Adventure Game
Updating with git and IDEA
Summary
Everybody learned how to update the game engine using git pull, and how to commit their changes using git commit. We explored parts of the game engine. Students began adding their own places, events and transitions. We added an “else” events feature for the game. We learned several productivity features of IDEA.
Session Three
Countdown Timer Program
Fundamentals Review
- Create a class
- Create a method
- Print hello
- Pass an argument to a method
if, else if, else
Summary
We built a countdown timer in Swing, to tell us when to return from our five-minute break. We reviewed and practiced the fundamentals above. Along the way we discussed Unix Epoch Time (the time elapsed since the beginning of 1970), and how Little Snitch allows one to control the network activity of running applications.
Session Four
Walkthrough of Countdown Timer Improvements
Doc Comments
Edabit and CodinGame Problems
Summary
We learned how adding documentation comments (doc comments) can help others (and your future self) understand your code. We added a message to the countdown timer, and solved several problems in Edabit (one using IDEA), and then worked on Power of Thor in CodinGame.
Session Five
Doc Comments Exercise
- Doc comments for a class, method, and field
Basic Skills Review and Practice
- Conditions
- Loops
Edabit
Summary
We covered the items above. We saw the value in creating doc comments, and that the Java library is documented with them.
Here’s Mr. Briccetti’s solution to the How Many Vowels Edabit problem:
return (int) str.chars().filter(code ->
"aeiou".contains(String.valueOf((char) code))).count();
Session Six
Review
- loops
- summing a sequence of numbers (the non-Gaussian way)
- functions
- with no parameters
- with a parameter
- with a parameter and a return value
- IDEA features
- introduce variable
- reformat code
- move line
File Input
- Reading data from a file
- Randomly choosing a word from the file
Session Seven
Anagram Solving Game
Sample run of the game:
Hello! I will give you words, and you will give me an anagram for each word.
The words I give you come from a list of 3,000 common words. Respond with nothing to end.
worth? throw
Right
largely? x
gallery
tea? eat
Right
armed? drame
dream
sign? gins
sing
flee? feel
Right
earn?
You got 3 right and 3 wrong
Part Three
Session 3-1, 2020-09-02
Quiz
We’ll reset to somewhere in between beginner and intermediate levels.
High/Low Game
Log₂ of large numbers is much smaller numbers.
Dividing by 2 Exercise
Homework
- Install IDEA (see above)
- Look over this document
Session 3-2, 2020-09-09
Get new students on IDEA, and with a clone of the repository
Basics review
Session 3-3, 2020-09-16
Simple Types
- int
- float
- string
- boolean
printf format strings
Conditionals (if and ? :)
- Why one must never call the conditional operator the ternary operator
- “ternary” is a characteristic of it, not its name
Loops
- Demo of making 1,000 stars in Unity
- Displaying a message repeatedly in Java
Misc
- Base 16
- George Boole, after whom
boolean
is named
Session 3-4, 2020-09-23
We’ll use IDEA for coding today.
Show and Tell
Review
More on Loops
Methods
- Arguments
- Parameters
- Return values
A method is a function that is a member of a class. All methods are functions. Not all functions are methods.
MethodsPractice
package examples.simple;
public class MethodsPractice {
public static void main(String[] args) {
doSomething();
System.out.println(returnSomething());
System.out.println(returnSomethingFromSomething("San Francisco"));
}
/** Takes no inputs (because of the empty parameter list) and returns nothing (because of the void type) */
public static void doSomething() {
// Add two numbers
int sum = 5 + 4;
System.out.println(sum);
}
/** Takes no inputs (because of the empty parameter list) and returns a number */
public static int returnSomething() {
return 5;
}
/** Takes a String input and returns something */
public static String returnSomethingFromSomething(String cityName) {
return cityName.toLowerCase();
}
}
package examples.simple;
public class MethodsPractice {
public static void main(String[] args) {
doSomething();
System.out.println(returnSomething());
System.out.println(returnSomethingFromSomething("San Francisco"));
}
/** Takes no inputs (because of the empty parameter list) and returns nothing (because of the void type) */
public static void doSomething() {
// Add two numbers
int sum = 5 + 4;
System.out.println(sum);
}
/** Takes no inputs (because of the empty parameter list) and returns a number */
public static int returnSomething() {
return 5;
}
/** Takes a String input and returns something */
public static String returnSomethingFromSomething(String cityName) {
return cityName.toLowerCase();
}
}
Session 3-5, 2020-09-30
We’ll use IDEA again for coding today.
Show and Tell
Review
- Loops
- Methods
Methods, Continued
Pre- and post-increment
++i (pre-increment)
i++ (post-increment)
--i (pre-decrement)
i-- (post-decrement)
int lives = 1;
if (--lives <= 0) // game over
if (lives-- <= 0) // game is not over
Refactoring (Martin Fowler)
- extract method
- inline variable
- rename
Mean Absolute Deviation Program
Arrays
- Don’t change their size
- Must specify the size when you create it
Lists
- Can grow
- Can create an empty list and then add elements to it
Session 3-6, 2020-10-07
Show and Tell
Review
Mean Absolute Deviation Program
There are now two versions of the calculation method, one using Stream
s, and one not.
There is a test class.
Lists
Exercises with lists
Session 3-7, 2020-10-14
Show and Tell
Double Characters Problem
package examples.simple;
public class DoubleChars {
public static void main(String[] args) {
var app = new DoubleChars();
var result = app.doubleChars("hello");
System.out.println(result);
}
private String doubleChars(String text) {
var output = new StringBuilder();
var chars = text.toCharArray();
for (char ch : chars) {
output.append(ch);
output.append(ch);
}
return output.toString();
}
}
Review
Lists
- Create an empty list
- Learn about List and ArrayList
- Add to a list
- Loop over a list’s items
- Integer vs. int: two ways to hold integers, with the first used for Lists
- Access a specific element of the list
Object-Oriented Concepts
Part Four
Session 4-1, 2020-10-21
Show and Tell
Review
- Lists
- Edabit, to review various areas
Session 4-2, 2020-10-28
Show and Tell
Review Using Student Asks Student
- Arrays
- Edabit problem about having enough change
- Lists
- Object-Oriented Concepts
More Object-Oriented Concepts
Session 4-3, 2020-11-04
Show and Tell
Review
- Object-oriented concepts
- Arrays
- Lists
Search Performance
searching for alex
n = 6
dave
sachi
ryans
max
ava
alex
linear search O(n)
n = 6
alex
ava
dave
max
ryans
sachi
binary search O(log n)
hash table (such as Java HashSet) search O(1)
Sets
A Word-Checking Program Using Sets and Classes
Terms
- Constructor: a method with the same name as the class, which is called when an instance of the class is created (with new).
Session 4-4, 2020-11-11
Show and Tell
Practice, Practice, Practice!
Codingbat
We’ll do some Codingbat exercises, but on CodingRooms.
-
Return true if there is a 6 at the beginning or the end of the array
- to get first element of array:
nums[0]
- to get last element of array:
nums[nums.length - 1]
Processing
Colors in RGB mode
Lines program
Session 4-5, 2020-11-18
Show and Tell
Practice, Practice, Practice!
Codingbat
We’ll do some Codingbat exercises
- Has teen
- Sleep in
Refactoring
- Extract method
- Rename
- Introduce variable
Session 4-6, 2020-12-02
Show and Tell
Advent of Code
We’ll do some Advent of Code challenges.
Session 4-7, 2020-12-09
Show and Tell
Data Extraction with Regular Expressions
\d
digit
\w
word character
+
one or more
Advent of Code
We’ll prepare for Advent of Code challenge 2.
Part Five
Session 5-1, 2020-12-16
Show and Tell
Regular Expressions Review
Advent of Code
Session 5-2, 2020-12-30
Show and Tell
Git and Github
Regular Expressions Review
Advent of Code
Peter Norvig’s Amazing Python Solutions
Day 2, Part 1
We’ll continue Advent of Code challenge 2.
Day 2, Part 2
Session 5-3, 2021-01-06
Show and Tell
Quiz and Review
Session 5-4, 2021-01-13
Lists
Performance
Double-Ended Queue
Advent of Code Day 22, Part 1
Session 5-5, 2021-01-20
Advent of Code Day 22, Part 1, Continued
Practice
Assignment (=
) vs. equality (==
)
Decrementing and incrementing variables
Session 5-6, 2021-01-27
Practice
We are continuing with the quiz from 2021-01-06, starting with number 5.
We know to go to Oracle’s API page to look up things like java.util.Random.nextInt
.
We solved problem 9 next, using a regular expression.
Left off reviewing loops.
Session 5-7, 2021-02-03
Practice
Students quiz each other on the topics in our objectives spreadsheet.
- Methods (arguments, parameters, return values)
- Loops
- Conditionals (if and ? :)
- “Simple” types (primitives, mostly, such as int, short, double)
Compilation
Java
How to compile a Java program into a class file using the
javac
command, and decompile it with javap
, and run
it with java
, and pass command-line arguments to it.
The command-line arguments arrive in the String[] args
parameter in the main
method of the class.
C
Using gcc -o greet greet.c
to compile the C-language
program greet.c
into an executable program, greet
.
Regular Expressions
Text from a news article. Runway length from airport information.
Part Six
Session 6-1, 2021-02-10
Fetching web page data
BufferedReaders and InputStreamReaders and URLs, oh my!
Using a weather API
Homework
Finish project using a regex to display the three pieces of weather data. Ask for help on Mr. B’s Discord server if you like, or otherwise help each other.
Session 6-2, 2021-02-17
Solving a Word Ladder
Wikipedia article on Word Ladders
Finding all words one step away from one word
Finding all words one step away from all words
Session 6-3, 2021-02-24
Solving a Word Ladder, Continued
We began work on a findLadder
method, which finds a path,
if one exists, from startWord
to endWord
.
We used Davy Crockett to talk about the “frontier”. Mr. B even sang along with the theme song from the TV show, to help everyone remember the idea of a frontier.
We used an ArrayDeque<String>
for the frontier, and a
HashSet<String>
for the explored words. We
loop while we haven’t found the target word and
the frontier is not empty. We add words popped from
the frontier queue to the explored Set.
Session 6-4, 2021-03-03
Solving a Word Ladder, Continued
Rewrite wordsOneDifferentFrom
We replaced several lines of code with a single line with a Stream and filter instead of a loop.
Complete the Algorithm
We had to add one word to the dictionary we are using, but
we were able to find the path from table
to crown
.
Session 6-5, 2021-03-10
Solving a Word Ladder, Continued
Finding the path back to the starting word
A java.util.Map<String, String>
is perfect for this!
Let’s have some exercises with Maps.
- food costs
- code names for people
- finding predecessor words
Session 6-6, 2021-03-17
Maps Review
Why use a map? When you have keys and values, and you want to store and access them easily (and quickly!).
Any more with the word ladder?
We integrated the search back routine, but it gets stuck in a loop.
How about working some CodinGame problems?
- The Descent
- Mars Lander Episode 1
Session 6-7, 2021-03-24
This is the final session of part 6, and of the series.
Let’s review and practice with Edabit and CodinGame
CodinGame
- Coders Strike Back
Edabit
Testing and Code Coverage
IDEA can generate test classes for you. You can run the tests with code coverage, and then look for the green and red markings to the left of the code, to find any untested code. Any red code should be suspect.