Libraries Lesson

Libraries: Your Programming Toolkit

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.

Why Use Libraries?

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.

Core Benefits

  • Reusability: Write code once, use it everywhere. Saves enormous amounts of time.
  • Reliability: Major libraries (like Java's own, and WPILib) are well-tested by thousands of developers.
  • Efficiency: Library code is often highly optimized for performance.
  • Standardization: Provides standard, well-documented ways to perform common tasks.

Packages and the `import` Statement

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

Key Built-in Java Libraries

Java comes with a vast collection of standard libraries (the Java API). Here are a few you'll use constantly:

`java.lang`

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

`java.util`

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
    

Test Your Knowledge

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?