Course contentsShow
← Java
Lesson 2027 of 2,87041. NIO.2 and the Path APIFree lesson

Absolute vs Relative Paths

Understand the difference between absolute and relative paths, and use isAbsolute() to distinguish between them.

Absolute vs Relative Paths

You'll learn how to distinguish between absolute and relative paths using the isAbsolute() method.

Understanding Path Types

When working with the Path interface, you'll encounter two fundamental types of paths:

Absolute paths specify the complete location of a file or directory from the root of the filesystem. Think of them like a full street address: "123 Main Street, Springfield, IL 62701" — it tells you exactly where something is, no matter where you're currently standing.

Relative paths specify a location relative to some starting point (usually the current working directory). These are like directions: "two blocks north, then turn right" — they only make sense if you know where you're starting from.

Examples of Each Type

On Windows, an absolute path looks like:

C:\Users\Alice\documents\report.txt

A relative path might look like:

documents\report.txt

On Unix/Linux/macOS, an absolute path starts with /:

/home/alice/documents/report.txt

A relative path would be:

documents/report.txt

Using isAbsolute()

The Path interface provides the isAbsolute() method to check which type you're dealing with:

Path absolutePath = Paths.get("/home/alice/file.txt");
Path relativePath = Paths.get("documents/file.txt");

System.out.println(absolutePath.isAbsolute());  // true
System.out.println(relativePath.isAbsolute());  // false

This method is crucial when you need to verify whether a path is self-contained or depends on a working directory context.

Key Takeaway: Absolute paths specify complete locations from the filesystem root and return true for isAbsolute(), while relative paths depend on a starting directory and return false.