×

How to Create Different Packages for Different Classes in Java

Packages in Java

In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points of interaction. Whenever we compose an assertion, be it as displayed underneath, we bring in every one of the classes of java.io.* package. Here, java is a catalogue name, and io is another sub-index inside it. What's more, the * addresses every one of the classes and connection points of that io subdirectory.

import java.io.*;

We have many such packages, for instance, java.lang, java. util, and there does exist a lot more inside which there are classes inside the package. Let’s take the most often utilised packages, the 'lang' package for java planning and the 'io' package for input-yield activities.

Allow us to talk about the upsides of packages in java that are as the following:

  • Packages help organise related classes to interfaces into a gathering. This assembles every one of the classes and connection points, playing out a similar undertaking in the package. For instance, In Java, every one of the classes and connection points which perform info and result activities are put away in the java.io package.
  • Packages conceal the classes and connection points in a different subdirectory.
  • A package's classes and points of interaction are segregated from another package's classes and points of interaction.

There are two kinds of packages in java, as recorded:

  • Built-in packages 
  • User-defined packages

Built-in packages:

Packages that accompany JDK or JRD you download are known as built-in packages. The built-in packages have come as Container documents. When we unfasten the Container records, we can undoubtedly see the packages in Container documents, for instance, lang, io, util, SQL, and so on. Java gives different built-in packages to model java.awt.

Examples of Built-in Packages:

  • java.sql: Gives the classes to get to and handle information put away in a data set. Classes like Association, DriverManager, PreparedStatement, ResultSet, Explanation, and so forth are essential for this package.
  • java.lang: Contains classes and points of interaction that are key to the plan of the Java programming language. Classes like String, StringBuffer, Framework, Math, Number, and so on are essential for this package.

Example:

import java.io.*;
import java.lang.*;
class JL {
   public static void main(String args []) {
      int p = 10, q = 20;
      int s = Math.addExact(a,b);
      int m = Math.max(a,b);
      double pi = Math.PI;
      System.out.printf("Sum = "+s+", Max = "+m+", PI = "+pi); 
    }
 }

Output:

Sum = 30
Max = 20
PI = 3.1415
  • java.util: Contains the assortments system, some internationalisation support classes, properties, and an arbitrary number of age classes. Classes like ArrayList, LinkedList, HashMap, Schedule, Date, Time Region, and so on are essential for this package.

Example:

import java.io.*;
import java.util.Arrays;
 
 class JU {
   public static void main(String args []) {
      int[] Arr = {1, 3, 2, 5, 4};
      Arrays.sort(Arr);
      System.out.printf("The Sorted array is: %s", Arrays.toString(Arr)); 
    }
 }

Output:

The sorted array is: [1, 2, 3, 4, 5]
  • java.net: Gives classes to execute organising applications. Classes like Authenticator, HTTP Treat, Attachment, URL, URLConnection, URLEncoder, URLDecoder, and so forth are essential for this package.
  • java.io: Gives classes to framework input/yield activities. Classes like BufferedReader, BufferedWriter, Document, InputStream, OutputStream, PrintStream, Serializable, and so on are essential for this package.

Example:

import java.io.Console;
 
 class JI {
   public static void main(String args []) {
      Console sc = System.console();
      System.out.println("Please enter your name : ");
      String na = sc.readLine();
      System.out.println("Welcome : "+na);
    }
 }

Output:

Please enter your name:
Vijay
Welcome : Vijay
  • java.awt: Contains classes for making UIs and for painting illustrations and pictures. Classes like Button, Variety, Occasion, Textual style, Illustrations, Pictures, and so forth are essential for this package.

Example:

//simple java program using the java awt package
import java.awt.Frame;     //here, we are importing the java awt package
 import java.awt.Label;      //here, we are importing the java awt package
  
 class JA {
   //here, we are declaring the constructor
   public JA() {
      Frame f = new Frame(); //here, we are creating a frame
      Label l = new Label(" Welcome to refresh java "); //here, we are creating a // label
      f.add(l);        //here, we are adding label to the frame
      f.setSize(300, 200);      //here, we are setting the frame size
      f.setVisible(true);    //here, we are setting the frame visibility as true
    }
   public static void main(String args []) {
      JA at = new JA();
   }
 }

Output:

How to Create Different Packages for Different Classes in Javaa

User-defined Packages:

User-defined packages are those packages that are planned or made by the designer to classify classes and packages. They are much like the underlying that java offers. It tends to be brought into different classes and involves equivalent to what we utilise worked in packages. However, If we discard the package explanation, the class names are placed into the default package with no name.

To make a package, we should utilise the package watchword.

Syntax:

package package-name;

Moves toward making User defined Packages.

Stage 1: Making a package in java class. The arrangement is fundamental and straightforward. Compose a package by following its name.

package example1;

Stage 2: Remember the class for the java package Yet recall that the class has one package announcement.

package example1;


class F1 {
   public static void main(Strings[] args){
     -------capability - - - - - - -
   }
}

Stage 3: Presently, the user-defined package is effectively made; we can bring it into different packages and utilise its capabilities.

Syntax:

In creating a package, the package keyword is used

  • To create a package, we use the Syntax
package package_name; 
  • If we want to create a subpackage within a package, we use
package package_name.spname;
  • To compile the package, we use
C:\> javac -d . classname.java
  • To run the package program
C:\> java packagename.classname

Example:

Stage 1: Characterize a class EmployeeData that holds the accompanying data of an employee:

ID: a string stores the remarkable ID of every employee

Name: It is a string showing the name of the employee.

Note that these fields ought to be proclaimed private.

Stage 2: Make one more class EmployeeDataExtended with a confidential characteristic named area. Fundamentally a string stores the area of the employee.

Stage 3: Presently, in this class, characterise a strategy addDetails() technique that stores the subtleties of understudies; and a strategy printDetails() strategy that yields the subtleties of employees in the arranged request of their id.

Creating the package1:

//simple Java Program that Illustrates the division of Classes into 
//the Packages where the Class EmployeeData
// which creates the first package, i.e. pack1 
//here, we are importing the package 
package pack1; 
//here, we are making the main class 
public class EmployeeData { 
    private String id; 
    private String name; 
    //here, we are creating method 1 
    public void addEmployeeData(String id1, String nam) 
    { 
        // This keyword refers to the current instance itself 
        this.id1 = id; 
        this.nam = name; 
    } 
    //here, we are declaring the getter setters’ Methods 
    //which use the getter methods so that we can 
    // access the private members for the other packages 
    public String getId() { return id1; } 
    public String getName() { return nam; } 
}

Creating the package2:

// Java Program that Illustrates the Dividion of Classes into 
//the Packages where Class EmployeeDataExtended creates 
//the Second package- pack2 and uses the first package  
//here, we are importing the packages 
package pack2; 
//here, we are importing the required classes 
// from the pre-defined packages 
import java.io.*; 
import java.lang.*; 
import java.util.*; 
import pack1.*;   
//here, we are declaring the main class 
class EmployeeDataExtended extends EmployeeData { 
    private String location; 
    public void addDetails(String id, String name, String location) 
    { 
        addEmployeeData(id, name); 
        // This keyword refers to the current object itself 
        this.location = location; 
    } 
    //here, we are implementing Method 1 
    public static void
    printDetails(TreeMap<String, EmployeeDataExtended> map) 
    { 
        //here, we are iterating via for each loop 
        for (String a : map.keySet()) {
            EmployeeDataExtended employee = map.get(a);  
            //here, we are going to print the ID and the name of the employee 
            System.out.println(employee.getId() + " " + employee.getName() + " "
            + employee.location); 
        } 
    } 
    //here, we are declaring Method 2 
    //here, we are declaring the Main driver method 
    public static void main(String[] args) 
    { 
        //here, we display a message for asking input from the user 
        System.out.print("Enter the number of employees : "); 
        //here, we are declaring the scanner class to read the user input 
        Scanner sc = new Scanner(System.in); 
        int a = sc.nextInt(); 
        String b = sc.nextLine();
        int c = 1; 
        //here, we are creating a TreeMap 
        TreeMap<String, EmployeeDataExtended> map = new TreeMap<>(); 
        while (a != 0) { 
            System.out.println("Enter the details of employee " + c + " (id, name, location):"); 
            c++; 
            String details = sc.nextLine(); 
            String employeeInfo[] = details.split(" "); 
            EmployeeDE employee = new EmployeeDE(); 
            employee.addDetails(employeeInfo[0], employeeInfo[1], employeeInfo[2]); 
            map.put(employeeInfo[0], employee); 
            a--; 
        } 
        //here, we are displaying the message 
        System.out.println("\nThe Employee Details are:"); 
        //here, we are calling the above method 1 to 
        //this program prints details of the employees 
        printDetails(map); 
    } 
}

Output:

Enter the number of Employees: 4
Enter the details of Employee 1 (id, name, location):
A101   Vijay Kumar   Medak
Enter the details of Employee 2 (id, name, location):
A105    Aslam M.D   Gajwel
Enter the details of Employee 3 (id, name, location):
A110   Ajay Kumar   Hyderabad
Enter the details of Employee 4 (id, name, location):
A115    Gowtham Kumar   Ranga Reddy
The Employee Details are:
A101   Vijay Kumar   Medak
A105    Aslam M.D   Gajwel
A110   Ajay Kumar   Hyderabad
A115    Gowtham Kumar   Ranga Reddy

Related Topics

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.