ResourceBundle containsKey(String) in Java

containsKey(String): This method is available in java.util.ResourceBundle class of Java.

Syntax:

boolean java.util.ResourceBundle.containsKey(String key)

This method takes one argument. This method determines whether the given key is contained in this ResourceBundle or its parent bundles.

Parameters: One parameter is required for this method.

key: the resource key.

Returns: true if the given key is contained in this ResourceBundle or its parent bundles; false otherwise.

Throws:

NullPointerException - if the key is null.

Approach 1: When no exception

Java

import java.util.Locale;
import java.util.ResourceBundle;

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

        ResourceBundle bundle =
ResourceBundle.getBundle("Hello", Locale.US);

        String key = "Hello";
        System.out.println(bundle.containsKey(key));
    }
}

Output:

true


Approach 2: NullPointerException 

Java

import java.util.Locale;
import java.util.ResourceBundle;

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

        ResourceBundle bundle =
ResourceBundle.getBundle("Hello", Locale.US);

        String key = null;
        System.out.println(bundle.containsKey(key));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.ResourceBundle.containsKey(ResourceBundle.java:2302) at com.example.ListResourceBundle.ResourceBundlecontainsKey.main(ResourceBundlecontainsKey.java:12)


No comments:

Post a Comment