Skip to content
Related Articles

Related Articles

Built-in Packages in Java

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Mar, 2022

Packages in java are used to avoid naming conflict and to control the access of class, interface, sub-classes, etc. A package can be defined as a group of similar types of classes, sub-classes, interfaces or enumerations, etc. while using packages it becomes easier to locate or find the related classes and packages provides a good structure or outline of the project with a huge amount of classes and files.

Packages are divided into two parts:

  • Built-in packages: In java, we already have various pre-defined packages and these packages contain large numbers of classes and interfaces that we used in java are known as Built-in packages.
  • User-defined packages: As the name suggests user-defined packages are a package that is defined by the user or programmer.

Built-in packages

Packages that come with JDK or JRD you download are known as built-in packages. The built-in packages have come in the form of JAR files and when we unzip the JAR files we can easily see the packages in JAR files, for example, lang, io, util, SQL, etc. Java provides various built-in packages for example java.awt

Java Built-In Packages

Now let’s discuss some built-in packages.

Examples of Built-in Packages

  • java.sql: Provides the classes for accessing and processing data stored in a database. Classes like Connection, DriverManager, PreparedStatement, ResultSet, Statement, etc. are part of this package.
  • java.lang: Contains classes and interfaces that are fundamental to the design of the Java programming language. Classes like String, StringBuffer, System, Math, Integer, etc. are part of this package.
  • java.util: Contains the collections framework, some internationalization support classes, properties, random number generation classes. Classes like ArrayList, LinkedList, HashMap, Calendar, Date, Time Zone, etc. are part of this package.
  • java.net: Provides classes for implementing networking applications. Classes like Authenticator, HTTP Cookie, Socket, URL, URLConnection, URLEncoder, URLDecoder, etc. are part of this package.
  • java.io: Provides classes for system input/output operations. Classes like BufferedReader, BufferedWriter, File, InputStream, OutputStream, PrintStream, Serializable, etc. are part of this package.
  • java.awt: Contains classes for creating user interfaces and for painting graphics and images. Classes like Button, Color, Event, Font, Graphics, Image, etc. are part of this package.

Let’s discuss some above-mentioned examples with code

Java. awt package

This package is the main package of the abstract window kit. it includes the classes for graphics, containing the java 2D graphics and it also defines the graphical user interface(GUI) framework for java. this package had several heavy GUI objects which come under java. swing package

Java




import java.awt.*;
public class AWTExample{
  AWTExample()
  {
    Frame fr1=new Frame(); 
    Label la = new Label("Welcome to the java graphics GEEKSFORGEEKS"); 
    fr1.add(la);                
    fr1.setSize(200, 200); 
    fr1.setVisible(true);  
  }
  public static void main(String args[])
  {
    Testawt tw = new Testawt();
  }
}


Output:

In the above-mentioned example, we created a frame of size 200 x 200 by using an awt package and then print a message “Welcome to the java graphics GEEKSFORGEEKS. 

Java.net package

This package contains the classes and interfaces for networking like  Socket class, ServerSocket class, URLConnection class,  DatagramSocket, MulticastSocket, etc. Java supports the two network protocols such as TCP(Transmission control protocol) and UDP(User Datagram Protocol which is a connection-less protocol).

Java




// using DatagramSocket under java.net package
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
 
public class UDP {
    public static void main(String[] args)
        throws IOException
    {
        // Create a socket to listen at port 4567
        int port_no = 4567;
        DatagramSocket ds = new DatagramSocket(port_no);
        byte[] receive = new byte[65535];
        DatagramPacket DpReceive = null;
 
        while (true) {
            // create a DatgramPacket to receive the data.
            DpReceive = new DatagramPacket(receive,
                                           receive.length);
            // receive the data in byte buffer.
            ds.receive(DpReceive);
            System.out.println("DATA:- " + data(receive));
            // Clear the buffer after every message.
            receive = new byte[65535];
        }
    }
}


Output

DATA:- //whatever to get from server 

In the above-mentioned example, we’ve implemented a UDP socket receiver that receives data from the server-side through port no. first, we created a socket using the DatagramSocket method to listen on port no 4567, second, we created a datagram packet to receive the data in byte buffer, and then finally after getting the data we printed it.

java.sql package

This package contains the classes and interfaces to provide and perform all JDBC tasks like creating and executing SQL queries. It includes a framework where different drivers can be installed dynamically to access different-different databases and it also provides the API for accessing and processing the database which is stored in a database.

Java




import java.sql.*;
 
public class JavaSQL {
    
   static final String URL = "jdbc:mysql://localhost/Geeksforgeeks";
   static final String USER = "user";
   static final String PASSWORD = "123";
   static final String QUERY = "SELECT ID, NAME, ADDRESS FROM STUDENTS";
   
   public static void main(String[] args) {
      // Open a connection
      try(
         Connection con = DriverManager.getConnection(URL, USER, PASSWORD);
         Statement stm = con.createStatement();
         ResultSet rs = stm.executeQuery(QUERY);) {
          
        while (rs.next()) {
            // Retrieving data from column name
            System.out.print("ID: " + rs.getInt("id"));
            System.out.print(",NAME: " + rs.getInt("name"));
            System.out.println(",ADDRESS: " + rs.getString("address"));
         }
      } catch (SQLException e) {
         e.printStackTrace();
      }
   }
}


Output

ID: 1, NAME: Harry, ADDRESS: India
ID: 2, NAME: Jhon, ADDRESS: USA
ID: 3, NAME: Kim, ADDRESS: USA
ID: 4, NAME: Bob, ADDRESS: India

In the above example, you can see that first, we imported the package name java.sql.*, In the main method we initialize the string variable name URL, USER, PASSWORD, QUERY. and then use DriverManager to get a connection to the database. and finally, we use the executeQuery method to execute the query of selecting the data from the database. 

java.lang package

This package contains the core classes of the java language. This package is automatically imported to each program, which means we can directly use classes of this package in our program. Let’s have an example of the Math class of lang package which provides various functions or methods for mathematical operation.

Java




import java.lang.*;
 
 class example_lang {
   public static void main(String args []) {
      int a = 100, b = 200,maxi;
      maxi = Math.max(a,b);
      System.out.printf("Maximum is = "+maxi);
    }
 }


Output

Maximum is = 200

In the above-mentioned example, we use the lang package and Math class to find the maximum of two-digit using the “max” function. first, we created a three integer variable named “a” and “b” and maxi. where a = 100 and b = 200 and maxi will store the maximum value from a or b. After assigning values to the variable we used the max function to find the maximum and stored it in maxi. so in desired output, we can see a maximum of two numbers and that is 200.  

java.io package

This package provides classes and an interface for handling the system(input/output). Using these classes programmer can take the input from the user and do operations on that and then display the output to the user. Other than this we can also perform file handling read or write using classes of this package.

Java




import java.io.Console;
  
 class example_io {
    
   public static void main(String args []) {
      Console cons = System.console();
      System.out.println("Enter your favorite color");
      String colour ;
      colour = cons.readLine();
      System.out.println("Favorite colour is " + colour);
    }
 }


Output

Enter your favorite color
RED
Favorite color is RED

In the above-mentioned example, we use the java.io package and Console class to take input from users to perform some task or operations on it and then finally display the result on the console. as code said first we display the message “Enter your favorite color” which asks a user to enter color. than user system read that line using cons.readLine() and stored it in string type variable then finally display that line.

java.util package

This package provides the basic necessary things to java programmers. The most common class in this package is Arrays which is generally used by programmers in various cases. we can say that it is the most useful package for java because it helps to achieve different types of requirements easily by using pre-written classes. let’s see the example of Arrays class.

Java




import java.util.Arrays;
 
public class MyClass {
    public static void main(String args[]) {
      int[] arr = { 40, 30, 20, 70, 80 };
      Arrays.sort(arr);
      System.out.printf("Sorted Array is = "+Arrays.toString(arr));
    }
}


Output:

Sorted Array is = [20, 30, 40, 70, 80]

In the above-mentioned example, we used java. util package and Arrays class to sort the integer array. first, we created an integer type array that consists of elements 40,30,20,70,80 and sort the array using the “sort” function of the Arrays class. After sorting an array we’ll print the sorted array you can see it in the desired output.  


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!