AdamBots Team 245
Before we start

Sign in

  1. 1Open your phone's camera
  2. 2Point it at the code
  3. 3Tap the link and fill in the form

No phone? Tell a mentor and we'll sign you in.

Today Session 2 · Intro to Java Rookie Bootcamp · Programming Track
📋 Attendance
forms.gle/os9g31bhyXHY3bPd6
AdamBots Team 245
Rookie Bootcamp · Programming Track · Session 2

Intro to
Java

The parts that trip up every rookie, and how to beat them

Today's mission

Read the robot's mind

This is real robot code from an intake (simplified). Click to reveal it.

Right now it probably looks like nonsense. That's OK.

By the end of today, you'll be able to read every line.

01

How Java runs

★ Story time
1970sBell Labs, New Jersey

Everyone's first program

1970sAt Bell Labs, Brian Kernighan used a tiny example program that did one thing: print hello, world.
1978It appeared in his famous book on the C language, and programmers everywhere copied the idea.
Today"Hello, World" is the traditional first program in almost every language, from Java to Python to robot code.
In a few minutes, it will be yours too.
Recap from last session

A compiler translates your code for the computer

You write it

Code humans can read

int total = 5 + 3;
🔍
Compiler1. checks for mistakes
2. translates
The CPU runs it

Only 0s and 1s

10110000 00000101
00000100 00000011
◆ It checks firstIf anything is wrong, the compiler stops and tells you where. Those messages are compile errors.
★ Like a translatorIt translates the whole program before it runs, like translating a whole book before anyone reads it.
.java and .class files

Java uses two kinds of files

.java

Ex01_Hello.java

  • Source code: the text you write
  • You can read it and edit it in VS Code
  • This is the file you save and share
javacthe Java compiler
.class

Ex01_Hello.class

  • Bytecode: made by the compiler
  • Looks like gibberish to people
  • Never edit it: it's rebuilt every time you compile
◆ File extensionsThe part after the dot tells the computer what kind of file it is: .java is source code, .class is bytecode.
★ Java's twistBytecode isn't machine code for any one CPU. It's an in-between language that a JVM runs (next slide).
The Java Virtual Machine

The JVM runs bytecode on any computer

JVM = Java Virtual Machine: a program that acts like a computer that understands bytecode. The command java Ex01_Hello starts it.

📦

Ex01_Hello.class

bytecode

→
🪟

Windows laptop

JVM for Intel/AMD

🍎

Mac

JVM for Apple chips

🤖

SystemCore

JVM for its ARM chip

Each computer has its own JVM that translates bytecode for its CPU. It even speeds up as it runs, by compiling the busiest parts on the fly.

Putting it together

From your keyboard to the CPU, in four stops

⌨️
You writehuman-readable codeEx01_Hello.java
🔍
javacthe compiler checks it, then translatesjavac Ex01_Hello.java
📦
Bytecodea new file appearsEx01_Hello.class
☕
JVMruns it on this computer's CPUjava Ex01_Hello
  output
Hello, World!
Compare

Two moments a mistake can show up

The compiler refuses

Compile time

  • Typos and missing ;
  • Missing braces
  • Wrong types: int x = "hi";

No .class file. Nothing runs.

VS
It compiled, then...

Run time

  • Divide by zero
  • Using something that doesn't exist yet
  • Logic errors: wrong answer, no crash

The program crashes or misbehaves.

The compiler is your friend: it catches mistakes before the robot ever moves.
Our robot

Deploy is the same pipeline, sent to the robot

💻
BuildVS Code compiles your whole project
📡
Copysends it to the robot over its network
🤖
RunSystemCore's JVM runs your code
◆ Why it mattersIf the build fails, nothing reaches the robot. Read the error, fix it, build again. A failed build at the competition is fixed in your code, not on the robot.
Before you write code

Give your code one home: C:\bootcamp

  1. 1Open File Explorer (⊞ Win + E), click This PC, then Local Disk (C:).
  2. 2Click New folder and name it bootcamp.
  3. 3Copy the exercise files from your mentor into it.
  4. 4In WPILib VS Code: File → Open Folder… → C:\bootcamp. If it asks, click Yes, I trust the authors.
📁This PC›Local Disk (C:)›bootcamp✓
☕ Ex01_Hello.java
☕ Ex02_FixMe.java
☕ Ex03_Predict.java
…
☁️OneDrive›Documents›bootcamp✗
☕ Ex01_Hello.java ⟳ syncing…
☕ Ex02_FixMe.java ☁ online-only
⚠ Not in Documents, Desktop or OneDriveOn most laptops those folders are synced by OneDrive. OneDrive moves and locks files while WPILib is building, and builds fail with strange errors. C:\bootcamp keeps it simple.
Live demo · mentor

Compile it yourself, step by step

Ex01_Hello.javaJava
public class Ex01_Hello {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
★ The promptPS C:\bootcamp> means "PowerShell, in the bootcamp folder, waiting for you." You type after the > and press Enter.
PROBLEMSOUTPUTDEBUG CONSOLETERMINAL⌄ powershell
PS C:\bootcamp> javac Ex01_Hello.java
↑ javac printed nothing: no news is good news
PS C:\bootcamp> dir

Mode          LastWriteTime   Length Name
----          -------------   ------ ----
-a----   10/30/2026  6:02 PM     425 Ex01_Hello.class
-a----   10/30/2026  6:01 PM     124 Ex01_Hello.java
PS C:\bootcamp> java Ex01_Hello
Hello, World!
PS C:\bootcamp> type Ex01_Hello.class
Êþº¾   A ... java/lang/Object ... ()V
↑ gibberish to us, perfect for the JVM
▶ Try it · 4 min

Run your first Java program

Steps

  • In WPILib VS Code, open your C:\bootcamp folder.
  • Open Ex01_Hello.java and click Run above main.
  • Change the message to say hi to you.
  • Add two more lines: your grade and your favorite robot part.
Ex01_Hello.javaedit me
public class Ex01_Hello {
%%    
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
★ Stuck?The small grey Run | Debug links appear just above main. Don't see them? Wait for VS Code to finish loading Java (bottom bar), then try again.
02

Anatomy of a Java program

★ Story time
1962Cape Canaveral, Florida

One missing symbol

July 1962NASA launched Mariner 1, its first probe headed for Venus.
+ 5 minThe rocket veered off course and the range safety officer had to destroy it.
WhyInvestigators traced it to a single missing symbol in the guidance instructions. Science fiction writer Arthur C. Clarke called it "the most expensive hyphen in history."
Computers do exactly what you write, down to the last character.
Anatomy

Every piece of Hello World has a job

public class Ex01_Hello {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
LINE 1A class named Ex01_Hello. Every Java program lives inside a class. Its box opens with {
LINE 2The main method: where the program starts. Its box opens with { inside the class box.
LINE 3A statement: one instruction. It ends with ;
LINE 4} closes main's box. Same color as the { on line 2.
LINE 5} closes the class box. Same color as the { on line 1.
ALLNothing here is decoration. Delete any piece and it won't compile.
Rule #1

The class name must match the file name

✓ Ex01_Hello.javafile name
public class Ex01_Hello {
    ...
}

File Ex01_Hello.java, class Ex01_Hello. Exactly the same, capitals included.

✗ ex01_hello.javafile name
public class ⟦Ex01_Hello⟧ {
    ...
}
ex01_hello.java:1: error: class Ex01_Hello is public,
should be declared in a file named Ex01_Hello.java
★ Robot codeIntake.java holds class Intake. Rename one, rename both (VS Code's rename does this for you).
Where Java starts

main is the door sign: "Program starts here"

publicanyone can use it, including Java itself
staticbelongs to the class itself (more next session)
voidgives nothing back
mainthe special name Java looks for
(String[] args)extra info you can pass in (rarely used)
For now: copy this line exactly. Every word is required.
◆ New in Java 25 (used by WPILib 2027)Tiny programs may skip the class: void main() { IO.println("Hi"); }. Robot code still uses full classes, so we learn the full form.
Braces · click any brace

Braces are boxes. Every { needs its }.

public class Robot {
    public void teleop() {
        if (buttonPressed) {
            intake.run();
        } else {
            intake.stop();
        }
    }
}
BLUEThe class box holds everything.
GOLDThe method box sits inside the class.
GREENThe if and else boxes sit inside the method.
★ TrickClick a brace in VS Code and its partner lights up too. Count: opens = closes.
Indentation

Indentation shows the boxes to humans

✗ Hard to readstill compiles!
public class Robot {
public void teleop() {
if (buttonPressed) {
intake.run();
} else {
intake.stop();
}
}
}
✓ Formattedsame code
public class Robot {
    public void teleop() {
        if (buttonPressed) {
            intake.run();
        } else {
            intake.stop();
        }
    }
}
◆ Let VS Code do itFormat Document: Shift + Alt + F (Windows) or Shift + Option + F (Mac). If the indentation looks wrong after formatting, a brace is missing.
Semicolons

A semicolon is a period at the end of a statement

✓ Statements end with ;

int speed = 5;
motor.setThrottle(0.5);
System.out.println("Go!");

✗ Never after these

public void stop() ⟦;⟧ {   // method header
if (x > 5) ⟦;⟧ {           // if condition
while (pathClear()) ⟦;⟧ {  // loop condition
⚠ The sneaky oneif (x > 5); { stop(); } compiles, and stop() always runs. The ; ends the if right there, with nothing inside it.
Picky, picky

Capital letters and quotes matter

Case counts

System.out.println("ok");  ✓
⟦system⟧.out.println("no"); ✗

To Java, System and system are different words.

String has a capital S

String name = "Ava";  ✓
⟦string⟧ name = "Ava"; ✗

But int, double, boolean are lowercase.

Straight quotes only

"Hello"   ✓
⟦“Hello”⟧   ✗

Curly "smart quotes" sneak in when you copy from Docs, Word or a website.

Comments

Comments are notes for humans. Java skips them.

// One-line comment: everything after // is ignored

/* A block comment
   can span many lines */

motor.setThrottle(0.3);  // arm hits frame above 0.4
✓ Good commentSays why: "arm hits frame above 0.4"
✗ Useless commentSays what the code already says: "sets the motor to 0.3"
★ Debug trickPut // in front of a line to switch it off without deleting it.
File organization

Where things live in a robot project

MyRobot/ build.gradle ← project settings src/main/java/frc/robot/ Main.java ← main() lives here Robot.java ← modes: auto, teleop RobotContainer.java Constants.java subsystems/ Intake.java commands/ ...
MAINMain.java has the main method. It starts the robot and hands off to Robot.java. Don't edit it.
PACKAGEFolders are packages. A file in subsystems/ starts with package frc.robot.subsystems; and it must match.
IMPORTimport lines borrow code from other packages. In WPILib 2027 they start with org.wpilib.
▶ Try it · 6 min

Spot the bug: each program has exactly one

1

Bug1.java
public class Bug1 {
  public static void
    main(String[] a) {
    int x = 5⟦ ⟧
    System.out.println(x);
  }
}
Missing ; after int x = 5

2

Bug2.java
public class Bug2 {
  public static void
    main(String[] a) {
    System.out.println("Hi");
  ⟦}⟧
Missing a closing }: two opened, one closed

3

robot.java
public class Robot {
  public static void
    main(String[] a) {
    System.out.println("Go");
  }
}
File is robot.java but the class is Robot

4

Bug4.java
public class Bug4 {
  public static void
    main(String[] a) {
    ⟦system⟧.out.println(1);
  }
}
system should be System (capital S)

5

Bug5.java
public class Bug5 {
  public static void
    main(String[] a) {
    System.out.println(⟦“Hi”⟧);
  }
}
Curly smart quotes. Use straight " quotes
★ ThenOpen Ex02_FixMe.java: the same five kinds of mistakes in one file. Fix them until it runs.
Reading errors

A compiler error tells you exactly where to look

  output
Robot.java:14: error: ';' expected
        motor.setThrottle(0.5)
                              ^
1 error
FILEWhich file
LINEWhich line
WHATWhat it expected
^The exact spot
Fix the first error first. One missing brace can cause 20 errors below it.
Read the robot's mind · 1 of 4

Find the structure

  • package line matches the folder
  • import lines borrow WPILib code
  • The class box: file is Intake.java
  • Last line: the class box closes
Break

Stretch!

Back in 10 minutes. Next: data and types.

03

Data and types

Variables

A variable is a labeled box that holds a value

type: double
speed
0.5
DECLAREMake the box and give it a type and a name: double speed;
ASSIGNPut a value in it: speed = 0.5;
BOTHUsually done in one line: double speed = 0.5;
READUse the name to look inside: motor.setThrottle(speed);
The most important symbol

In Java, = means "store," not "equals"

int x = 5;
x = x + 1;
In math classx = x + 1 is impossible.
1Read the right side first: x is 5, so x + 1 is 6.
2Store the result in the box on the left: x is now 6.
Read = out loud as "gets": "x gets x plus one."
Types

Each type is a different shape of box

int

42
-7

Whole numbers. No decimals. Up to about 2.1 billion.

Big siblinglong for whole numbers past 2.1 billion. Ends in 3_000_000_000L

double

0.75
3.14

Numbers with decimals. Our default.

Small siblingfloat is half the size and less precise. Ends in 0.75f

boolean

true
false

Yes or no. Only two values.

char

'A'
'7'

One character, in single quotes.

String

"Hi"
"245"

Text, in double quotes. Capital S.

◆ The compiler checks the shapesint count = 0.5; won't compile: a decimal doesn't fit in a whole-number box.
★ Rule of thumbUse int and double. Reach for long or float only when a library hands you one.
Types on our robot

Pick the type that matches the real thing

@@int motorId = 3;
@@double speed = 0.75;
@@boolean hasGamePiece = false;
@@String mode = "auto";
@@final int kIntakeMotorId = 9;
intIDs, counts, channels
doubleSpeeds (-1.0 to 1.0), angles, distances
booleanSensors that are on or off
StringNames and messages
finalA constant: it can never change. WPILib style names start with k.
▶ Try it · 3 min

Type sorter: click a value, then click its box

423.14true'A'"Hello""42"-70.5"true"100.0'7'

int

double

boolean

char

String

Pick a value to start.
Why types? Bits again

A type tells the computer how many switches to use

boolean

Just true or false. Basically one switch.

int · 32 bits

Biggest value: 2,147,483,647. Remember Gangnam Style from last session? Need more? long uses 64 bits.

double · 64 bits

Decimals with about 15 to 16 digits of accuracy. Big range, but not perfect: 0.1 + 0.2 is 0.30000000000000004. float uses 32 bits and keeps only about 7 digits.

The type decides how much memory the box gets and what you're allowed to do with it.
★ Story time
1996Kourou, French Guiana

The number that didn't fit

June 1996Europe's brand-new Ariane 5 rocket exploded about 37 seconds after launch.
WhyIts software tried to squeeze a 64-bit number into a 16-bit integer box. The value was too big to fit, and the guidance system shut down.
2015The FAA told airlines to restart the Boeing 787's power system at least every 248 days: an internal counter could overflow and shut the power down.
Every type has limits. Pick one big enough for the real world.
Memory stepper · press Step

Watch the boxes as each line runs

1int count = 0; 2double speed = 0.5; 3count = count + 1; 4speed = speed * 2; 5boolean fast = speed > 0.8; 6String msg = "Count: " + count;
MEMORY
Naming

Good names make code read like English

✓ Do

double leftMotorSpeed = 0.5;   // camelCase
boolean isAtTarget = false;    // reads as a question
final double kMaxSpeed = 0.8;  // constant: k...

✗ Don't

double ⟦x⟧ = 0.5;            // what is x?
int ⟦2ndMotor⟧ = 4;          // can't start with a digit
double ⟦left speed⟧ = 0.5;   // no spaces
int ⟦class⟧ = 3;             // reserved word
◆ camelCaseStart lowercase, capitalize each new word: leftMotorSpeed, hasGamePiece. Classes start with a capital: Intake, Robot.
Read the robot's mind · 2 of 4

Find the data

  • Three constants: final, names start with k
  • Two kinds of int and one double
  • motor and beamBreak are boxes holding robot parts (objects, next session)
04

Operators and expressions

Math

Math works like math class, mostly

+ −

add, subtract

*

multiply

/

divide (careful!)

%

remainder: 7 % 3 is 1

◆ Order of operations2 + 3 * 4 is 14. Use parentheses to be clear: (2 + 3) * 4 is 20.
★ Robot usecount % 2 == 0 asks "is count even?" Great for blinking lights.
Shortcuts

Counting up and down: ++ and --

x = x + 1;

The long way you already know: "x gets x plus one."

x += 1;

Same thing, shorter. Works with any amount: speed += 0.1;

x++;

Shortest: add exactly one. Say it "x plus plus."

x--;

The opposite: subtract one. Say it "x minus minus."

int x = 5;
x = x + 1;   // x is 6
x += 1;      // x is 7
x++;         // x is 8
x--;         // x is 7
★ You'll see these everywhereEvery for loop counts with i++ (next section), and counting down uses i--.You may also see ++x. On its own line, it does exactly the same thing.
Predict, then click each card

The integer division trap

7 / 2predict
3int ÷ int drops the decimal (no rounding)
7.0 / 2predict
3.5a double in the mix keeps the decimal
7 % 2predict
1the remainder
1 / 2predict
0half speed? No: zero!
9 / 10predict
00.9 chopped down to 0
1.0 / 2predict
0.5the fix: write a decimal point
⚠ Robot horror storymotor.setThrottle(1 / 2); compiles fine and sets the motor to 0. Write 0.5 or 1.0 / 2.
Strings

+ with a String glues things together

"Team " + 245
"Team 245"

Text + number = text

"2" + 2
"22"

Not 4! "2" is text.

2 + 2 + "2"
"42"

Left to right: 2 + 2 is 4, then "4" + "2"

★ Super usefulSystem.out.println("Speed: " + speed); prints a readable message while you debug.
Comparisons

Comparisons give you true or false

==is equal to
!=is not equal to
< >less than, greater than
<= >=or equal
&& || !AND, OR, NOT: the gates from last session
⚠ The #1 rookie bug= stores. == compares.
if (count ⟦=⟧ 3)   // ✗ stores 3
if (count == 3)  // ✓ asks "is it 3?"
boolean ready = enabled && !hasGamePiece;
▶ Try it · 4 min · tap an answer

Predict the output

7 / 2

int ÷ int drops the decimal

"2" + 2

String + number glues

2 + 2 + "2"

Left to right: 4, then "42"

10 % 3

10 ÷ 3 is 3, remainder 1

5 == 5.0

Same value, Java compares numbers

!(3 > 2)

3 > 2 is true, NOT flips it

Then run Ex03_Predict.java to check every answer on your laptop.

Break

Recharge!

Back in 10 minutes. Next: making decisions and repeating.

05

Control structures

if / else · click the switch

Last session's flowchart, now in real Java

boolean hasGamePiece = true;

if (hasGamePiece) {
    shooter.fire();
} else {
    intake.run();
}
hasGamePiece = true
( )The condition goes in parentheses. It must be true or false.
{ }Each branch gets its own box. Exactly one box runs.
else if · drag the slider

else if checks one thing after another

double speed;
if (distance > 5.0) {
    speed = 0.9;     // far: go fast
} else if (distance > 2.0) {
    speed = 0.5;     // medium
} else {
    speed = 0.2;     // close: creep in
}

distance = 6.0 m

speed = 0.9

★ RuleJava checks from the top and runs only the first true branch.
Spot these in your own code

Four classic if mistakes

1 · = instead of ==

if (mode ⟦=⟧ 2) { ... }

Use == to compare.

2 · ; after the condition

if (x > 5)⟦;⟧ { stop(); }

stop() always runs.

3 · Missing braces

if (ready)
    intake.run();
    shooter.fire();   // always runs!

Without braces, only the first line belongs to the if. Always use braces.

4 · Comparing Strings with ==

if (mode ⟦==⟧ "auto")      // ✗ unreliable
if (mode.equals("auto"))  // ✓

Strings use .equals().

while loop stepper · press Step

A while loop repeats while its check is true

int laps = 0;while (laps < 3) {    System.out.println("Lap " + laps);    laps++;}System.out.println("Done!");
⚠ Change what you checkSomething in the body must move the check toward false. Forget laps++ and the loop never ends.

laps

-

laps < 3 ?

-
for loop stepper · press Step

A for loop has three parts

for (int i = 0; i < 3; i++) {    System.out.println("Lap " + i);}System.out.println("Done!");
STARTruns once
CHECKbefore every lap
UPDATEafter every lap

i

-

i < 3 ?

-
Off by one

< vs <= : the difference is one lap

for (int i = 0; i < 3; i++)
0
1
2

3 laps: 0, 1, 2

for (int i = 0; i <= 3; i++)
0
1
2
3

4 laps: 0, 1, 2, 3

◆ Programmers count from 0"Do it 3 times" is usually for (int i = 0; i < 3; i++). Start at 0, use <, and the number is the lap count.
★ Story time
Dec 312008, New Year's Eve

The music player that froze

MorningThousands of Microsoft Zune 30 music players froze at the same moment, all over the world.
Why2008 was a leap year. On day 366, a loop in the clock code could never reach its exit condition: an infinite loop.
FixWait until January 1, when the date no longer matched. Every player started working again.
Always ask: will this loop's condition definitely become false?
The most important robot lesson today

Never make robot code wait in a loop

robot loops0every 20 ms
public void periodic() {   // called every 20 ms
    // ✗ waits here, nothing else runs:
    while (!intake.hasGamePiece()) { }
    // ✓ check once per loop instead:
    if (intake.hasGamePiece()) { intake.stop(); }
}
Running: driving, sensors and dashboard all update.
▶ Try it · 6 min

Match countdown

Open Ex04_Countdown.java

  • Use a for loop to print 10 down to 1.
  • Then print "Match start!"
  • Inside the loop, when the number is 3 or less, also print "Get ready!"
  • Stretch: rewrite last session's Level 2 game solution as real Java (repeat → for, while stays while).
  expected output
10
9
...
3
Get ready!
2
Get ready!
1
Get ready!
Match start!
★ HintCounting down: start at 10, keep going while i >= 1, and use i--.
Read the robot's mind · 3 of 4

Find the decisions

  • An if / else inside run()
  • If a game piece is in: stop. Else: spin the motor.
  • No waiting loop anywhere: it checks once, every 20 ms
06

Methods

★ Story time
1969Apollo 11

Margaret Hamilton's software

1960sMargaret Hamilton led the MIT team writing the onboard flight software for Apollo, and helped popularize the term "software engineering."
LandingMinutes before Apollo 11 touched down, the computer got overloaded and flashed alarms.
SavedThe software was organized into separate jobs with priorities. It dropped the unimportant work, kept the landing jobs running, and the landing went ahead.
Big programs work when they're split into well-organized, named pieces.
Methods

A method is a named recipe you can use again and again

✗ Copy and paste

leftMotor.setThrottle(0);
rightMotor.setThrottle(0);
intake.stop();
// ...and the same 3 lines
// in 6 other places

✓ Write it once

void stopEverything() {
    leftMotor.setThrottle(0);
    rightMotor.setThrottle(0);
    intake.stop();
}
stopEverything();   // use anywhere
★ You've already used methodsSystem.out.println("Hi") and motor.setThrottle(0.5) are method calls. Someone else wrote those recipes.
Anatomy

The parts of a method

double average(double a, double b) {
    double total = a + b;
    return total / 2;
}
doubleReturn type: what kind of value comes back. void means nothing comes back.
averageName: a verb, in camelCase.
( )Parameters: the inputs, each with a type and a name.
{ }Body: the steps of the recipe.
returnHands the answer back to whoever called it.
The method machine · pick one, type inputs, press Run

Inputs go in, a result comes out

⚙️

returns

?
Calling a method

Arguments go in, the return value comes back

double average(double a, double b) { ... }   // definition

double avg = average(2.0, 4.0);               // call
2.0 → aArguments are copied into the parameters, in order.
4.0 → bSame count, same types, same order.
3.0 → avgThe returned value is stored in avg.
◆ WordsParameters are the named slots in the definition. Arguments are the actual values you pass in.
Scope

A variable lives only inside its braces

void teleop() {
    if (buttonPressed) {
        double speed = 0.8;    // born here
        motor.setThrottle(speed);
    }                          // gone here
    System.out.println(⟦speed⟧);  // ✗
}
error: cannot find symbol
  symbol: variable speed
WHYspeed was made inside the if box. When the box closes, the variable disappears.
FIXDeclare it in the outer box, before the if, so both places can see it.
Methods on our robot

Name methods like actions and questions

Actions (void)

void drive(double speed)
void stop()
void runIntake()

Do something. Names are verbs.

Questions and readings (return a value)

boolean hasGamePiece()
boolean isAtTarget()
double getAngle()

Answer something. Booleans read like yes/no questions.

Read it out loud: if (intake.hasGamePiece()) { shooter.fire(); }
▶ Try it · 6 min

Write two methods

Open Ex05_Methods.java

  • isFast(double speed): return true if speed is more than 0.7
  • average(double a, double b): return the average
  • Run it: main already calls both and prints what it expects
  • Stretch: write clamp(double value, double max)
starterfill in the TODOs
static boolean isFast(double speed) {
    // TODO
    return false;
}
Read the robot's mind · 4 of 4

Find the methods

  • run() and stop(): void actions
  • hasGamePiece(): returns a boolean
  • run() calls the other two
07

Read the robot's mind

Mission complete

You can read every line

Click a layer to turn it on or off.

Structure Data Control Methods

Same file you saw at the very start of today.

▶ Try it · 8 min · in pairs

Debug the robot code: six bugs, one from each section

1 · Structure

A brace problem

2 · Types

A value in the wrong box

3 · Operators

Sneaky division

4 · Comparisons

= vs ==

5 · Loops

The robot loop trap

6 · Methods

A scope or return mistake

Open Ex06_DebugIntake.java. Fix the compile errors first, then run it and fix what's still wrong.

Coming up next session

A class bundles data and methods together

Intake

Data (has): a motor, a beam-break sensor, a speed

Methods (can): run(), stop(), hasGamePiece()

Every subsystem on the robot is a class: Intake, Shooter, Drivetrain, Arm.

Next time: how to build your own, and how they work together.

Recap

Five things to remember

01

javac checks and compiles; the JVM runs it.

02

Braces are boxes. Every { needs its }.

03

The type decides what fits. Watch 1 / 2.

04

if / else and loops, but never wait in robot code.

05

Methods are named recipes.

Quick check · tap an answer

How much do you remember?

1 · Ex01_Hello.java must contain...

File name and class name match exactly

2 · int x = 7 / 2; x is...

Integer division drops the decimal

3 · Which compares two values?

= stores, == compares

4 · A method that returns nothing is...

void means nothing comes back
AdamBots Team 245
Up next · Session 3

Classes &
Objects

Build your own Intake. Practice with the exercise pack before then.

Press ? for keyboard help · T for contents

Contents T or Esc to close

Keyboard & mouse ? or Esc to close

→SpacePgDnEnterNext step or slide (also: click the right half of the screen, or a clicker)
←PgUpBackspaceBack (also: click the left half, or right-click)
Home EndFirst slide / last slide
12… then EnterJump to a slide number
TContents: jump to any slide (or the ☰ button, top-left)
NShow or hide speaker notes
FFullscreen on / off
?This help
EscClose notes, contents, help or a photo
On interactive slides, clicking bulbs, switches, buttons, sliders, photos and quiz answers works the piece instead of changing slides.