File File(String, String) in Java

File(String, String): This method is available in the java.io.File class of Java.

Syntax:

java.io.File.File(String parent, String child)

This method takes two arguments. This method creates a new File instance from a parent pathname string and a child pathname string.

Note:

If the parent is null then the new File instance is created as if by invoking the single-argument File constructor on the given child pathname string.

Otherwise the parent pathname string is taken to denote a directory, and the child pathname string is taken to denote either a directory or a file.

Parameters: One parameter is required for this method.

parent: The parent pathname string child The child pathnames string

Throws:

NullPointerException - If the child is null

Approach 1: When no exception

Java

import java.io.File;

public class FileParent2 {
    public static void main(String[] args) {

        String parent = "hello";
        String child = "java";
        File file = new File(parent, child);

        System.out.println(file);
    }
}

Output:

hello\java


Approach 2: NullPointerException 

Java

import java.io.File;

public class FileParent2 {
    public static void main(String[] args) {

        String parent = "hello";
        String child = null;
        File file = new File(parent, child);

        System.out.println(file);
    }
}

Output

Exception in thread "main" java.lang.NullPointerException at java.base/java.io.File.<init>(File.java:319)


No comments:

Post a Comment