← Back to Chapters

Java User Defined Packages

? Java User Defined Packages

? Quick Overview

A user defined package in Java is a package created by the programmer to group related classes and interfaces. It improves code organization, reusability, and access control in large applications.

? Key Concepts

  • Packages act as folders for Java classes
  • User defined packages are created using the package keyword
  • They help avoid class name conflicts
  • Packages support access protection

? Syntax / Theory

A package statement must be the first line of a Java source file. The compiled class files are stored in directory structures matching the package name.

? Code Example(s)

? View Code Example
// Defining a user defined package
package com.mycompany.utils;

public class Calculator {
// Method to add two numbers
public int add(int a, int b) {
return a + b;
}
}
? View Code Example
// Using a user defined package
import com.mycompany.utils.Calculator;

public class MainApp {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(10, 20));
}
}

? Live Output / Explanation

Output

30

The Calculator class is accessed using the import statement. The JVM locates the class using the directory structure of the package.

? Interactive Package Simulator

Type a package and class name below to see how Java creates the folder structure and how to import it.

? Directory Structure

 

⚙️ Generated Code

 

✅ Tips & Best Practices

  • Use reverse domain naming for package names
  • Keep related classes in the same package
  • Avoid default package in real projects
  • Compile using javac -d . FileName.java

? Try It Yourself

  • Create a package named com.school.student
  • Add a class with student details
  • Access it from another class
  • Compile and run using command line