- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Package of an Object in Java
The package for an object of a class can be obtained using the getPackage() method with the help of the class loader of the class. If there is no package object created by the class loader of the class, then null is returned.
A program that demonstrates this is given as follows −
Example
import java.util.ArrayList; import java.util.LinkedList; import java.util.HashSet; public class Main { public static void main(String[] args) { System.out.println("The package is: " + new ArrayList().getClass().getPackage().getName()); System.out.println("The package is: " + new LinkedList().getClass().getPackage().getName()); System.out.println("The package is: " + new HashSet().getClass().getPackage().getName()); System.out.println("The package is: " + "This is a string".getClass().getPackage().getName()); System.out.println("The package is: " + new Double(1).getClass().getPackage().getName()); System.out.println("The package is: " + new Integer(1).getClass().getPackage().getName()); } }
Output
The package is: java.util The package is: java.util The package is: java.util The package is: java.lang The package is: java.lang The package is: java.lang
Now let us understand the above program.
The package is obtained and printed by using getClass().getPackage().getName(). A code snippet which demonstrates this is as follows −
System.out.println("The package is: " + new ArrayList().getClass().getPackage().getName()); System.out.println("The package is: " + new LinkedList().getClass().getPackage().getName()); System.out.println("The package is: " + new HashSet().getClass().getPackage().getName()); System.out.println("The package is: " + "This is a string".getClass().getPackage().getName()); System.out.println("The package is: " + new Double(1).getClass().getPackage().getName()); System.out.println("The package is: " + new Integer(1).getClass().getPackage().getName());
Advertisements