Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Java Packages

What is a Package?

A package is a namespace that organizes related classes and interfaces. It prevents naming conflicts and controls access. Packages map directly to directory structures on the filesystem.

Built-in Java Packages

PackageContains
java.langCore classes: String, Math, Object, System, Thread (auto-imported)
java.utilCollections, Scanner, Date, Random, Arrays
java.ioFile I/O: File, InputStream, OutputStream, BufferedReader
java.netNetworking: URL, Socket, HttpURLConnection
java.mathBigInteger, BigDecimal
java.timeModern date/time API: LocalDate, LocalDateTime, Duration
Package Declaration & Import
// File: com/example/utils/MathUtils.java
package com.example.utils;   // package declaration - must be first line

public class MathUtils {
    public static int square(int n) { return n * n; }
    public static double circleArea(double r) { return Math.PI * r * r; }
}
Using Packages & Static Import
package com.example;

// Import a specific class
import com.example.utils.MathUtils;

// Import all classes in a package (wildcard)
import java.util.*;

// Static import - import static members directly
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;

public class Main {
    public static void main(String[] args) {
        // Using imported class
        System.out.println(MathUtils.square(5));          // 25
        System.out.println(MathUtils.circleArea(3.0));    // 28.27...

        // Using java.util classes
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        System.out.println(names);  // [Alice, Bob]

        // Using static import - no Math. prefix needed
        System.out.println(PI);          // 3.141592653589793
        System.out.println(sqrt(16.0));  // 4.0
    }
}
Key Takeaways
  • Packages organize related classes and interfaces - they prevent naming conflicts.
  • The package statement must be the first line in a Java source file.
  • Java's standard library is organized into packages: java.lang, java.util, java.io, java.net, etc.
  • java.lang is automatically imported - you don't need to import String, Math, or System.
  • Use import statements to use classes from other packages without fully qualifying them.
  • Use wildcard imports (import java.util.*) sparingly - explicit imports are clearer.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.