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.
package keywordA 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.
// 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;
}
}
// 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));
}
}
30
The Calculator class is accessed using the import statement. The JVM locates the class using the directory structure of the package.
Type a package and class name below to see how Java creates the folder structure and how to import it.
javac -d . FileName.javacom.school.student