×

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

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 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.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.