0% found this document useful (0 votes)
39 views38 pages

Packages

Java packages

Uploaded by

Pranav Balusu
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)
39 views38 pages

Packages

Java packages

Uploaded by

Pranav Balusu
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
You are on page 1/ 38

What is a Package?

A package is a grouping of related types (classes, interfaces,


Exceptions and Annotations) providing access protection and
Name Space Management.

Built-In packages are library packages.


Example: java.lang, java.awt etc.
Built-In

Package
User-defined packages are user developed
packages.
User-Defines
 Are containers for classes
 Used to keep the class name space
compartmentalized.
 Mechanism for partitioning the class name
space into more manageable chunks.
 It is both a naming and a visibility control
mechanism.
 include a package command as the first
statement in Java source file.
 classes declared in that file will belong to the
specified package.
 package st. defines namespace.
 Classes are put into default package if package
statement is omitted.
 General form :
 package pkg;
 Example :
 package MyPackage;
 Java uses file system directories to store
packages.
 Case is significant. Directory name must match
the package name exactly.
 More than one file can include same package
statement.
 It is possible to create hierarchy of packages.
Simply separate the packages using period.
 General form :
 package pkg1[.pkg2[.pkg3]];
 Example :
 package java.awt.image;
Creating a Packages?

Syntax to create a package:

package packagename;
Here package is the keyword used to create a package followed
by packagename.

Syntax to create a sub-package:

package package1.package2;
Here package1 is a package, which contains a subpackage
named package2.

Note
The package statement must be the first line in the source file.
Program to demonstrate packages:
package world;

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello World");
}
}

How to compile the above program:

➢ javac -d . HelloWorld.java

➢ “-d” stands for “directory“ which explains the compiler


the location where the class files should be created.

➢ .(dot) stands for the current directory.


Packages

What happens when we use package statement?

When we use a package statement, the underlying


operating system will create a directory with the same
name of the package.

As a programmer we should make sure that the .class


files should be compiled to the same package directory.

Make sure that you set the CLASSPATH to the directory


where the .class files are located.
After setting the classpath, we can run our programs as
follows:
>java packagename.classname
 Path of the classes – one can run from anywhere
using classpath
 We can use –classpath option with java and javac
to specify path to your classes.

java -classpath d:\JP\Prog\Packages MyPack.AccountBalance

 Set CLASSPATH environmental variable.


Java MyPack.AccountBalance

**classnames must be qualified by package name


Which of the following is incorrect statement about
packages?

a) Package defines a namespace in which classes are


stored.

b) A package can contain other package within it.

c) Java uses file system directories to store packages.

d) A package can be renamed without renaming the


directory in which the classes are stored.
 Standard classes are stored in some named
package.
 It is tedious to type fully qualified path name
whenever we want to use it.
 Java includes import statement to bring
classes, entire packages into visibility.
 A class can be referred directly once it is
imported.
 Imports statements occur immediately after
package statement.
 General form of import statement
import pkg1[.pkg2].(classname | *)

 There is no limit on the depth of a package


hierarchy.
import java.util.Date;
Import java.util.*;
 All Standard classes of Java are stored in a
package called java.
 Basic language functions are stored in a
subpackage called java.lang.
 java.lang is implicitly imported by the java
compiler for all programs.
import java.util.*;
class MyDate extends Date {
}

Is similar to

class MyDate extends java.util.Date{


}
Which of the following package stores all
the standard java classes?
a) lang
b) java
c) util
d) java.packages
 Java provides many levels of protection to
allow fine-grained control over the visibility of
variables and methods within classes,
subclasses and packages.
 Packages add another dimension to access
control.
 4 categories of visibility for class members
◦ Subclasses in the same package
◦ Non-subclasses in the same package
◦ Subclasses in different packages
◦ Classes that are neither in the same package nor
subclasses.
 May seem complicated.

 Simply
◦ Anything declared public can be accessed from
anywhere.
◦ Anything declared private cannot be seen outside
of its class.
No
Private Protected Public
Modifier
Same Class
Same package
subclass
Same package non-
subclass
Different package
subclass
Different package
non-subclass
No
Private Protected Public
Modifier
Same Class Yes Yes Yes Yes
Same package
No Yes Yes Yes
subclass
Same package non-
No Yes Yes Yes
subclass
Different package
No No Yes Yes
subclass
Different package
No No No Yes
non-subclass
 Class has only two possible access
levels
◦ default – if class has no modifer, then it
can be accessed by other code within its
same package.
◦ public - if a class is declared public, it is
accessible by any other code.
 Java SE (Standard  Key packages in JAVA
Edition) provides a rich SE
set of packages that are ◦ java.lang
part of the core Java ◦ java.util
platform. These ◦ java.io
packages contain ◦ java.net
classes and interfaces ◦ java.sql
that provide ◦ java.time
functionalities for basic ◦ java.math
language features, data ◦ java.awt
structures,
input/output, Write down purpose and
key classes of every
networking, package.
concurrency, and more.
 a core package in Java that is automatically imported into
every Java program.
 contains fundamental classes and interfaces essential for
Java programming, such as basic data types, strings,
mathematical operations, exceptions, and threading.
 java.lang provides classes that are necessary for most Java
programs.
 Key classes and interfaces
 Object Class –
◦ This is the root class of the Java class hierarchy.
◦ Every class in Java directly or indirectly inherits from the Object
class.
◦ It provides several methods that are inherited by all classes.
◦ Important Methods:
 equals(): Checks if two objects are equal.
 toString(): Returns a string representation of the object.
 hashCode(): Returns a hash code value for the object.
 clone(): Creates and returns a copy of the object.
 String Class
◦ Represents immutable sequences of characters. Strings in Java are objects, not arrays
of characters.
◦ Important Methods:
 length(): Returns the length of the string.
 charAt(int index): Returns the character at the specified index.
 substring(int beginIndex, int endIndex): Returns a new string that is a substring of this
string.
 concat(String str): Concatenates the specified string to the end of this string.
 Math Class
◦ Contains methods for performing basic numeric operations such as exponential,
logarithm, square root, and trigonometric functions.
◦ Important Methods:
 sqrt(double a): Returns the square root of a number.
 pow(double a, double b): Returns the value of the first argument raised to the power of
the second argument.
 max(int a, int b): Returns the greater of two int values.
 random(): Returns a random number between 0.0 and 1.0.
 System Class
◦ Provides methods for standard input, output, error streams, and access to external
system resources such as environment variables.
◦ Important Methods:
 currentTimeMillis(): Returns the current time in milliseconds.
 gc(): Requests garbage collection.
 exit(int status): Terminates the currently running Java Virtual Machine (JVM).
 out: Static member for output stream (e.g., System.out.println).
 Thread Class
◦ Represents a thread of execution in a program. The Thread
class provides methods to create and control threads in
Java.
◦ Important Methods:
 start(): Starts the thread.
 run(): Contains the code that constitutes the new thread.
 sleep(long millis): Causes the current thread to sleep for the
specified number of milliseconds.
 Exception and Throwable Classes
◦ These classes are the basis for error and exception
handling in Java. Exception is a subclass of Throwable,
which represents the hierarchy of exceptions in Java.
◦ Common Subclasses:
 IOException: Indicates an I/O error.
 RuntimeException: Unchecked exceptions like division by zero
or null pointer access.
 root of the class hierarchy, - every class in Java
implicitly inherits from Object.
 part of the java.lang package
 automatically imported into every Java program.
 provides several crucial methods that every Java
object can use.
 These methods are essential for tasks like
comparison between objects, object cloning,
obtaining hash codes, and converting objects to
strings.
 Key features of object class
◦ Superclass of all classes
◦ Default behavior for methods
 equals(Object obj)
◦ checks if two objects are equal.
◦ By default, the equals() method compares the memory addresses
 toString()
◦ returns a string representation of the object.
◦ By default, it returns the class name followed by the @ symbol and
the hexadecimal hash code of the object.
◦ It is often overridden to provide a more meaningful string
representation.
 hashCode()
◦ returns a hash code value for the object.
◦ If two objects are equal according to the equals() method, they
must have the same hash code.
 getClass()
◦ returns the runtime class of the object.
 wait() and notify()
◦ are used in multithreading to synchronize the activities of threads.
◦ wait() causes the current thread to wait until another thread calls
notify() or notifyAll() on the same object.
 part of the java.lang package
 provides a collection of methods for performing basic
mathematical operations like exponential, logarithmic,
square root, and trigonometric calculations.
 The methods in the Math class are static, so they can be
called directly without creating an instance of the class.
Key Features of the Math Class
 Utility Class for Mathematical Operations
◦ The Math class provides a wide range of mathematical functions
for various calculations.
 Constant Values
◦ The Math class defines two useful constants:
◦ Math.PI: Represents the value of π (approximately 3.14159).
◦ Math.E: Represents the base of the natural logarithms
(approximately 2.71828).
 Math.abs() : Returns the absolute value of a number.
 Math.max() returns the maximum of two numbers, and
Math.min() returns the minimum of two numbers.
 Math.pow() : Raises a number to the power of another number
(exponentiation).
 Math.sqrt() : Returns the square root of a number.
 Math.random() : Returns a random number between 0.0
(inclusive) and 1.0 (exclusive).
 Math.round() : Rounds a floating-point number to the nearest
integer.
 Math.ceil(): Rounds a number up to the nearest integer.
 Math.floor(): Rounds a number down to the nearest integer.
 Math.log(): Returns the natural logarithm (base e) of a number.
 Math.exp(): Returns Euler's number e raised to the power of the
input.
 used to convert primitive data
types (such as int, char, float, etc.)
into objects.
 Java provides these classes for all
primitive data types, and they allow
primitive values to be treated as
objects, which is useful in
situations where only objects can
be used
 wrapper classes are part of
java.lang package
 uses of wrapper classes
◦ object oriented programming
◦ utility methods
◦ autoboxing and unboxing
◦ Methods to convert, compare, or parse
primitive values
 parseInt(String s) (in Integer class): Converts a String to an int.
int number = Integer.parseInt("123");

 valueOf(String s) (in Integer class): Converts a String to an Integer object.


Integer num = Integer.valueOf("123");
 toString(): Converts a primitive or wrapper object to a String.
Integer num = 50;
String str = num.toString();

 compareTo(T o):Compares two wrapper objects.


Integer num1 = 100;
Integer num2 = 200;
int comparison = num1.compareTo(num2); // Returns -1, 0, or 1

 MAX_VALUE and MIN_VALUE: Constants representing the maximum and minimum


values of the wrapper's corresponding primitive type.
int maxInt = Integer.MAX_VALUE;
int minInt = Integer.MIN_VALUE;
 simplify the conversion between primitive data types and
their corresponding wrapper classes.
 Autoboxing:
◦ Automatically converting a primitive type to its corresponding
wrapper class object.
◦ For example:
 int is autoboxed into Integer.
 double is autoboxed into Double.
 Unboxing:
◦ Automatically converting a wrapper class object back to its
corresponding primitive type.
◦ For example:
 Integer is unboxed into int.
 Double is unboxed into double.
 These conversions happen automatically during
assignments or method calls and are done by the Java
compiler.
 Java also allows autoboxing and unboxing to happen in
expressions, where operations between primitive types
and wrapper objects are performed automatically.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy