Java Packages with Examples

Java Packages Tutorial with Examples


Package in Java :

Java uses the concept of package to grouped classes together.

Packages are used to reuse an existing without physically copying the code.

There are two types of packages -

  • Built-in package
  • User-defined package

1. Built-in package / Predefined Package

Ther are predefined and the part of the language.

Java has many built-in packages like - util, lang, awl, sql,...etc.

2. User-define package

They created by programmer package keyword is used to declare a package.

The “import”  keyword is used to import package in a class.

Example -

// calc.java

// web design house

//online promotion house


package P;
public class Calc{
  
public static int add(int a,int b){
      
return a+b;
   }
  
public static int sub(int a, int b){
      
return a-b;
   }
}

//Save file with - Calc.java
  // javaC_-d_.Calc.java
import  P.Calc;
public class Main {

  
public static void main(String[] args) {
 
// write your code here
  int r = Calc.add(10,30);
  System.out.println(
"sum = "+r);
  r = Calc.sub(
10,5);
  System.out.println(
"sub = "+r);

   }

}