Java Packages

JK JK 2038 
Created at
Updated at  
7,285 0 0

In Java, packages act like file folders to group related classes, helping developers write maintainable code and prevent naming conflicts. Packages are divided into built-in packages from the Java API library and user-defined packages created by developers. Built-in functionality, such as utility classes like Scanner, can be accessed using the import keyword to bring in either a single class or an entire package using an asterisk. Developers can also create their own user-defined packages by placing a package declaration at the top of a source file, keeping package names in lowercase, and compiling them with the javac -d command to generate the required directory structure for execution.

 

Java Packages & API

A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:

  • Built-in Packages (packages from the Java API)
  • User-defined Packages (create your own packages)


 

Built-in Packages

The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.

The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:

import package.name.Class;   // Import a single class
import package.name.*;   // Import the whole package


 

Import a Class

If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read a complete line:

import java.util.Scanner;

class MyClass {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter username");

    String userName = myObj.nextLine();
    System.out.println("Username is: " + userName);
  }
}


 

Import a Package

There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in the java.util package:

import java.util.*;


 

User-defined Packages

To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:

└── root
  └── mypack
    └── MyPackageClass.java

MyPackageClass.java

package mypack;
class MyPackageClass {
  public static void main(String[] args) {
    System.out.println("This is my package!");
  }
}

Save the file as MyPackageClass.java, and compile it:

C:\Users\Your Name>javac MyPackageClass.java

Then compile the package:

C:\Users\Your Name>javac -d . MyPackageClass.java

This forces the compiler to create the "mypack" package.

The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign ".", like in the example above.

Note: The package name should be written in lower case to avoid conflict with class names.

 

When we compiled the package in the example above, a new folder was created, called "mypack".

To run the MyPackageClass.java file, write the following:

C:\Users\Your Name>java mypack.MyPackageClass

The output will be:

This is my package!

 

Tags Java Java Packages Facebook X
Comments 0
Similar posts
  1. Java Inheritance (Subclass and Superclass)
    7,273
  2. Java Polymorphism
    7,155
  3. Java Classes and Objects
    7,219
  4. Java Inner Classes
    7,178
  5. Java Recursion
    7,292
  6. Java Scope
    7,218
  7. Java Methods
    7,191
  8. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    8,083
  9. Java Switch Statements
    7,542
  10. Java Short Hand If...Else (Ternary Operator)
    7,715
  11. Java If ... Else
    7,529
  12. Java Math
    7,572
  13. Java Variables
    7,616
  14. Java Comments
    8,243
  15. The Print() Method
    7,260
  16. Java Syntax
    7,590
  17. Java Getting Started
    7,530
  18. What is Java?
    7,181
  19. Machine Learning Types and Programming Languages
    7,359
  20. Java Tutorials associated with AP Computer Science A
    7,804
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,287
  22. Java Servlet Example
    7,214
  23. Difference between Java and Javascript
    7,774
  24. Challenge: One Code Problem Per Day
    1,316
  1. How do I replace content that based on the HTML UI Template
    7,246
  2. Dataset of California Foodbanks
    7,267
  3. Java Abstract Classes and Methods
    7,940
  4. Java Arrays
    9,130
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    1,040
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    914
  3. Michael Jackson's Billie Jean
    434
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    414
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    361
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    399
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    397
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    424
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    1,397
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    574
  11. The Evolution and Production Reality of Agentic AI
    457
  12. How to Activate or Waive Your UIUC Student Health Insurance
    589
  13. Complete Guide to Building a Machine Learning Model
    602
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,647
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    608
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,387
  17. Clean Python Environments: The Power of venv vs. Docker
    1,130
  18. What is Docker? Why is Docker also useful in a development environment?
    842
  19. UIUC 2026-2027 Academic Calendar
    2,087
  20. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    1,103
  21. Open-Source LLMs: The AI Revolution
    1,007
  22. Resume 2.0: Leveling Up for My First Software Gig
    3,072
  23. Not everyone will understand what this man just did
    2,529
  24. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,900
  25. Unpacking IU's Shopper
    1,002
  26. Jackie Chan's Police Story: The Action Masterpiece
    894
  27. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,246
  28. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,418
  29. Open Databases for Sex Crime Occurrences in the U.S.
    1,009
  30. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,488
  31. My First Day at University of Illinois-Urvana Champaign
    1,402
  32. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,453
  33. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,520
  34. Sipping the Stars: My Starbucks Adventure
    10,227
  35. Exciting explore at Sequoia National Park
    7,887
  36. My Life Shot at Death Valley
    2,100
  37. Ip Man fights with Muay Thai Master
    1,165
  38. Mad Clown - Don't Die
    1,280
  39. How to get Student Enrollment and Degree Verification at UIUC
    6,017
  40. LAX Thanksgiving Rush: A Joyful Reunion
    1,115
  41. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,387
  42. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,171
  43. 10CM - To Reach You (너에게 닿기를)
    1,356
  44. Feeling weak? Transform yourself at the UIUC ARC!
    1,770
  45. BOYNEXTDOOR - If I Say I Love You
    1,409
  46. The Future of Software Engineer - AI Engineering
    1,130
  47. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,139
  48. Lie - Legend song by BIGBANG
    8,032
  49. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,125
  50. Reimbursement after Vaccination at McKinley Health Center
    1,254