Unit 5: Basic FRC Coding
In programming, a library is a collection of pre-written, reusable code that you can use to perform common tasks without having to "reinvent the wheel." Using libraries is fundamental to modern, efficient software development.
Imagine you're building a robot. You wouldn't manufacture your own motors or sensors from scratch; you'd use pre-made, tested components. Libraries are the software equivalent. They provide reliable, optimized code for complex tasks.
In Java, libraries are organized into packages. To use a class from a package, you must tell your program where to find it using an `import` statement at the top of your Java file.
// To use the Scanner class, we must import it from the java.util package
import java.util.Scanner;
// To use motor controllers, we import them from the WPILib library
import edu.wpi.first.wpilibj.motorcontrol.Spark;
public class MyRobot {
// Now we can use these classes because we imported them
private Scanner myScanner;
private Spark myMotor;
}
Java comes with a vast collection of standard libraries (the Java API). Here are a few you'll use constantly:
This package is so fundamental that it's automatically imported into every Java program. It contains essential classes like `String`, `Math`, and `System`.
// No import needed for these classes!
String message = "Hello, FRC!";
double absoluteValue = Math.abs(-10.5);
System.out.println(message);
This package contains powerful utility classes for data structures and more.
import java.util.ArrayList;
import java.util.Random;
// A dynamic list that can grow and shrink
ArrayList<String> teams = new ArrayList<>();
teams.add("2910");
teams.add("254");
// A random number generator
Random rand = new Random();
int randomNumber = rand.nextInt(100); // A random number between 0 and 99
Question: You want to use the `ArrayList` class in your code. What is the first thing you must do at the top of your Java file?