Java - Write code to Return the package name of the given Java class name.

Requirements

Write code to Return the package name of the given Java class name.

Demo

/*
 * Copyright (c) 2001-2002, Marco Hunsicker. All rights reserved.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 *//*from w w  w  . j a v a  2 s . c  om*/
 
//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String name = "com.book2s.exam";
        System.out.println(getPackageName(name));
    }

    private static final String EMPTY_STRING = "" /* NOI18N */.intern();

    /**
     * Returns the package name of the given Java class name.
     *
     * @param name class name for which the package name should be returned.
     *
     * @return package name of the given class name. Returns the empty string if the
     *         given name contains no package name (the default package).
     *
     * @see #getClassName
     */
    public static String getPackageName(String name) {
        int lastDot = name.lastIndexOf('.');

        if (lastDot > 0) {
            return name.substring(0, lastDot);
        }

        return EMPTY_STRING;
    }
}