0% found this document useful (0 votes)
20 views18 pages

Java Packages: Types and Usage Guide

Chapter 5 discusses Java packages, which encapsulate classes, sub-packages, and interfaces to prevent naming conflicts and promote organization. It covers built-in and user-defined packages, file handling operations, and access modifiers in the context of packages. Additionally, it explains how to create, read, write, and delete files using Java's file handling APIs.

Uploaded by

mekashfetene89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views18 pages

Java Packages: Types and Usage Guide

Chapter 5 discusses Java packages, which encapsulate classes, sub-packages, and interfaces to prevent naming conflicts and promote organization. It covers built-in and user-defined packages, file handling operations, and access modifiers in the context of packages. Additionally, it explains how to create, read, write, and delete files using Java's file handling APIs.

Uploaded by

mekashfetene89
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 5

Package and File


Packages in Java are a mechanism that encapsulates a group of classes, sub-packages, and
interfaces. Packages are used for:

Prevent naming conflicts by allowing classes with the same name to exist in different
packages, like [Link] and [Link].
To make it easier to organize, locate, and use classes, interfaces, and other components.
Packages also provide controlled access for protected members that are accessible within
the same package and by subclasses.
Also, default members (no access specifier) are accessible only within the same package.
By grouping related classes into packages, Java promotes data encapsulation, making code
reusable and easier to manage. Simply import the desired class from a package to use it in your
program.
Types of Java Packages
 Built-in Packages
 User-defined Packages
1. Built-in Packages
The java API is the library of prewritten classes that are free to use included in the JDK. These
packages consist of a large number of classes which are a part of Java API. Some of the
commonly used built-in packages are:
 [Link]: Contains language support classes(e.g classes which defines primitive data
types, math operations). This package is automatically imported.
 [Link]: Contains classes for supporting input / output operations.
 [Link]: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
 [Link]: Contains classes for creating Applets.
 [Link]: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc). 6)
 [Link]: Contain classes for supporting networking operations.
2. User-defined Packages
These are the packages that are defined by the user.
1. Create the Package:

1
First we create a directory myPackage (name should be same as the name of the package). Then
create the MyClass inside the directory with the first statement being the package names.
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;
public class MyClass
{
public void getNames(String s)
{
[Link](s);
}
}

2. Use the Class in Program:


Now we will use the MyClass class in our program.
// import 'MyClass' class from 'names' myPackage
import [Link];

public class Geeks {


public static void main(String args[]) {

// Initializing the String variable


// with a value
String s = "Bule Hora";

// Creating an instance of class MyClass in


// the package.
MyClass o = new MyClass();

2
[Link](s);
}
}

Note: [Link] must be saved inside the myPackage directory since it is a part of the
package.

Accessing Classes inside a Package


In Java, we can import classes from a package using either of the following methods:
1. Import a specific class:
import [Link];
This imports only the Vector class from the [Link] package.
2. Import all classes from a package:
import [Link].*;
This imports all classes and interfaces from the [Link] package but does not include sub-
packages.
Example: Importing Class
// Import the Vector class from
// the [Link] package
import [Link];
public class Geeks {
public Geeks() {
// [Link] is imported, We are
// able to access it directly in our code.
Vector v = new Vector();
// [Link] is not imported
// We are referring to it using the complete
// package name.
[Link] l = new [Link]();
[Link](3);

3
[Link](5);
[Link](7);
[Link](l);
}
public static void main(String[] args) {
// Creating an instance of Geeks
// class to invoke the constructor
new Geeks();
}
}

Output
[3, 5, 7]
Note:
 Using import package.*; imports all classes in a package, but not classes from its sub-
packages.

Static Import
Static Import in Java is about simplifying access to static members and separates it from the
broader discussion of user-defined packages.
Static import is a feature introduced in Java programming language (versions 5 and above) that
allows members (fields and methods) defined in a class as public static to be used in Java code
without specifying the class in which the field is defined.
Static Import: Static import allows members (fields and methods) defined in a class to be used
in Java code without specifying the class in which the field is defined.
import static [Link].*;

public class StaticImportExample {


public static void main(String[] args) {
[Link](sqrt(16)); // No need to use [Link](16)
}

4
}

Example
// Note static keyword after import.
import static [Link].*;
class Great {

public static void main(String args[]) {


// We don't need to use '[Link]'
// as imported using static.
[Link]("Bule Hora University");
}
}

Output
Bule Hora University

Handling Name Conflicts


When two packages contain a class with the same name (e.g., [Link] and [Link]),
specify the full package name to avoid conflicts.
import [Link].*;
import [Link].*;

//And then use Date class, then we will get a compile-time error :
Date today ; //ERROR– [Link] or [Link]?
The compiler will not be able to figure out which Date class do we want. This problem can be
solved by using a specific import statement:
import [Link];
import [Link].*;
If we need both Date classes then, we need to use a full package name every time we declare a
new object of that class. For Example:

5
[Link] deadLine = new [Link]();
[Link] today = new [Link]();
Example
Example:
[Link]
[Link]
If you do not import a class explicitly, you can still use its FQN:
public class Example {
public static void main(String[] args) {
[Link]<String> list = new [Link]<>();
}
}

Path and ClassPath


PATH − the path environment variable is used to specify the set of directories which contains
executional programs. Path is an environment variable that is used to find and locate binary
files like "java" and "javac" and to locate needed executables from the command line or
Terminal window. To set the path, we're supposed to include or mention JDK_HOME/bin
directory in a PATH environment variable. The PATH cannot be overridden by providing
command and PATH is only used by the operation system(OS) to find binary files.
Syntax
// To set PATH in the window OS.
set PATH=%PATH%;C:\Program Files\Java\JDK12\bin
// To set PATH in Unix OS
export PATH=${PATH}:/opt/Java/JDK1.5.10/bin
CLASSPATH − the class path environment variable is used to specify the location of the classes
and packages. The CLASSPATH environment variable tells the Java compiler and Java Virtual
Machine where to find compiled Java classes (.class files), packages, and external libraries (usually
.jar files).
 The default value of CLASSPATH is a dot (.).
 It means the only current directory searched.
 The default value of CLASSPATH overrides when you set the CLASSPATH
variable or using the - classpath command (for short -cp).

6
Put a dot (.) in the new setting if you want to include the current directory in the search path.
The following table demonstrates the difference between a PATH and a CLASSPATH

S.
No. PATH CLASSPATH

An environment variable is used by the An environment variable is used by


1. operating system to find the executable the Java compiler to find the path of
files. classes.

PATH setting up an environment for the Classpath setting up the environment


2. operating system. Operating System will for Java. Java will use to find
look in this PATH for executables. compiled classes.

3. Refers to the Developing


Refers to the operating system.
Environment.

In classpath, we must place .\lib\jar


4. In path variable, we must place .\bin folder
file or directory path in which .java
path
file is available.

CLASSPATH is used by the


5. PATH is used by CMD prompt to find
compiler and JVM to find library
binary files.
files.

Illustration of user-defined packages: Creating our first package: File name – [Link]
package package_name;

public class ClassOne {


public void methodClassOne()
{
[Link]("Hello there its ClassOne");
}
}
Creating our second package: File name – [Link]

7
package package_one;

public class ClassTwo {


public void methodClassTwo()
{
[Link]("Hello there i am ClassTwo");
}
}

Making use of both the created packages: File name – [Link]


import package_name.ClassOne;
import package_one.ClassTwo;

public class Testing {


public static void main(String[] args)
{
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
[Link]();
[Link]();
}
}

Now having a look at the directory structure of both the packages and the testing class file:
testing class file:

8
Access Modifiers in the Context of Packages
 Public: Members with the public modifier are accessible from anywhere, regardless of
whether the accessing class is in the same package or not.
 Protected: Members with the protected modifier are accessible within the same package,
In subclasses
 Default: Members with no modifier are accessible only within the same package
 Private: Members with the private modifier are accessible only within the same class.
They cannot be accessed by classes in the same package, subclasses, or different
packages.
Important points:
 Every class is part of some package.
 If no package is specified, the classes in the file goes into a special unnamed package (the
same unnamed package for all files).
 All classes/interfaces in a file are part of the same package. Multiple files can specify the
same package name.

9
 If package name is specified, the file must be in a subdirectory called name (i.e., the
directory name must match the package name).
 We can access public classes in another (named) package using: [Link]-
name

File Handling in Java

In Java, file handling means creating, reading, writing, updating, or deleting files on the file
system. Java provides two main APIs for file operations:

 [Link] package – Older, widely used.


 [Link] package – Newer, more powerful (since Java 7)

Let us now get acquainted with the various file operations in Java.

File Operations
The following are the several operations that can be performed on a file in Java:
 Create a File
 Read from a File
 Write to a File
 Delete a File
1. Create a File
 In order to create a file in Java, you can use the createNewFile() method.
 If the file is successfully created, it will return a Boolean value true and false if the file
already exists.
Example:
// Creating File using Java Program

// Import the File class


import [Link];
import [Link];

public class CreateFile


{

10
public static void main(String[] args)
{
// Creating the File also
// Handling Exception
try {
File Obj = new File("[Link]");

// Creating File
if ([Link]()) {
[Link]("File created: " + [Link]());
}
else {
[Link]("File already exists.");
}
}

// Exception Thrown
catch (IOException e) {
[Link]("An error has occurred.");
[Link]();
}
}
}
Output:

2. Write to a File
11
We use the FileWriter class along with its write() method in order to write some text to the file.
Example:
// Writing Files using Java Program

// Import the FileWriter class


import [Link];
import [Link];

public class WriteFile


{
public static void main(String[] args)
{
// Writing Text File also
// Exception Handling
try {

FileWriter Writer = new FileWriter("[Link]");

// Writing File
[Link]("Files in Java are seriously good!!");
[Link]();

[Link]("Successfully written.");
}

// Exception Thrown
catch (IOException e) {
[Link]("An error has occurred.");

12
[Link]();
}
}
}
Output:

3. Read from a File


We will use the Scanner class in order to read contents from a file.
Example:
// Reading File using Java Program

// Import the File class


import [Link];
import [Link];
import [Link];

public class ReadFile


{
public static void main(String[] args)
{
// Reading File also
// Handling Exception
try {
File Obj = new File("[Link]");

13
Scanner Reader = new Scanner(Obj);

// Traversing File Data


while ([Link]()) {
String data = [Link]();
[Link](data);
}

[Link]();
}

// Exception Cases
catch (FileNotFoundException e) {
[Link]("An error has occurred.");
[Link]();
}
}
}
Output:

4. Delete a File
We use the delete() method in order to delete a file.
Example:
// Deleting File using Java Program
import [Link];

14
public class DeleteFile
{
public static void main(String[] args)
{
File Obj = new File("[Link]");

// Deleting File
if ([Link]()) {
[Link]("The deleted file is : " + [Link]());
}
else {
[Link](
"Failed in deleting the file.");
}
}
}
Output:

Java File Class Methods


The following table depicts several File Class methods:

Method Name Description Return Type

canRead() It tests whether the file is readable or not. Boolean

15
Method Name Description Return Type

canWrite() It tests whether the file is writable or not. Boolean

createNewFile() It creates an empty file. Boolean

delete() It deletes a file. Boolean

exists() It tests whether the file exists or not. Boolean

length() Returns the size of the file in bytes. Long

getName() Returns the name of the file. String

list() Returns an array of the files in the directory. String[]

mkdir() Creates a new directory. Boolean

getAbsolutePath() Returns the absolute pathname of the file. String

Example 1: Program to check if a file or directory physically exists or not.


// In this Java program, we accepts a file or directory name
// from command line arguments. Then the program will check
// if that file or directory physically exist or not and it
// displays the property of that file or directory.

import [Link];

16
// Displaying file property
class CheckFileExist
{
public static void main(String[] args)
{

// Accept file name or directory name through


// command line args
String fname = args[0];

// pass the filename or directory name to File


// object
File f = new File(fname);

// apply File class methods on File object


[Link]("File name :" + [Link]());
[Link]("Path: " + [Link]());
[Link]("Absolute path:" + [Link]());
[Link]("Parent:" + [Link]());
[Link]("Exists :" + [Link]());

if ([Link]()) {
[Link]("Is writable:" + [Link]());
[Link]("Is readable" + [Link]());
[Link]("Is a directory:" + [Link]());
[Link]("File Size in bytes " + [Link]());
}
}

17
}
Output:

18

You might also like