Chapter 12: Packages

Interpreter vs Compiler

Understanding how programming languages are executed

Interpreter vs Compiler

Aspect Interpreter Compiler
Translation One statement at a time Entire program at a time
Execution Interpreter is needed every time Once compiled, it is not needed
Error Handling Partial execution if error occurs No execution if an error occurs
Development Easy for programmers Usually not as easy as interpreted ones
Speed Slower execution Faster execution

Is Java Compiled or Interpreted?

Java is a hybrid language → both compiled as well as interpreted

Java Execution Process

📝
Java Source Code
Harry.java
⚙️
Java Compiler
javac Harry.java
📦
Bytecode
Harry.class
🖥️
JVM Interpreter
java Harry
Machine Code
Platform Specific

Executing a Java Program

1
Compile: javac Harry.java → Creates Harry.class
2
Execute: java Harry → Runs the bytecode

Platform Independence

This bytecode can be taken to any platform (Windows/Mac/Linux) for execution.

Hence Java is platform independent (Write Once Run Everywhere)

Terminal Commands
# Compile Java file
javac MyProgram.java

# Run compiled bytecode
java MyProgram

# Compile and create package
javac -d . MyProgram.java

Note: So far the execution of our program was being managed by IntelliJ IDEA. We can download a source code editor like VS Code to compile & execute our Java programs manually.

Packages in Java

A package is used to group related classes.

Packages help in avoiding name conflicts and organizing code better.

Built-in Packages

Java API packages provided by Oracle

  • java.lang - Basic classes
  • java.util - Utility classes
  • java.io - Input/Output classes
  • java.net - Networking classes
  • User-defined Packages

    Custom packages created by developers

  • com.company.project
  • org.example.utils
  • Package Organization (Like File System)

    Files

    Song.mp3
    Photo.jpg
    Video.mp4

    Java Classes

    Song.java
    Photo.java
    Video.java

    Organized Packages

    com.media.audio
    com.media.image
    com.media.video

    Creating a Package

    Creating Simple Package
    # Simple compilation
    javac Harry.java → Creates Harry.class
    
    # Create package folder structure
    javac -d . Harry.java → Creates package folder and class file

    Package Declaration and Creation

    com/company/utils/Calculator.java
    package com.company.utils;
    
    public class Calculator {
        public static int add(int a, int b) {
            return a + b;
        }
        
        public static int subtract(int a, int b) {
            return a - b;
        }
        
        public static int multiply(int a, int b) {
            return a * b;
        }
        
        public static double divide(int a, int b) {
            if (b != 0) {
                return (double) a / b;
            }
            throw new IllegalArgumentException("Division by zero");
        }
    }
    com/company/shapes/Circle.java
    package com.company.shapes;
    
    public class Circle {
        private double radius;
        
        public Circle(double radius) {
            this.radius = radius;
        }
        
        public double getArea() {
            return Math.PI * radius * radius;
        }
        
        public double getCircumference() {
            return 2 * Math.PI * radius;
        }
        
        public double getRadius() {
            return radius;
        }
    }

    Inner Packages

    We can also create inner packages by adding package "inner" as package name

    Note: These packages once created can be used by other classes.

    Using a Java Package

    To use classes from packages, we need to import them.

    Import Statements

    ImportExamples.java
    // Import specific class
    import java.util.Scanner;
    import java.util.ArrayList;
    
    // Import all classes from a package
    import java.util.*;
    
    // Import specific class from custom package
    import com.company.utils.Calculator;
    import com.company.shapes.Circle;
    
    // Import all classes from custom package
    import com.company.shapes.*;
    
    public class ImportExamples {
        public static void main(String[] args) {
            // Using imported classes
            Scanner scanner = new Scanner(System.in);
            ArrayList list = new ArrayList<>();
            
            // Using custom package classes
            Calculator calc = new Calculator();
            Circle circle = new Circle(5.0);
            
            System.out.println("Circle area: " + circle.getArea());
            System.out.println("Addition: " + Calculator.add(10, 20));
        }
    }

    Specific Import

    import java.lang.String;

    Import specific class from java.lang

    Wildcard Import

    import java.lang.*;

    Import everything from java.lang

    Default Import

    String s = new String("Harry");

    java.lang is imported by default

    PackageUsageExample.java
    import com.company.utils.Calculator;
    import com.company.shapes.*;
    
    public class PackageUsageExample {
        public static void main(String[] args) {
            // Using Calculator from utils package
            int sum = Calculator.add(15, 25);
            int difference = Calculator.subtract(30, 10);
            
            System.out.println("Sum: " + sum);
            System.out.println("Difference: " + difference);
            
            // Using Circle from shapes package
            Circle circle = new Circle(7.5);
            System.out.println("Circle Area: " + circle.getArea());
            System.out.println("Circle Circumference: " + circle.getCircumference());
            
            // Using Rectangle from shapes package (if exists)
            // Rectangle rect = new Rectangle(10, 5);
            // System.out.println("Rectangle Area: " + rect.getArea());
        }
    }

    Access Modifiers in Java

    Access modifiers determine whether other classes can use a particular field or invoke a particular method.

    Can be public, private, protected or default (no modifier).

    Access Modifiers Scope

    Modifier Class Package Subclass World
    public ✅ Y ✅ Y ✅ Y ✅ Y
    protected ✅ Y ✅ Y ✅ Y ❌ N
    default (no modifier) ✅ Y ✅ Y ❌ N ❌ N
    private ✅ Y ❌ N ❌ N ❌ N

    Access Modifier Examples

    com/example/AccessExample.java
    package com.example;
    
    public class AccessExample {
        public String publicField = "Public - accessible everywhere";
        protected String protectedField = "Protected - accessible in package and subclasses";
        String defaultField = "Default - accessible in same package only";
        private String privateField = "Private - accessible in same class only";
        
        public void publicMethod() {
            System.out.println("Public method - accessible everywhere");
        }
        
        protected void protectedMethod() {
            System.out.println("Protected method - accessible in package and subclasses");
        }
        
        void defaultMethod() {
            System.out.println("Default method - accessible in same package only");
        }
        
        private void privateMethod() {
            System.out.println("Private method - accessible in same class only");
        }
        
        public void demonstrateAccess() {
            // All fields and methods accessible within same class
            System.out.println(publicField);
            System.out.println(protectedField);
            System.out.println(defaultField);
            System.out.println(privateField);
            
            publicMethod();
            protectedMethod();
            defaultMethod();
            privateMethod();
        }
    }
    com/example/SamePackageClass.java
    package com.example;
    
    public class SamePackageClass {
        public void testAccess() {
            AccessExample obj = new AccessExample();
            
            // Accessible: public, protected, default
            System.out.println(obj.publicField);
            System.out.println(obj.protectedField);
            System.out.println(obj.defaultField);
            // System.out.println(obj.privateField); // Error - not accessible
            
            obj.publicMethod();
            obj.protectedMethod();
            obj.defaultMethod();
            // obj.privateMethod(); // Error - not accessible
        }
    }
    com/other/DifferentPackageClass.java
    package com.other;
    
    import com.example.AccessExample;
    
    public class DifferentPackageClass {
        public void testAccess() {
            AccessExample obj = new AccessExample();
            
            // Only public accessible from different package
            System.out.println(obj.publicField);
            // System.out.println(obj.protectedField); // Error - not accessible
            // System.out.println(obj.defaultField); // Error - not accessible
            // System.out.println(obj.privateField); // Error - not accessible
            
            obj.publicMethod();
            // obj.protectedMethod(); // Error - not accessible
            // obj.defaultMethod(); // Error - not accessible
            // obj.privateMethod(); // Error - not accessible
        }
    }
    
    class SubclassExample extends AccessExample {
        public void testInheritedAccess() {
            // In subclass: public and protected accessible
            System.out.println(publicField);
            System.out.println(protectedField);
            // System.out.println(defaultField); // Error - different package
            // System.out.println(privateField); // Error - not accessible
            
            publicMethod();
            protectedMethod();
            // defaultMethod(); // Error - different package
            // privateMethod(); // Error - not accessible
        }
    }

    Practice Set

    Chapter 12 - Practice Set

    1. Calculator Package

    Create three classes Calculator, ScCalculator and HybridCalculator and group them into a package.

    2. Built-in Package Usage

    Use a built-in package in Java to write a class which displays a message (by using sout) after taking input from the user.

    3. Three-Level Package

    Create a package in class with three package levels: folder → folder.L1 → folder.L2

    4. Access Modifier Demo

    Prove that you cannot access default property but can access protected property from the subclass.

    Solution Example: Calculator Package

    ← Previous: Abstract & Interfaces Next: Multithreading →