Java Programming - Lesson 13
Java Libraries and Documentation Explained: A Beginner's Guide to the Java API
Introduction
One of the greatest advantages of learning Java is that you do not have to write every programming feature from scratch.
Java provides an extensive collection of ready-made classes, interfaces, and methods that programmers can use to perform common and specialised tasks.
These resources are organised into libraries and packages and are collectively documented through the Java API documentation.
Whether you want to manipulate text, perform mathematical calculations, read files, create graphical applications, or build complex software systems, Java provides existing tools that can help.
In this tutorial, you will learn:
What Java libraries are.
How Java packages organise classes.
Why object-oriented libraries are useful.
How to navigate Java's official documentation.
How to understand constructors and methods.
What inherited methods mean.
How to explore useful Java classes through practical examples.
How to use documentation when developing your own programs.
1. What Are Java Libraries?
A library is a collection of reusable programming components that developers can incorporate into their applications.
Instead of writing every operation from the beginning, programmers can use existing classes and methods.
For example, suppose you want to convert a string containing the number "250" into an integer.
You do not need to write your own conversion algorithm. Java already provides the Integer.parseInt() method.
Similarly, if you want to generate a random number, you can use Math.random().
Java's libraries save development time, reduce unnecessary repetition, and provide tested functionality.
2. Understanding Java Packages
Java organises related classes and interfaces into packages.
A package acts as a namespace and helps programmers organise their code logically.
For example, the Java platform includes packages such as:
Package
Main purpose
java.lang
Fundamental classes used by Java programs
java.util
Utility classes, collections, dates, and related tools
java.io
Input and output operations
java.nio
Modern input/output and file-system functionality
java.net
Networking operations
java.awt
Basic graphical user-interface components
javax.swing
Components for building graphical user interfaces
These are examples of Java platform packages. The exact APIs available depend on the Java version being used.
Why Are Packages Important?
Imagine a large software project containing hundreds of classes.
Without proper organisation, finding and maintaining these classes could become difficult.
Packages help solve this problem by grouping related components together.
For example, classes responsible for reading and writing files can be organised within the java.io package.
This makes the Java platform easier to navigate and maintain.
3. Understanding Object-Oriented Libraries
Java is an object-oriented programming language.
In object-oriented programming, classes define the structure and behaviour of objects.
A well-designed class should have clearly defined responsibilities.
For example, consider a class called Duck.
It might contain methods such as:
quack();
swim();
fly();
Each method represents a behaviour associated with the object.
A method named quack() should perform the action of quacking rather than unexpectedly performing unrelated operations.
This illustrates an important software-design principle: classes and methods should have meaningful names that accurately communicate their responsibilities.
Encapsulation
Encapsulation means organising data and the methods that operate on that data within a class while controlling access to the internal details.
For example:
public class BankAccount {
private double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance;
}
}
In this example:
balance is private, so it cannot be accessed directly from unrelated classes.
deposit() provides a controlled way to increase the balance.
getBalance() allows other parts of the program to retrieve the balance.
This design helps protect the object's internal data and makes its behaviour easier to understand.
4. Accessing Java's Official Documentation
Java's official documentation is one of the most useful resources available to programmers.
The original video uses the Java SE 7 API documentation:
http://docs.oracle.com/javase/7/docs/api/
That address documents an older version of Java.
For modern Java development, you should consult the current Java documentation:
https://docs.oracle.com/en/java/javase/
The documentation provides information about classes, interfaces, constructors, methods, fields, inheritance, and exceptions.
Understanding the Structure of the Documentation
Java API documentation is generally organised around three important elements:
Packages: Collections of related classes and interfaces.
Classes and interfaces: The individual components available within packages.
Members: The constructors, methods, and fields provided by those classes.
When you open a class documentation page, you will commonly find the following sections:
Class description
Constructor summary
Method summary
Field summary, where applicable
Inherited methods
Detailed descriptions of constructors and methods
Understanding these sections makes it easier to find the information you need.
5. Practical Example: Exploring the String Class
The String class belongs to the java.lang package.
It is used to represent sequences of characters.
For example:
String message = "Welcome to Java Programming!";
Java provides many methods for manipulating and examining strings.
Let's examine four useful methods.
A. charAt()
The charAt() method returns the character at a specified index.
Remember that Java uses zero-based indexing.
Example:
public class StringExample {
public static void main(String[] args) {
String message = "JAVA";
char letter = message.charAt(1);
System.out.println(letter);
}
}
Output:
A
The first character is at index 0, while the second character is at index 1.
If you provide an index outside the valid range, Java throws a StringIndexOutOfBoundsException.
B. compareTo()
The compareTo() method compares two strings lexicographically.
Example:
public class CompareStrings {
public static void main(String[] args) {
String first = "Apple";
String second = "Banana";
int result = first.compareTo(second);
System.out.println(result);
}
}
Because "Apple" comes before "Banana" in lexicographical order, the result is negative.
Important: compareTo() does not simply return only -1, 0, or 1. It returns a negative integer, zero, or a positive integer depending on the comparison.
C. format()
The String.format() method creates a formatted string.
Example:
public class FormatExample {
public static void main(String[] args) {
String name = "Emmanuel";
int age = 30;
String message = String.format(
"My name is %s and I am %d years old.",
name,
age
);
System.out.println(message);
}
}
Output:
My name is Emmanuel and I am 30 years old.
Here:
%s represents a string.
%d represents an integer.
D. matches()
The matches() method checks whether an entire string matches a specified regular expression.
Example:
public class MatchesExample {
public static void main(String[] args) {
String number = "12345";
boolean result = number.matches("\\d+");
System.out.println(result);
}
}
Output:
true
The expression \\d+ checks whether the string contains one or more digits.
This method is useful when validating simple text patterns.
6. Understanding Constructors and Methods
When reading Java documentation, you will frequently encounter two important terms: constructors and methods.
What Is a Constructor?
A constructor is a special class member used when creating an object.
For example:
String message = new String("Hello");
Here, String("Hello") invokes a constructor.
However, Java allows us to create strings more conveniently using:
String message = "Hello";
This uses a string literal.
A class may provide several constructors that allow objects to be created in different ways.
These different constructor options are called constructor overloading.
What Is a Method?
A method represents an operation that a class or object can perform.
For example:
String message = "Hello";
int length = message.length();
The length() method returns the number of characters in the string.
The documentation explains the purpose of each method, its parameters, its return type, and possible exceptions.
7. Understanding Inheritance and Inherited Methods
Inheritance is an important feature of object-oriented programming.
It allows a new class to extend an existing class and reuse its accessible members.
For example:
class Person {
String name;
void introduce() {
System.out.println("My name is " + name);
}
}
class VIPPerson extends Person {
String membershipLevel;
}
The VIPPerson class inherits the accessible members of Person.
This means an object of VIPPerson can use the inherited name field and introduce() method.
Example:
public class InheritanceExample {
public static void main(String[] args) {
VIPPerson vip = new VIPPerson();
vip.name = "Emmanuel";
vip.membershipLevel = "Gold";
vip.introduce();
System.out.println(vip.membershipLevel);
}
}
Output:
My name is Emmanuel
Gold
Notice that the VIPPerson class does not need to define the introduce() method again.
It inherits that method from Person.
What Is Polymorphism?
Polymorphism allows an object of a subclass to be treated as an object of its superclass.
For example:
Person individual = new VIPPerson();
Although the variable is declared as type Person, it refers to an actual VIPPerson object.
This is why Java documentation sometimes lists methods inherited from other classes.
When examining a class, remember that some methods available to it may come from its parent classes rather than being declared directly inside it.
8. Practical Example: Exploring the Integer Class
The Integer class belongs to the java.lang package.
It provides useful methods for working with integer values.
One important method is parseInt().
Converting a String to an Integer
Example:
public class IntegerExample {
public static void main(String[] args) {
String numberText = "250";
int number = Integer.parseInt(numberText);
System.out.println(number + 50);
}
}
Output:
300
The parseInt() method converts the text "250" into the integer 250.
The program can then perform ordinary arithmetic operations on the result.
Understanding NumberFormatException
What happens if the string does not contain a valid integer?
For example:
String numberText = "Hello";
int number = Integer.parseInt(numberText);
Java cannot convert "Hello" into an integer.
Consequently, the program throws a NumberFormatException.
We can handle this situation using a try-catch statement:
public class ExceptionExample {
public static void main(String[] args) {
String numberText = "Hello";
try {
int number = Integer.parseInt(numberText);
System.out.println(number);
} catch (NumberFormatException e) {
System.out.println("Please provide a valid integer.");
}
}
}
Output:
Please provide a valid integer.
This demonstrates why reading the exception information in Java documentation is important.
It helps programmers understand what can go wrong when using a particular method.
9. Practical Example: Exploring the Math Class
The Math class belongs to the java.lang package.
It provides mathematical methods that can be used without creating a Math object.
One interesting method is Math.random().
It returns a pseudorandom double value in the range:
0.0 <= value < 1.0
Example:
public class RandomExample {
public static void main(String[] args) {
double number = Math.random();
System.out.println(number);
}
}
The output will be different across executions. For example:
0.735214
The exact value is not guaranteed.
Generating a Random Whole Number
We can use Math.random() to generate an integer between 1 and 10:
public class RandomNumber {
public static void main(String[] args) {
int number = (int) (Math.random() * 10) + 1;
System.out.println(number);
}
}
The result will be a whole number from 1 through 10.
This can be useful when creating simple games, simulations, and randomised activities.
10. Practical Example: Exploring the FileReader Class
Java provides the FileReader class in the java.io package.
It is designed for reading character-based data from files.
For example:
FileReader reader = new FileReader("example.txt");
This creates a reader for a file named example.txt.
The FileReader class inherits reading functionality from its parent classes.
One inherited method is read().
The following complete example reads a text file one character at a time:
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
try (FileReader reader = new FileReader("example.txt")) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
}
}
}
If example.txt contains:
Welcome to Java!
Learning Java is interesting.
The program displays:
Welcome to Java!
Learning Java is interesting.
Understanding the Example
FileReader opens the file for reading.
reader.read() reads the next character.
The method returns -1 when the end of the file is reached.
(char) character converts the returned integer into a character.
The while loop continues until the entire file has been read.
The try-with-resources statement automatically closes the reader.
The catch block handles possible input/output errors.
This example also demonstrates how documentation helps programmers understand inherited methods and possible exceptions.
11. How to Read Java Documentation Effectively
When you open the documentation for an unfamiliar Java class, do not feel that you must understand everything on the page immediately.
Instead, follow these steps:
Step 1: Identify the class.
Confirm that you are examining the correct class for the task you want to perform.
Step 2: Read the class description.
Understand what the class is designed to do.
Step 3: Examine its constructors.
Find out how objects of the class can be created.
Step 4: Examine the method summary.
Look for methods that perform the operation you need.
Step 5: Read the detailed method description.
Check the parameters, return type, behaviour, and possible exceptions.
Step 6: Check inherited methods.
Some useful methods may be provided by parent classes.
Step 7: Test the method in a small program.
Writing and running a simple example helps confirm your understanding.
12. Why Java Documentation Is Important
Learning to use documentation is an essential part of becoming a competent programmer.
It helps you:
Discover existing Java features.
Avoid unnecessarily rewriting existing functionality.
Understand unfamiliar classes and methods.
Learn how to provide the correct arguments to methods.
Identify expected return values.
Understand possible errors and exceptions.
Write more reliable and maintainable applications.
Become more independent when solving programming problems.
Professional programmers do not memorise every class and method in Java. They develop the ability to find the information they need and apply it correctly.
13. Practical Exercises
Test your understanding by completing the following exercises.
Exercise 1: String Class
Write a Java program that stores your full name in a string variable and displays:
The complete name.
The number of characters.
The first character.
The last character.
Exercise 2: Integer Class
Write a program that converts the string "450" into an integer and adds 150 to it.
Exercise 3: Exception Handling
Modify Exercise 2 so that the program handles an invalid number using try-catch.
Exercise 4: Math Class
Write a program that generates and displays a random whole number between 1 and 100.
Exercise 5: FileReader Class
Create a text file containing three sentences. Write a Java program that reads the file and displays its contents.
Conclusion
Java provides a powerful collection of libraries that make programming easier and more productive.
These libraries contain reusable classes and methods for handling text, numbers, mathematical calculations, files, networking, graphical interfaces, and many other tasks.
In this lesson, we explored the String, Integer, Math, and FileReader classes and examined how inheritance makes additional methods available to a class.
Most importantly, we learned that Java's official documentation is not simply a reference for experienced programmers. It is also a valuable learning resource for beginners.
As you progress in your programming journey, develop the habit of consulting documentation, experimenting with examples, and learning how existing Java components work.
Watch the accompanying video tutorial via the link below:
https://youtu.be/EVlwRCgMvAk?si=35mYgYlEpqIxVcjs
Remember: You do not need to know everything about Java. You need to know how to find the information that helps you solve the problem in front of you.
Happy coding!


Comments
Post a Comment
Welcome to Creative Skills & Hobbies Hub!
This blog is dedicated to recognizing, showcasing, and promoting diverse creative skills and hobbies, with the aim of helping individuals discover and nurture their own creative potentials, etc. We encourage you to share your thoughts, ask questions, and engage with our community.
Your voice matters! Whether you have a new hobby to explore, insights to offer, or creative stories to tell, we’d love to hear from you. Leave a comment below and join the conversation!