Getting Started
In programming, we rarely build complex applications from scratch. Just as a chef uses pre-made ingredients, a programmer uses pre-written code to perform common tasks. Java provides a vast collection of these tools, called libraries. This chapter introduces how to use these libraries through their Application Programming Interfaces (APIs) to handle tasks like mathematical calculations and text manipulation.
What You Should Be Able to Do
Explain the purpose of an Application Programming Interface (API) and a Java library.
Call
staticmethods from theMathclass to perform calculations.Create
Stringobjects and call non-static (instance) methods to inspect and manipulate them.Use methods like
length(),substring(), andindexOf()onStringobjects.Differentiate between calling a
staticmethod on a class and an instance method on an object.
Key Concepts & Java Implementation
The Core Idea
An Application Programming Interface (API) is a set of specifications and protocols that defines how software components should interact. Think of it as a menu at a restaurant: it tells you what dishes you can order (methods), what you need to provide (ingredients or parameters), and what you will get back (return values), but it hides the complex details of how the kitchen prepares the food.
A Java Library is a collection of pre-written, reusable code in the form of classes and methods. The Java standard library provides thousands of classes to handle everything from file input/output to networking. The Math and String classes are fundamental parts of this library.
A class is a blueprint for creating objects. For example, String is a class. An object is a specific instance of a class, created from that blueprint. For example, "Hello, World!" is a String object.
Syntax & Implementation
Static Methods and the Math Class
Some methods belong to the class itself, not to a specific object created from that class. These are called static methods. They are utility functions that are called using the class name directly. The Math class is a prime example; you never need to create a Math object.
- Syntax Table
| Component | Purpose | Java Example |
|---|---|---|
ClassName.methodName() | The syntax for calling a static method. | Math.random() |
(parameters) | Values passed into the method for it to use. | Math.pow(2.0, 3.0) |
- Annotated Java Examples
// Math.abs() returns the absolute value of a number.
int positiveNum = Math.abs(-15); // positiveNum is now 15
double positiveDouble = Math.abs(-22.5); // positiveDouble is now 22.5
// Math.pow() returns the first argument raised to the power of the second.
double result = Math.pow(2.0, 4.0); // result is 16.0 (2.0 * 2.0 * 2.0 * 2.0)
// Math.random() returns a double value in the range [0.0, 1.0)
// The value includes 0.0 but does not include 1.0.
double randomValue = Math.random(); // e.g., 0.734...
// To generate a random integer in a specific range, we combine methods.
// Example: Simulate a standard six-sided die roll (1-6).
int dieRoll = (int) (Math.random() * 6) + 1;
// 1. Math.random() * 6 gives a double in [0.0, 6.0)
// 2. (int) casts this to an integer: 0, 1, 2, 3, 4, or 5
// 3. + 1 shifts the range to 1, 2, 3, 4, 5, or 6
Instance Methods and the String Class
Most methods in Java are instance methods (or non-static methods). These methods operate on the data of a specific object and must be called on an instance of a class. The String class provides many instance methods for working with text.
A key feature of String objects is that they are immutable, meaning their internal state (the sequence of characters) cannot be changed after they are created. Methods like substring do not modify the original string; they create and return a brand new String object.
- Syntax Table
| Component | Purpose | Java Example |
|---|---|---|
objectReference.methodName() | The syntax for calling an instance method. | myString.length() |
new | A keyword used to create a new object instance. | String s = new String("text"); |
- Annotated Java Examples
// Create a String object. This is the most common way.
String message = "AP Computer Science";
// .length() returns the number of characters in the string.
int len = message.length(); // len is 19
// .indexOf(str) returns the starting index of the first occurrence of str.
// It returns -1 if str is not found. Indices start at 0.
int position = message.indexOf("Computer"); // position is 3
// .substring(from) returns a new string from the 'from' index to the end.
String sub1 = message.substring(12); // sub1 is "Science"
// .substring(from, to) returns a new string from the 'from' index (inclusive)
// up to, but not including, the 'to' index.
String sub2 = message.substring(3, 11); // sub2 is "Computer"
// This gets characters at indices 3, 4, 5, 6, 7, 8, 9, 10.
// Because Strings are immutable, the original 'message' variable is unchanged.
System.out.println(message); // Prints "AP Computer Science"
Tracing & Analysis
- Execution Trace
Let's trace the execution of a sequence of String method calls.
| Line of Code | Variable text | Variable part | Variable len | Variable idx | Explanation |
|---|---|---|---|---|---|
String text = "Java Rock"; | "Java Rock" | (not declared) | (not declared) | (not declared) | text is initialized. |
String part = text.substring(0, 4); | "Java Rock" | "Java" | (not declared) | (not declared) | substring creates a new string "Java". text is unchanged. |
int len = part.length(); | "Java Rock" | "Java" | 4 | (not declared) | length() is called on part. The length of "Java" is 4. |
int idx = text.indexOf(part); | "Java Rock" | "Java" | 4 | 0 | indexOf finds "Java" in text starting at index 0. |
- Analysis
The trace highlights the immutability of String objects. The call to text.substring(0, 4) did not alter text. Instead, it produced a new String object, "Java", which was then assigned to the part variable. This is a critical safety feature in Java, as it prevents one part of a program from unexpectedly modifying a String used elsewhere. Also, note the common pattern: the length of substring(a, b) is b - a.
Java Syntax Quick-Reference
Math.abs(value): Returns the absolute value of anint,double, etc.Math.pow(base, exponent): Returns adoublerepresenting thebaseraised to the power of theexponent.Math.random(): Returns adoublevalue in the range[0.0, 1.0).new ClassName(parameters): Thenewkeyword is an operator that creates a new object instance.stringVar.length(): Returns theintnumber of characters in the string.stringVar.substring(from): Returns a newStringcontaining characters from indexfrom(inclusive) to the end.stringVar.substring(from, to): Returns a newStringcontaining characters from indexfrom(inclusive) toto(exclusive).stringVar.indexOf(str): Returns the startingintindex of the first occurrence ofstr, or -1 if not found.
Core Code Examples & Terminology
API (Application Programming Interface): A specification that defines how a programmer can interact with a piece of software, detailing the available methods, their parameters, and their return values.
Java Library: A collection of pre-written classes and methods that developers can use to perform common tasks without having to write the code from scratch.
Class: A blueprint or template for creating objects that defines their properties (instance variables) and behaviors (methods).
Object: A specific instance of a class, with its own state and access to the class's behaviors.
Constructor: A special method that is called when an object is created with the
newkeyword. It is used to initialize the object's state.Static Method: A method that belongs to a class rather than an object. It is called using the class name (e.g.,
Math.random()).Instance Method: A method that belongs to a specific object. It is called using an object reference variable (e.g.,
myString.length()).Immutable: Describes an object whose state cannot be modified after it has been created.
Stringobjects in Java are immutable.Core Snippet 1 (Static Method Call):
double value = Math.pow(5.0, 2.0); // value becomes 25.0This code calls the
staticmethodpowon theMathclass to calculate a value.Core Snippet 2 (Instance Method Call):
String word = "example"; int len = word.length(); // len becomes 7This code calls the instance method
lengthon theStringobject referenced byword.Core Snippet 3 (Generating a Random Integer):
// Generates a random integer from 10 to 20, inclusive. int num = (int) (Math.random() * 11) + 10;This formula scales and shifts the output of
Math.random()to fit a desired integer range.
Core Skill Check
Code Tracing: What is the final value of
xafter this Java code runs:String s = "documentation"; String sub = s.substring(3, 7); int x = sub.indexOf("m");?Debugging: Identify the compile-time error in this Java code:
String name = "Ada"; name.substring(0, 1) = "a";.Application: Write a single line of Java code that finds the index of the first space character in a
Stringvariable namedsentence.
Common Misconceptions & Errors
Confusing Static vs. Instance Calls: You cannot call an instance method on a class (
String.length()) or a static method on an object (myString.random()). Static methods use the class name; instance methods use the object variable.substringEnd Index is Exclusive: A common mistake is assumingmyString.substring(0, 5)includes the character at index 5. It includes characters at indices 0, 1, 2, 3, and 4 only.Forgetting
StringImmutability: WritingmyString.substring(1);does not changemyString. The method returns a new string, which must be assigned to a variable to be used:String newString = myString.substring(1);.Ignoring the Return Value of
indexOf: TheindexOfmethod returns-1if the substring is not found. If you use this-1value directly in a subsequentsubstringcall, it will cause a runtime error.
Summary
Java's power comes from its extensive libraries, which provide pre-built functionality through a well-defined API. This allows programmers to solve complex problems efficiently by reusing existing code. The Math class offers static utility methods for calculations, which are called directly on the class itself. In contrast, classes like String provide instance methods that are called on specific objects to work with their unique data. Understanding the distinction between a class and an object, and between a static and an instance method, is fundamental to using the Java API correctly and building robust applications.