Packages
Packages Notes — https://docs.google.com/document/d/1UalTL2GyA6exjvGgaoa0kkiQqZtQVQ6R-GfX15LeOQ8/edit?usp=sharing
Package is the collection of inter related classes and interfaces.
Package is a folder that contains .class files which are representing related classes and interfaces.
In Java applications, Packages are able to provide the following advantages.
- Modularization
- Abstraction
- Security
- Shareability
- Reusability
Modularization:
The logical partition in Source code is called a Module, in Java applications, to represent modules we will use “packages”.
Abstraction:
The process of showing necessary implementations and hiding unnecessary implementation is called an abstraction.
In Java applications, Packages are able to provide abstraction , because if we declare classes and interfaces inside the packages then the packages are able to hide those declared classes and interfaces, so packages are able to provide abstraction.
Security:
In Java applications, packages are able to hide their internal declarations, so Packages are able to provide security for the internal declarations.
In Java applications, we are able to implement some explicit security mechanisms over the packages, so Packages are able to provide security in the java applications.
Shareability:
In Java applications, if we declare a package one time that we can share to multiple java applications at a time as per the requirement.
Reusability:
In Java applications, if we declare a package one time that we can reuse any number of times in multiple applications one after another , so Packages are able to improve Reusability.
In Java, there are two types of packages.
- Predefined Packages
- User Defined Packages
Predefined Packages
These Packages are defined by the Java programming language and provided along with the Java Software.
java.lang
java.lang package is a default package in Java applications, it is not required to import java.lang package in order to use the members of the java.lang package.
java.lang package is able to provide the fundamental classes and interfaces which are required to prepare basic Java applications.
java.lang package is able to provide the following classes and interfaces to prepare the java applications.
System, String, StringBuffer, StringBuilder, Object, Exception and its subclasses, Thread, Runnable, ThreadGroup, All Wrapper Classes like NUmber, Byte, Short, Integer, Long, Float, Double, Boolean, Character,…..
java.io
This package is able to provide the predefined classes and interfaces to perform INput and Output operations in the Java applications.
java.io package is able to provide the following predefined classes and interfaces to perform the io operations.
InputStream, FIleInputStream, ByteArrayInputStream, BufferedInputStream, OutputSteam, FileOutputStream, PrintStream, BufferedOutputStream, Reader, Writer, FileReader, FileWriter,…..
java.util
This package is able to provide a predefined library to represent all the data structures.
java.util package is able to provide the following predefined classes and interfaces to represent all the data structures.
List, ArrayList, Vector, Stack, LinkedList,
Set, HashSet, LinkedHashSet, SortedSet, NavigableSet, TreeSet, Queue, PriorityQueue, LinkedPriorityQueue, Deque, ArrayDeque, Map, HashMap, LinkedHashMap, WeakHashMap, IdentityHashMap, SortedMap, NavigableMap, TreeMap, Comparable, Comparator,…..
java.net
java.net package is able to provide the predefined library to prepare Distributed applications by using Socket Programming.
java.net package has provided the following predefined classes and interfaces to prepare network applications.
Socket, ServerSocket, InetAddress, URL, URLCOnnection, Inet4Address,….
java.rmi
java.rmi package is able to provide the predefined library to prepare Distributed applications on the basis of the Remote Method Invocation.
java.rmi is able to provide the following predefined classes and interfaces to prepare RMI applications.
Remote, RemoteException, UnicastRemoteObject, Naming,…..
java.awt
java.awt package is able to provide the predefined library to prepare GUI Applications.
java.awt package is able to provide the following predefined classes and interfaces to prepare GUI applications.
Frame, Applet, Label, TextField, CheckBox, List, Choice, Menu, Panel, Button,…..
javax.swing
javax.swing package is able to provide the predefined library to prepare GUI Applications.
javax.swing package is able to provide the following predefined classes and interfaces to prepare GUI applications.
JFrame, JApplet, JLabel, JTextField, JPasswordField, JCheckBox, JRadio, JList, JChoice, JMenu, JPanel, JButton, JColorChooser, JFileChooser, JDialogBox, …..
java.text
Java.text package is able to provide the predefined library to provide Internationalization Services to the Java applications.
To provide Internationalization Services in Java applications, java.text package is able to provide the following predefined library.
NumberFormat, DateFormat, Currency,…
java.sql
java.sql package is able to provide the predefined library to prepare JDBC applications.
To prepare JDBC applications, java.sql package is able to provide the following predefined classes and interfaces.
Driver, DriverManager,Connection, Statement, PreparedStatement, CallableStatement, ResultSetMetaData, DatabaseMetaData,…
User defined packages
These packages are defined by the developers as per their application requirements.
In Java applications, to declare an user defined package we have to use the following syntax.
package packageName;
Where the packageName may be a single name or the combination of the parent package name and child package name with ‘.’ separator.
EX-1: package p;
EX-2: package p1.p2.p3;
If we want to declare a package statement in a java file then we must use the following conditions.
- Package declaration statement must be the first statement.
- Package name must be unique, it must not be duplicated and it must not be shareable.
Q) Is it possible to provide more than one package declaration statement in a single java file?
No, it is not possible to provide more than one package declaration statement in a single java file, because the Package declaration statement must be the first statement, if we provide more than one package declaration statement, then ,only the first package declaration statement is valid and all the remaining package declaration statements are invalid.
File Name: abc.java
package p1; —-------> Valid
package p2; —-------> Invalid
package p3; —-------> Invalid
In Java applications, after declaring a package with the classes and interfaces we have to access the classes and interfaces of that particular package into the present Java file, to access the classes and interfaces of a particular package in the present java file we have to make available that classes and interfaces from the respective package to the present java file, to make available classes and interfaces of a particular package to the present java file we have to import the respective package into the present java file.
To import a package into the present java file we have to use the following syntaxes.
- import packageName.*;
It is able to import all classes and interfaces from the specified package to the present java file.
import java.io.*;
import java.sql.*;
import java.util.*;
- import packageName.memberName;
It is able to import only the specified class name or interface name from the specified package.
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Vector;
Note: import statement is optional for the java.lang package , because java.lang package is a default package in the java files.
Note: In Java files, we are able to provide at most one package declaration statement, but we are able to provide any number of import statements.
FileName: abc.java
package p1; —--------------> Valid
package p2; —--------------> Invalid
package p3; —--------------> Invalid
import java.util.*; —------> Valid
import java.io.*; —--------> Valid
import java.sql.*; —-------> Valid
Note: In Java applications, always it is suggestible to import the individual members directly instead of all members of a package by using ‘*’ notation, because if we import individual classes and interfaces separately then we are able to get more readability from the import statements.
import java.io.*;
import java.sql.*;
import java.util.*;
public class Test{
public static void main(String[] args){
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
ArrayList al = new ArrayList();
Connection con = DriverManager.getConnection(“--”,”--”,”--”);
}
}
If we see the above program, we are unable to get the clarity of the classes and interfaces which are coming from which packages, so the above approach is able to reduce “Readability”.
If we want to improve Readability we have to import the individual classes and interfaces and which makes the connection between the classes and the packages which we have used in the present java file.
EX:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.DriverManager;
public class Test{
public static void main(String[] args){
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
ArrayList al = new ArrayList();
Connection con = DriverManager.getConnection(“--”,”--”,”--”);
}
}
Note: IDEs like Eclipse, Intellij IDEA are supporting the import statements with the individual classes names and interface names only.
Q)Is it possible to use the classes and interfaces of a particular package in the present java file without importing the respective package?
Yes, It is possible to use classes and interfaces of a particular package in the present java file without importing the respective package, but we must use the “Fully Qualified Name” of the respective class or interface.
Note: Writing classes names and interfaces names along with their respective package names is called “Fully Qualified Name”.
ArrayList —----> Normal Name
java.util.ArrayList —---> Fully Qualified Name
System —--------> Normal Name
java.lang.System —------> Fully Qualified Name.
EX:
A Java program with import statement:
import java.io.*;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
A Java program Without the import statement:
java.io.BufferedReader br = new java.io.BufferedReader(
new java.io.InputStreamReader(System.in));
Note: In Java applications, always import statements are suggestible instead of using fully qualified names for the classes and interfaces.
Q)In Java applications, in which situations we must use “Fully Qualified Names” for the classes over the import statements?
In Java applications, if more than one class is having the same name in the more than one package, if we import both the packages and if we use the class name in the java file then the compiler will get confused as to which package the provided class is importing. In this case to resolve the confusion we have to use Fully qualified names to the classes.
EX:
In Java, Date is a class existed in java.util package and in java.sql package, if we import both java.util and java.sql packages in the present java file and if we use Date class name in the present java file then the compiler will raise an error like below.
“reference to Date is ambiguous
Date date1 = new Date();
both class java.util.Date in java.util and class java.sql.Date in java.sql match”
To resolve the above ambiguous situation we have to use Fully qualified names to the Date class in the present java file.
import java.util.*;
import java.sql.*;
class Test{
public static void main(String[] args){
java.util.Date date1 = new java.util.Date();
System.out.println(date1);
java.sql.Date date2 = java.sql.Date.valueOf("1996-10-2");
System.out.println(date2);
}
}
EX-1:
——–
E:\abc
Employee.java[Package: com.durgasoft.emp]
Compile Employee.java from E:\abc and send the generated .class file to the location “C:\abc”.
C:\abc
com
|-----durgasoft
|--------core
|-----Employee.class
D:\Fullstack10\packages\app01
Test.java
Test.class
If we execute the Test class then we have to get all Employee details as an output.
Employee.java
package com.durgasoft.emp;
public class Employee{
private int eno = 111;
private String ename = "Durga";
private float esal = 50000.0f;
private String eaddr = "Hyd";
public void displayEmpDetails(){
System.out.println("Employee Details");
System.out.println("----------------------");
System.out.println("Employee Number : "+eno);
System.out.println("Employee Name : "+ename);
System.out.println("Employee Salary : "+esal);
System.out.println("Employee Address : "+eaddr);
}
}
Test.java
import com.durgasoft.emp.*;
public class Test{
public static void main(String[] args){
Employee emp = new Employee();
emp.displayEmpDetails();
}
}
E:\abc>javac -d C:\abc Employee.java
E:\abc>d:
D:\>cd Fullstack10AM
D:\Fullstack10AM>cd "CORE JAVA"
D:\Fullstack10AM\CORE JAVA>cd PACKAGES
D:\Fullstack10AM\CORE JAVA\PACKAGES>cd app01
D:\Fullstack10AM\CORE JAVA\PACKAGES\app01>javac Test.java
Test.java:1: error: package com.durgasoft.emp does not exist
import com.durgasoft.emp.*;
^
Test.java:4: error: cannot find symbol
Employee emp = new Employee();
^
symbol: class Employee
location: class Test
Test.java:4: error: cannot find symbol
Employee emp = new Employee();
^
symbol: class Employee
location: class Test
3 errors
D:\Fullstack10AM\CORE JAVA\PACKAGES\app01>set classpath=C:\abc;
D:\Fullstack10AM\CORE JAVA\PACKAGES\app01>javac Test.java
D:\Fullstack10AM\CORE JAVA\PACKAGES\app01>java Test
Employee Details
----------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000.0
Employee Address : Hyd
EX-2:
——–
C:\xyz
Student.java[package: com.durgasoft.std]
Compile Student.java from C:\xyz location and send the generated .class files to the E:\xyz
E:\xyz
com
|—–durgasoft
|———std
|——Student.class
E:\abc
Customer.java[package: com.durgasoft.cust]
Compile Customer.java from E:\abc location and send the generated .class file to the location C:\abc location
C:\abc
com
|—–durgasoft
|——-cust
|—–Customer.class
D:\Fullstack10Am\COREJAVA\PACKAGES\app02
Test.java
Test.class
If we run Test class then we have to get Student details and Customer details as output.
Student.java
package com.durgasoft.std;
public class Student{
String sid = “S-111”;
String sname = “Durga”;
String saddr = “Hyd”;
public void displayStudentDetails(){
System.out.println(“Student Details”);
System.out.println(“———————-“);
System.out.println(“Student Id : “+sid);
System.out.println(“Student Name : “+sname);
System.out.println(“Student Address : “+saddr);
}
}
Customer.java
package com.durgasoft.cust;
public class Customer{
String cid = “C-111”;
String cname = “Anil”;
String caddr = “Pune”;
public void displayCustomerDetails(){
System.out.println(“Customer Details”);
System.out.println(“—————————“);
System.out.println(“Customer Id : “+cid);
System.out.println(“Customer Name : “+cname);
System.out.println(“Customer Address : “+caddr);
}
}
Test.java
import com.durgasoft.std.*;
import com.durgasoft.cust.Customer;
public class Test{
public static void main(String[] args){
Student std = new Student();
std.displayStudentDetails();
System.out.println();
Customer cust = new Customer();
cust.displayCustomerDetails();
}
}
Microsoft Windows [Version 10.0.19044.3086]
(c) Microsoft Corporation. All rights reserved.
C:\Users\Administrator>cd\
C:\>cd xyz
C:\xyz>javac -d E:\xyz Student.java
C:\xyz>e:
E:\>cd abc
E:\abc>javac -d C:\abc Customer.java
E:\abc>d:
D:\>cd Fullstack10AM
D:\Fullstack10AM>cd “CORE JAVA”
D:\Fullstack10AM\CORE JAVA>cd PACKAGES
D:\Fullstack10AM\CORE JAVA\PACKAGES>cd app02
D:\Fullstack10AM\CORE JAVA\PACKAGES\app02>javac Test.java
Test.java:2: error: package com.durgasoft.cust does not exist
import com.durgasoft.cust.Customer;
^
Test.java:1: error: package com.durgasoft.std does not exist
import com.durgasoft.std.*;
^
Test.java:5: error: cannot find symbol
Student std = new Student();
^
symbol: class Student
location: class Test
Test.java:5: error: cannot find symbol
Student std = new Student();
^
symbol: class Student
location: class Test
Test.java:9: error: cannot find symbol
Customer cust = new Customer();
^
symbol: class Customer
location: class Test
Test.java:9: error: cannot find symbol
Customer cust = new Customer();
^
symbol: class Customer
location: class Test
6 errors
D:\Fullstack10AM\CORE JAVA\PACKAGES\app02>set classpath=E:\xyz;C:\abc;
D:\Fullstack10AM\CORE JAVA\PACKAGES\app02>javac Test.java
D:\Fullstack10AM\CORE JAVA\PACKAGES\app02>java Test
Student Details
———————-
Student Id : S-111
Student Name : Durga
Student Address : Hyd
Customer Details
—————————
Customer Id : C-111
Customer Name : Anil
Customer Address : Pune
EX-3:
E:\abc
Product.java[Package: com.durgasoft.prd]
Compile Product.java from E:/abc location and send the generated .class file to the location C:\xyz
C:\xyz
com
|—-durgasoft
|——prd
|—–Product.class
C:\abc
Order.java[package: com.durgasoft.order]
Compile Order.java file from C:\abc location and send the generated .class file to the location E:\xyz.
E:\xyz
com
|—-durgasoft
|——order
|——Order.class
D:\java10\packages\app03
Test.java[Package: com.durgasoft.test]
Compile Test.java from the location D:\java10\packages\app03 and send the generated .class file to the same location like below.
D:\java10\packages\app03
com
|—-durgasoft
|——test
|—–Test.class
If we execute the Test class then we have to get both product details and Order details as output.
Product.java
package com.durgasoft.prd;
public class Product{
private String productId = “p111”;
private String productName = “Laptop”;
private int productPrice = 50000;
public void displayProductDetails(){
System.out.println(“Product Details”);
System.out.println(“———————-“);
System.out.println(“Product Id : “+productId);
System.out.println(“Product Name : “+productName);
System.out.println(“Product Price : “+productPrice);
}
}
Order.java
package com.durgasoft.order;
public class Order{
private String orderId = “abc123”;
private String orderType = “Electronic Goods”;
private String itemName = “Apple”;
public void displayOrderDetails(){
System.out.println(“Order Details”);
System.out.println(“——————“);
System.out.println(“Order Id : “+orderId);
System.out.println(“Order Name : “+orderType);
System.out.println(“Item Name : “+itemName);
}
}
Test.java
package com.durgasoft.test;
import com.durgasoft.prd.*;
import com.durgasoft.order.*;
public class Test{
public static void main(String[] args) {
Product product = new Product();
product.displayProductDetails();
System.out.println();
Order order = new Order();
order.displayOrderDetails();
}
}
On Command Prompt
Microsoft Windows [Version 10.0.19045.3693]
(c) Microsoft Corporation. All rights reserved.
C:\Users\Nagoor>e:
E:\>cd abc
E:\abc>javac -d C:\xyz Product.java
E:\abc>c:
C:\Users\Nagoor>cd\
C:\>cd abc
C:\abc>javac -d E:\xyz Order.java
C:\abc>d:
D:\>cd java10
D:\java10>cd PACKAGES
D:\java10\PACKAGES>cd app03
D:\java10\PACKAGES\app03>set classpath=C:\xyz;E:\xyz;
D:\java10\PACKAGES\app03>javac -d . Test.java
D:\java10\PACKAGES\app03>java com.durgasoft.test.Test
Product Details
———————-
Product Id : p111
Product Name : Laptop
Product Price : 50000
Order Details
——————
Order Id : abc123
Order Name : Electronic Goods
Item Name : Apple
JAR Files in Java:
JAR: Java Archive
JAR file is the collection of packages and .class files.
In general, we will use JAR files in the following situations.
- To deploy the java applications into the Servers.
- To transfer bulk .class files from one system to another system we will use jar files.
- To simplify uploading a project or product and downloading a project or product we will use jar files.
——-
——–
Note: At present, Some Frameworks like Spring, Hibernate,…. are provided by the vendors in the form of zip files that contain the number of jar files, where all the jar files contain the required packages and .class files.
In Java applications, to create a JAR file we have to use the following command.
jar -cvf fileName.jar *
cvf: create verbose file
*: all files and folders in the current location.
EX:
jar -cvf app.jar *
To extract the JAR files we will use the following command.
jar -xvf fileName.jar
EX:
C:\abc
Account.java[Package: com.durgasoft.icici.accounts]
Compile Account.java file from the location C:\abc and send the generated .class file to the location C:\xyz.
c:\xyz
com
|—-durgasoft
|——icici
|——accounts
|——Account.class
Create a jar file at C:\xyz location and send the jar file to a location E:\abc
icici_account.jar
D:\Java10\PACKAGES\app04
Test.java
Test.class
If we execute the Test class then we have to get Account details.
Account.java
package com.durgasoft.icici.accounts;
public class Account{
private String accNo = “abc123”;
private String accHolderName = “Durga”;
private String accType = “Savings”;
private int balance = 25000;
public void displayAccountDetails(){
System.out.println(“Account Details”);
System.out.println(“———————-“);
System.out.println(“Account Number : “+accNo);
System.out.println(“Account Holder Name : “+accHolderName);
System.out.println(“Account Type : “+accType);
System.out.println(“Account Balance : “+balance);
}
}
Test.java
import com.durgasoft.icici.accounts.*;
public class Test{
public static void main(String[] args) {
Account account = new Account();
account.displayAccountDetails();
}
}
On COmmand Prompt:
C:\abc>javac -d C:\xyz Account.java
C:\abc>cd\
C:\>cd xyz
C:\xyz>jar -cvf icici_account.jar *
added manifest
adding: com/(in = 0) (out= 0)(stored 0%)
adding: com/durgasoft/(in = 0) (out= 0)(stored 0%)
adding: com/durgasoft/icici/(in = 0) (out= 0)(stored 0%)
adding: com/durgasoft/icici/accounts/(in = 0) (out= 0)(stored 0%)
adding: com/durgasoft/icici/accounts/Account.class(in = 1400) (out= 740)(deflated 47%)
C:\xyz>d:
D:\java10\PACKAGES\app04>set classpath=E:\abc\icici_account.jar;
D:\java10\PACKAGES\app04>javac Test.java
D:\java10\PACKAGES\app04>java Test
Account Details
———————-
Account Number : abc123
Account Holder Name : Durga
Account Type : Savings
Account Balance : 25000
MANIFEST File in jar file
MANIFEST file is a file in the form of MANIFEST.MF under META-INF folder created by the jar command at the time of creating the jar file.
MANIFEST file is able to provide some information or metadata about the jar file in the form of Name-Value pairs.
MANIFEST.MF
Manifest-Version: 1.0
Created-By: 17.0.8 (Oracle Corporation)
Executable Jar File
If any jar file contains the main class and main() method then that jar file is called an executable jar file, and we can execute the executable jar files directly without providing the main class name in the command prompt.
To create executable jar files in Java applications we have to use the following steps.
1. Create a Java application and compile the java resources.
D:\Fullstack10AM\CORE JAVA\PACKAGES\app05
Test.java
import java.awt.*;
import java.awt.event.*;
class LogoFrame extends Frame{
LogoFrame(){
setVisible(true);
setSize(800,500);
setTitle(“Logo Frame”);
setBackground(Color.yellow);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void paint(Graphics g){
Font font = new Font(“arial”, Font.BOLD, 40);
g.setFont(font);
setForeground(Color.red);
g.drawString(“DURGA SOFTWARE SOLUTIONS”,100, 250);
}
}
class Test{
public static void main(String[] args){
LogoFrame frame = new LogoFrame();
}
}
D:\Fullstack10AM\CORE JAVA\PACKAGES\app05>javac Test.java
2. Create a text file with the Main-Class attribute in order to keep main class name in the MANIFEST.MF file:
D:\Fullstack10AM\CORE JAVA\PACKAGES\app05\abc.txt
Main-Class: Test
3. Create jar file with the user defined manifest data:
D:\Fullstack10AM\CORE JAVA\PACKAGES\app05>jar -cvfm logo.jar abc.txt *
added manifest
adding: abc.txt(in = 18) (out= 20)(deflated -11%)
adding: LogoFrame$1.class(in = 500) (out= 345)(deflated 31%)
adding: LogoFrame.class(in = 989) (out= 641)(deflated 35%)
adding: Test.class(in = 285) (out= 222)(deflated 22%)
adding: Test.java(in = 612) (out= 351)(deflated 42%)
adding: Test.java.bak(in = 464) (out= 287)(deflated 38%)
4. Execute jar file:
D:\Fullstack10AM\CORE JAVA\PACKAGES\app05>java -jar logo.jar
If we execute the above command on the command prompt, JVM will perform the following actions.
- JVM will recognize the -jar flag and JVM will take the provided jar file name and search for it at current location, at Java predefined library and at the locations referred by the “classpath” environment variable.
- If the provided jar file exists then the JVM will go inside the jar file and search for the META-INF folder.
- When the META-INF folder is identified , JVM will go inside the META-INF folder and search for the MANIFEST.MF file.
- When a MANIFEST.MF file exists , JVM will go inside the MANIFEST.MF file and search for the Main-Class attribute value that is the Main class name.
- If the Main-Class attribute value is identified then the JVM will take the main class from the Main-Class attribute value and search for the main class and main() method inside the jar.
- If the main class is identified inside the jar file then the JVM will execute the main() method directly and JVM will provide the required output.
If we want to simplify the execution process of the jar file we have to use a batch file with the “java -jar logo.jar” command and double click on the generated batch file.
logo.bat
java -jar logo.jar
Note: Copy logo.jar and logo.bat files to the desktop and double click on the logo.bat file.