Java Path getName() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, path.getName(index) returns the name element at position index as a one-element Path. Index 0 is the element closest to the root, and the last index is getNameCount() - 1, which is the file name.

The root is not a name element, so for /home/anna/docs/report.txt, getName(0) is home, not /. Indexes outside the range throw an exception instead of returning null.

An instance method of the java.nio.file.Path interface, available since Java 7. Call it on a Path object, as in path.getName(...), after import java.nio.file.Path;.

Syntax

Pass a zero-based index between 0 and getNameCount() - 1:

Java
Path p = Paths.get("/home/anna/docs/report.txt");
Path first = p.getName(0);                       // home
Path last = p.getName(p.getNameCount() - 1);     // report.txt
CallWhat it does
p.getName(0)The first name after the root, such as the top folder.
p.getName(p.getNameCount() - 1)The last name; the same text as getFileName().
p.getName(i).toString()The element as a String for text comparisons.

Since Java 7. Looping i from 0 to getNameCount() - 1 visits the same elements as iterator().

Library declarations
Java
// java.nio.file.Path (interface)
Path getName(int index)

Parameters

ParameterDescription
indexPosition of the element, counting from 0 at the root side. Must be at least 0 and less than getNameCount().

Return Value

Return ValueDescription
PathA relative path with exactly one name element.

Compare with Similar Methods

Ways to reach name elements:

MethodHow it differs
getNameCount()How many indexes are valid.
subpath(begin, end)Several neighbouring elements at once.
iterator()All elements in order, without index arithmetic.

Java Examples

Outputs below are shown for Linux and macOS. On Windows, Java prints \ between names instead of /; the note above each output says when a result really differs.

Example 1 — Print Every Name Element with Its Index

Loop from 0 to getNameCount() - 1 and print what getName(i) returns for an absolute path.

Java
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathGetNameBasic {
    public static void main(String[] args) {
        Path p = Paths.get("/home/anna/docs/report.txt");
        for (int i = 0; i < p.getNameCount(); i++) {
            System.out.println("getName(" + i + ") = " + p.getName(i));
        }
    }
}

How It Works

  1. Indexes start after the root. The leading / is not an element, so index 0 is home and the four names use indexes 0 to 3.
  2. The loop bound comes from the path. i < p.getNameCount() stops right after index 3, so the loop never asks for an element that does not exist.
  3. Single names print the same everywhere. Each result holds just one name and no separator, so this output does not change between Windows and Linux.

Example 2 — Read the Top-Level Folder of Project Files

Use getName(0) to tell which part of a project each file belongs to, and the last index for its name.

Java
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathGetNameTopFolder {
    public static void main(String[] args) {
        Path[] files = {Paths.get("src/main/App.java"), Paths.get("docs/guide.md"),
                        Paths.get("test/AppTest.java"), Paths.get("README.md")};
        for (Path f : files) {
            int last = f.getNameCount() - 1;
            String area = last == 0 ? "(project root)" : f.getName(0).toString();
            System.out.println(f.getName(last) + " belongs to " + area);
        }
    }
}

How It Works

  1. Index of the file name. getNameCount() - 1 is the last valid index, so getName(last) is the file name of each relative path.
  2. Index 0 is the top folder. For src/main/App.java the first element is src; toString() turns it into a String so it can share a variable with the fallback text.
  3. One element means no folder. README.md has a single name, so last is 0 and the program prints (project root) instead of treating the file itself as its folder.

Example 3 — Catch the Exception for an Invalid Index

Try indexes that are too large, negative, and used on a root path, and print the exception class each one throws.

Java
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathGetNameBadIndex {
    static void tryName(Path p, int index) {
        try {
            System.out.println(p + " getName(" + index + ") = " + p.getName(index));
        } catch (IllegalArgumentException e) {
            System.out.println(p + " getName(" + index + ") -> " + e.getClass().getSimpleName());
        }
    }

    public static void main(String[] args) {
        Path music = Paths.get("music/rock/song.mp3");
        tryName(music, 2);
        tryName(music, 3);
        tryName(music, -1);
        tryName(Paths.get("/"), 0);
    }
}

How It Works

  1. The highest valid index. The path has three names, so index 2 is the last one that works and returns song.mp3.
  2. Too far either way. Index 3 equals the name count and -1 is negative; both are rejected with IllegalArgumentException, not an array-style index exception.
  3. A root has nothing to index. Paths.get("/") has zero names, so even index 0 fails; check getNameCount() > 0 before reading elements of a path that could be a root.

Frequently Asked Questions

The name element at that zero-based index, as a Path with one name. For /home/anna/report.txt, getName(0) is home and getName(2) is report.txt.
No. The root is not a name element, so index 0 is the first name after the root.
IllegalArgumentException, when the index is negative or not less than getNameCount(). It also throws for a root path, which has no names.
For a file path, use path.getName(path.getNameCount() - 2), after checking that getNameCount() is at least 2. path.getParent().getFileName() gives the same name.
getName returns a Path, and a Path is never equal to a String. Compare getName(0).toString() with "home" instead.

Next: Path.getNameCount()

Count the name elements in a path; the root is not counted.

getNameCount() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful