Create Package in Java

Advertisements

Java Package

Packages are collection of class, interface, enums, sub-packages, etc. Java provides an enormous set of packages such as lang, util, io, swing, awt, etc to help programmer to avoid rewriting of complex code.

Steps To Create Your Own Package

STEP 1:

Create a package(folder) named p1.




STEP 2:

Create a file named MyCalculator.java inside p1 package.




STEP 3:

Write the followling code in MyCalculator.java file.


//MyCalculator.java

    package p1;

    public class MyCalculator
    {
        public int Add(int x,int y)
        {
            return x+y;
        }

        public int Subtract(int x,int y)
        {
            return x-y;
        }

        public int Product(int x,int y)
        {
            return x*y;
        }
    }

STEP 4:

Create a file named TestPackage.java outside p1 package.




STEP 5:

Write the following code in TestPackage.java file.


//TestPackage.java

    import p1.MyCalculator;

    class TestPackage
    {
        public static void main(String[] args)
        {

            MyCalculator M = new MyCalculator();

            System.out.print("\n\n\tThe Sum is : " + M.Add(45,10));
            System.out.print("\n\n\tThe Subtract is :" + M.Subtract(45,10));
            System.out.print("\n\n\tThe Product is :" + M.Product(45,10));

        }
    }

STEP 6:

Compile and Run TestPackage.java and get the output.


    Output:
                The Sum is : 55
                The Subtract is : 35
                The Product is : 450

Advertisement