Packages in Java allow grouping of related classes and avoid naming collisions. A package is mapped to a directory on the file system where Java files for that package are stored. There are predefined packages provided by Java and user-defined packages can also be created. Packages are specified using the package keyword and imported into other classes using import statements. The classpath variable is used to locate packages and classes for compilation and execution.
A package allows a developer to group classes (and interfaces) together. These classes will all be related in some way – they might all have to do with a specific application or perform a specific set of tasks.
This presentation introduces Java packages, including system packages that are part of the Java API and user-defined packages. It discusses how packages organize related classes and interfaces, the structure of package names and directories, and how to create and access packages. Packages provide advantages like grouping related code, preventing name collisions, and improving reusability.
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,packages in java, java packages notes, java packages notes,different types of packages in Java,packages with an example, packages in Java
Packages and interfaces are two of Java's most innovative features. Packages are used to group related classes and avoid naming conflicts by providing a mechanism to partition the class namespace into more manageable chunks. Packages also provide access control, with protected and default members having package-level access. To define a package, the package statement is included at the top of a Java file specifying the package name. Import statements are used to make classes in other packages visible. Packages can be built-in, from the Java API, or user-defined.
This document discusses Java programming packages. It explains that Java API provides predefined packages organized by functionality. Packages are hierarchical, so classes can be accessed using package names and dot notation. The import statement allows accessing package classes without fully qualifying names. To create a package, the package keyword declares the name, then classes within that package are defined and stored in a subdirectory matching the package name. Packages can be accessed using import or fully qualifying class names with the package path.
Packages in Java provide a mechanism for organizing classes and interfaces by grouping related ones together. Packages can control visibility and access to classes. The package statement specifies the package a class belongs to, and packages are mapped to directories in the file system. Interfaces in Java specify a contract that classes can implement, defining method signatures but not bodies. This allows for abstraction and polymorphism.
The document discusses object oriented programming concepts related to packages, interfaces, and their implementation in Java. It defines what packages and interfaces are, how to create and access packages, differences between classes and interfaces, how to define and implement interfaces, and examples of applying packages and interfaces in Java code.
This document summarizes key concepts about packages, classes, and the static keyword in Java. It discusses how packages are used to organize classes and prevent naming conflicts. It also explains that the static keyword in Java is used for memory management and that static variables, methods, blocks, and nested classes belong to the class rather than object instances. The document provides examples of how to define packages and use the static keyword with variables, methods, and blocks in Java programs.
This document discusses Java packages. It explains that packages allow for organizing classes into namespaces to achieve code reuse and prevent naming collisions. Packages act as containers that group related classes and interfaces. The document also provides details on using packages from the Java API, package access protection, creating JAR files, package naming conventions, and common mistakes when working with packages.
Packages in Java help organize code by providing a layer of encapsulation and control. Packages group related classes and interfaces together, and allow classes to be made private to a package. To define a package, use the package statement at the top of a file with the package name. Multiple files can belong to the same package. Packages are hierarchical, with names separated by periods. Directories mirror package hierarchies.
This document discusses packages in Java. It defines packages as containers for grouping related classes and interfaces. There are built-in packages provided by Java, such as java.lang for core classes and java.util for utility classes. Users can also create their own packages by specifying the package name at the top of a file and storing the class files in a subdirectory matching the package name. Packages provide advantages like organizing related classes, hiding classes to prevent accidental deletion, and allowing class name reuse across packages.
This document discusses Java packages and interfaces. It explains that packages organize Java files into directories based on functionality, and interfaces define collections of abstract methods that classes can implement. The document also covers importing packages, implementing interfaces, nested interfaces, and interfaces extending other interfaces.
Packages allow partitioning of classes into namespaces for organization. To define a package, include a package statement with the package name at the top of a Java file. Classes within that file will belong to the specified package. Package names must match the subdirectory used to store the .class files. The import statement allows referring to classes from other packages without specifying the full package name.
Class importing, Creating a Package, Naming a Package, Using Package Members,
Managing Source and Class Files. Developing and deploying (executable) Jar File.
Packages in Java allow classes to be grouped together and reused. Packages provide a way to uniquely name classes and hide classes from other packages. The Java API contains many pre-defined packages that are organized hierarchically, such as java.awt for graphical user interface classes. Classes in a package can be accessed using either fully qualified names or import statements. User-defined packages follow similar conventions as the Java API packages.
Packages in Java are used to categorize classes and interfaces to facilitate organization and access protection. There are two types of packages - built-in packages that are part of the Java API, and user-defined packages that are created by the user. Classes can be imported into other packages using either "import package.*" to access all classes, "import package.classname" to access a specific class, or the fully qualified name. This allows code reuse through organizing related classes and controlling access.
The document discusses Java packages. The key points are:
- Packages are containers that group related classes and interfaces together. They allow for organizing code and uniquely naming classes.
- The core Java packages are java.lang, java.util, java.io, java.awt, java.net, and java.applet. They contain fundamental classes for various purposes.
- To use classes from a package, the package must be imported or the fully qualified class name can be used. The package statement declares user-defined packages.
Packages in Java provide three main benefits: reusability, allowing classes with the same name in different packages, and hiding classes to prevent other packages from accessing them. Packages are organized hierarchically, so sub-packages can be created within packages. Classes within a package are accessible to other classes in the same package, and classes declared public in one package are accessible to another package.
A package in Java is a grouping of related classes and interfaces that provides namespacing to avoid naming conflicts. There are two types of packages: predefined packages provided by Java and user-defined packages. Packages provide advantages like reusability and better organization. Some key predefined packages include java.lang, java.io, java.util, java.applet, and java.awt. To define a user package, include the package statement as the first line in a Java source file, which specifies the package name. Classes in that file will belong to that package.
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,packages in java, java packages notes, java packages notes,different types of packages in Java,packages with an example, packages in Java
Packages in Java allow grouping of related classes and interfaces to avoid naming collisions. Some key points about packages include:
- Packages allow for code reusability and easy location of files. The Java API uses packages to organize core classes.
- Custom packages can be created by specifying the package name at the beginning of a Java file. The class files are then compiled to the corresponding directory structure.
- The import statement and fully qualified names can be used to access classes from other packages. The classpath variable specifies locations of package directories and classes.
How to Buy Snapchat Account A Step-by-Step Guide.pdfjamedlimmk
Scaling Growth with Multiple Snapchat Accounts: Strategies That Work
Operating multiple Snapchat accounts isn’t just a matter of logging in and out—it’s about crafting a scalable content strategy. Businesses and influencers who master this can turn Snapchat into a lead generation engine.
Key strategies include:
Content Calendars for Each Account – Plan distinct content buckets and themes per account to avoid duplication and maintain variety.
Geo-Based Content Segmentation – Use location-specific filters and cultural trends to speak directly to a region's audience.
Audience Mapping – Tailor messaging for niche segments: Gen Z, urban youth, gamers, shoppers, etc.
Metrics-Driven Storytelling – Use Snapchat Insights to monitor what type of content performs best per account.
Each account should have a unique identity but tie back to a central brand voice. This balance is crucial for brand consistency while leveraging the platform’s creative freedoms.
How Agencies and Creators Handle Bulk Snapchat Accounts
Digital agencies and creator networks often manage dozens—sometimes hundreds—of Snapchat accounts. The infrastructure to support this requires:
Dedicated teams for each cluster of accounts
Cloud-based mobile device management (MDM) systems
Permission-based account access for role clarity
Workflow automation tools (Slack, Trello, Notion) for content coordination
This is especially useful in verticals such as music promotion, event marketing, lifestyle brands, and political outreach, where each campaign needs targeted messaging from different handles.
The Legality and Risk Profile of Bulk Account Operations
If your aim is to operate or acquire multiple Snapchat accounts, understand the risk thresholds:
Personal Use (Low Risk) – One or two accounts for personal and creative projects
Business Use (Medium Risk) – Accounts with aligned goals, managed ethically
Automated Bulk Use (High Risk) – Accounts created en masse or used via bots are flagged quickly
Snapchat uses advanced machine learning detection for unusual behavior, including:
Fast switching between accounts from the same IP
Identical Snap stories across accounts
Rapid follower accumulation
Use of unverified devices or outdated OS versions
To stay compliant, use manual operations, vary behavior, and avoid gray-market account providers.
Smart Monetization Through Multi-Account Snapchat Strategies
With a multi-account setup, you can open doors to diversified monetization:
Affiliate Marketing – Niche accounts promoting targeted offers
Sponsored Content – Brands paying for story placement across multiple profiles
Product Launch Funnels – Segment users by interest and lead them to specific landing pages
Influencer Takeovers – Hosting creators across multiple themed accounts for event buzz
This turns your Snapchat network into a ROI-driven asset instead of a time sink.
Conclusion: Build an Ecosystem, Not Just Accounts
When approached correctly, multiple Snapchat accounts bec
Ad
More Related Content
Similar to Module-4 Java Notes.docx notes about java (20)
This document discusses Java programming packages. It explains that Java API provides predefined packages organized by functionality. Packages are hierarchical, so classes can be accessed using package names and dot notation. The import statement allows accessing package classes without fully qualifying names. To create a package, the package keyword declares the name, then classes within that package are defined and stored in a subdirectory matching the package name. Packages can be accessed using import or fully qualifying class names with the package path.
Packages in Java provide a mechanism for organizing classes and interfaces by grouping related ones together. Packages can control visibility and access to classes. The package statement specifies the package a class belongs to, and packages are mapped to directories in the file system. Interfaces in Java specify a contract that classes can implement, defining method signatures but not bodies. This allows for abstraction and polymorphism.
The document discusses object oriented programming concepts related to packages, interfaces, and their implementation in Java. It defines what packages and interfaces are, how to create and access packages, differences between classes and interfaces, how to define and implement interfaces, and examples of applying packages and interfaces in Java code.
This document summarizes key concepts about packages, classes, and the static keyword in Java. It discusses how packages are used to organize classes and prevent naming conflicts. It also explains that the static keyword in Java is used for memory management and that static variables, methods, blocks, and nested classes belong to the class rather than object instances. The document provides examples of how to define packages and use the static keyword with variables, methods, and blocks in Java programs.
This document discusses Java packages. It explains that packages allow for organizing classes into namespaces to achieve code reuse and prevent naming collisions. Packages act as containers that group related classes and interfaces. The document also provides details on using packages from the Java API, package access protection, creating JAR files, package naming conventions, and common mistakes when working with packages.
Packages in Java help organize code by providing a layer of encapsulation and control. Packages group related classes and interfaces together, and allow classes to be made private to a package. To define a package, use the package statement at the top of a file with the package name. Multiple files can belong to the same package. Packages are hierarchical, with names separated by periods. Directories mirror package hierarchies.
This document discusses packages in Java. It defines packages as containers for grouping related classes and interfaces. There are built-in packages provided by Java, such as java.lang for core classes and java.util for utility classes. Users can also create their own packages by specifying the package name at the top of a file and storing the class files in a subdirectory matching the package name. Packages provide advantages like organizing related classes, hiding classes to prevent accidental deletion, and allowing class name reuse across packages.
This document discusses Java packages and interfaces. It explains that packages organize Java files into directories based on functionality, and interfaces define collections of abstract methods that classes can implement. The document also covers importing packages, implementing interfaces, nested interfaces, and interfaces extending other interfaces.
Packages allow partitioning of classes into namespaces for organization. To define a package, include a package statement with the package name at the top of a Java file. Classes within that file will belong to the specified package. Package names must match the subdirectory used to store the .class files. The import statement allows referring to classes from other packages without specifying the full package name.
Class importing, Creating a Package, Naming a Package, Using Package Members,
Managing Source and Class Files. Developing and deploying (executable) Jar File.
Packages in Java allow classes to be grouped together and reused. Packages provide a way to uniquely name classes and hide classes from other packages. The Java API contains many pre-defined packages that are organized hierarchically, such as java.awt for graphical user interface classes. Classes in a package can be accessed using either fully qualified names or import statements. User-defined packages follow similar conventions as the Java API packages.
Packages in Java are used to categorize classes and interfaces to facilitate organization and access protection. There are two types of packages - built-in packages that are part of the Java API, and user-defined packages that are created by the user. Classes can be imported into other packages using either "import package.*" to access all classes, "import package.classname" to access a specific class, or the fully qualified name. This allows code reuse through organizing related classes and controlling access.
The document discusses Java packages. The key points are:
- Packages are containers that group related classes and interfaces together. They allow for organizing code and uniquely naming classes.
- The core Java packages are java.lang, java.util, java.io, java.awt, java.net, and java.applet. They contain fundamental classes for various purposes.
- To use classes from a package, the package must be imported or the fully qualified class name can be used. The package statement declares user-defined packages.
Packages in Java provide three main benefits: reusability, allowing classes with the same name in different packages, and hiding classes to prevent other packages from accessing them. Packages are organized hierarchically, so sub-packages can be created within packages. Classes within a package are accessible to other classes in the same package, and classes declared public in one package are accessible to another package.
A package in Java is a grouping of related classes and interfaces that provides namespacing to avoid naming conflicts. There are two types of packages: predefined packages provided by Java and user-defined packages. Packages provide advantages like reusability and better organization. Some key predefined packages include java.lang, java.io, java.util, java.applet, and java.awt. To define a user package, include the package statement as the first line in a Java source file, which specifies the package name. Classes in that file will belong to that package.
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,packages in java, java packages notes, java packages notes,different types of packages in Java,packages with an example, packages in Java
Packages in Java allow grouping of related classes and interfaces to avoid naming collisions. Some key points about packages include:
- Packages allow for code reusability and easy location of files. The Java API uses packages to organize core classes.
- Custom packages can be created by specifying the package name at the beginning of a Java file. The class files are then compiled to the corresponding directory structure.
- The import statement and fully qualified names can be used to access classes from other packages. The classpath variable specifies locations of package directories and classes.
How to Buy Snapchat Account A Step-by-Step Guide.pdfjamedlimmk
Scaling Growth with Multiple Snapchat Accounts: Strategies That Work
Operating multiple Snapchat accounts isn’t just a matter of logging in and out—it’s about crafting a scalable content strategy. Businesses and influencers who master this can turn Snapchat into a lead generation engine.
Key strategies include:
Content Calendars for Each Account – Plan distinct content buckets and themes per account to avoid duplication and maintain variety.
Geo-Based Content Segmentation – Use location-specific filters and cultural trends to speak directly to a region's audience.
Audience Mapping – Tailor messaging for niche segments: Gen Z, urban youth, gamers, shoppers, etc.
Metrics-Driven Storytelling – Use Snapchat Insights to monitor what type of content performs best per account.
Each account should have a unique identity but tie back to a central brand voice. This balance is crucial for brand consistency while leveraging the platform’s creative freedoms.
How Agencies and Creators Handle Bulk Snapchat Accounts
Digital agencies and creator networks often manage dozens—sometimes hundreds—of Snapchat accounts. The infrastructure to support this requires:
Dedicated teams for each cluster of accounts
Cloud-based mobile device management (MDM) systems
Permission-based account access for role clarity
Workflow automation tools (Slack, Trello, Notion) for content coordination
This is especially useful in verticals such as music promotion, event marketing, lifestyle brands, and political outreach, where each campaign needs targeted messaging from different handles.
The Legality and Risk Profile of Bulk Account Operations
If your aim is to operate or acquire multiple Snapchat accounts, understand the risk thresholds:
Personal Use (Low Risk) – One or two accounts for personal and creative projects
Business Use (Medium Risk) – Accounts with aligned goals, managed ethically
Automated Bulk Use (High Risk) – Accounts created en masse or used via bots are flagged quickly
Snapchat uses advanced machine learning detection for unusual behavior, including:
Fast switching between accounts from the same IP
Identical Snap stories across accounts
Rapid follower accumulation
Use of unverified devices or outdated OS versions
To stay compliant, use manual operations, vary behavior, and avoid gray-market account providers.
Smart Monetization Through Multi-Account Snapchat Strategies
With a multi-account setup, you can open doors to diversified monetization:
Affiliate Marketing – Niche accounts promoting targeted offers
Sponsored Content – Brands paying for story placement across multiple profiles
Product Launch Funnels – Segment users by interest and lead them to specific landing pages
Influencer Takeovers – Hosting creators across multiple themed accounts for event buzz
This turns your Snapchat network into a ROI-driven asset instead of a time sink.
Conclusion: Build an Ecosystem, Not Just Accounts
When approached correctly, multiple Snapchat accounts bec
Interfacing PMW3901 Optical Flow Sensor with ESP32CircuitDigest
Learn how to connect a PMW3901 Optical Flow Sensor with an ESP32 to measure surface motion and movement without GPS! This project explains how to set up the sensor using SPI communication, helping create advanced robotics like autonomous drones and smart robots.
YJIT can make Ruby code run faster, but this is a balancing act, because the JIT compiler itself must consume both memory and CPU cycles to compile and optimize your code while it is running. Furthermore, in large-scale production environments such as those of GitHub, Shopify and Stripe, we end up in a situation where YJIT is compiling the same code over and over again on a very large number of servers, which seems very inefficient.
In this presentation, we will go over the design of ZJIT, a next generation Ruby JIT which aims to save and reuse compiled code between executions. We hope that this will help us eliminate duplicated work while also allowing the compiler to spend more time optimizing code so that we can get better performance.
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfMohamedAbdelkader115
Glad to be one of only 14 members inside Kuwait to hold this credential.
Please check the members inside kuwait from this link:
https://www.rics.org/networking/find-a-member.html?firstname=&lastname=&town=&country=Kuwait&member_grade=(AssocRICS)&expert_witness=&accrediation=&page=1
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
Cloud Platform Architecture over Virtualized Datacenters: Cloud Computing and
Service Models, Data Center Design and Interconnection Networks, Architectural Design of Compute and Storage Clouds, Public Cloud Platforms: GAE, AWS and Azure, Inter-Cloud
Resource Management.
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
In tube drawing process, a tube is pulled out through a die and a plug to reduce its diameter and thickness as per the requirement. Dimensional accuracy of cold drawn tubes plays a vital role in the further quality of end products and controlling rejection in manufacturing processes of these end products. Springback phenomenon is the elastic strain recovery after removal of forming loads, causes geometrical inaccuracies in drawn tubes. Further, this leads to difficulty in achieving close dimensional tolerances. In the present work springback of EN 8 D tube material is studied for various cold drawing parameters. The process parameters in this work include die semi-angle, land width and drawing speed. The experimentation is done using Taguchi’s L36 orthogonal array, and then optimization is done in data analysis software Minitab 17. The results of ANOVA shows that 15 degrees die semi-angle,5 mm land width and 6 m/min drawing speed yields least springback. Furthermore, optimization algorithms named Particle Swarm Optimization (PSO), Simulated Annealing (SA) and Genetic Algorithm (GA) are applied which shows that 15 degrees die semi-angle, 10 mm land width and 8 m/min drawing speed results in minimal springback with almost 10.5 % improvement. Finally, the results of experimentation are validated with Finite Element Analysis technique using ANSYS.
1. OOP with JAVA(BCS306A)
MODULE -4
Packages:
Module 4
Chapter 1-
Packages
Java provides a mechanism for partitioning the class name space into more manageable
chunks. This mechanism is the package.
The package is both a naming and a visibility control mechanism. You can define classes
inside a package that are not accessible by code outside that package. You can also define
class members that are only exposed to other members of the same package.
Defining a Package:
To create a package is quite easy: include a package command as the first statement in a
Java source file.
Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored. If you omit the
package statement, the class names are put into the default package, which has noname.
The general form of the package statement:
package pkg;
Here, pkg is the name of the package.
For example, the following statement creates a package called
MyPackage.package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called
MyPackage.
Remember that case is significant, and the directory name must match the package name
exactly.
More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong.
2. OOP with JAVA(BCS306A)
MODULE -4
Use can create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period.
The general form of a multileveled package statement is :
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development
system.
For example, a package declared as
package java.awt.image;
Finding Packages and CLASSPATH:
Packages are mirrored by directories.
The Java run-time system know where to look for packages that user create
First, by default, the Java run-time system uses the current working directory as its
starting point. Thus, if your package is in a subdirectory of the current directory, it
will be found.
Second, you can specify a directory path or paths by setting the
CLASSPATH environmental variable.
Third, you can use the -classpath option with java and javac to specifythe path to
your classes.
For example, consider the following package specification:package MyPack
can be executed from a directory immediately above MyPack, or the CLASSPATH must be
set to include the path to MyPack, or the -classpath option must specify the path to MyPack
when the program is run via java.
When the second two options are used, the class path must not include MyPack, itself.
It must simply specify the path to MyPack. For example, in a Windows environment, if
the path to MyPack is
C:MyProgramsJavaMyPack
Then the class path to MyPack is
C:MyProgramsJava
3. A Short Package Example:
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b)
{ name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("-->
");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[])
{ Balance current[] = new Balance[3];
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called MyPack.
Next, compile the file. Make sure that the resulting .class file is also in the MyPack
directory.
Then, try executing the AccountBalance class, using the following command line:
java MyPack.AccountBalance
4. Packages and Member Access:
Packages add another dimension to access control.
Java provides many levels of protection to allow fine-grained control over the visibility
of variables and methods within classes, subclasses, and packages Classes and packages
are both means of encapsulating and containing the name space and scope of variables
and methods.
Packages act as containers for classes and other subordinate packages.
Classes act as containers for data and code. The class is Java’s smallest unit of
abstraction.
Because of the interplay between classes and packages, Java addresses four categoriesof
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
The three access specifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories.
Table sums up the interactions.
Anything declared public can be accessed from different classes and different packages.
Anything declared private cannot be seen outside of its class.
When a member does not have an explicit access specification, it is visible to subclasses as
well as to other classes in the same package. This is the default access.
If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.
An Access Example:
This example has two packages and five classes. The classes for the two different
packages need to be stored in directories named after their respective packages in this
case, p1 and p2.
5. The source for the first package defines three classes: Protection, Derived, and
SamePackage. The first class defines four int variables in each of the legal protection
modes.
The variable n is declared with the default protection, n_pri is private, n_pro is protected,
and n_pub is public.
The second class, Derived, is a subclass of Protection in the same package, p1. This grants
Derived access to every variable in Protection except for n_pri, the private one.
The third class, SamePackage, is not a subclass of Protection, but is in the same package
and also has access to all but n_pri.
6. public class Demo
{
public static void main(String args[])
{
Protection ob1 = new Protection();
Derived ob2 = new Derived();
Same Package ob3 = new Same Package ();
}
}
Following is the source code for the other package, p2. The two classes defined in p2 cover
the other two conditions that are affected by access control.
The first class, Protection2, is a subclass of p1.Protection. This grants access to all of
p1.Protection’s variables except for n_pri (because it is private) and n, the variable declared
with the default protection.
The default only allows access from within the class or the package, not extra-package
subclasses.
Finally, the class OtherPackage has access to only one variable, n_pub, which was declared
public.
Protection2.java:
package p2;
class Protection2 extends pl. Protection
{
Protection2 ( )
{
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n”,+n);
// class only
// System.out.println("n_pri =” n_pri );
System.out.println("n_pro =” n_pro);
System.out.println("n_pub =” n_pub);
}
}
OtherPackage.java:
7. package p2;
class Other Package {
Other Package ( )
{
pl. Protection p = new pl. Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n”+n);
// class only
System.out.println("n_pub =” n_pub);
}
}
public class Demo {
public static void main(String args[ ])
{
Protection2 ob1 = new Protection2 ();
Other Package ob2 = new OtherPackage ();
}
Importing Packages:
Given that packages exist, it is easy to see why all of the built-in Java classes are stored
in packages.
There are no core Java classes in the unnamed default package; all of the standard classes
are stored in some named package.
Java includes the import statement to bring certain classes, or entire packages, into
visibility.
Once imported, a class can be referred to directly, using only its name. The import
statement is a convenience to the programmer and is not technically needed to write a
complete Java program.
If you are going to refer to a few dozen classes in your application, however, the
import statement will save a lot of typing.
This is the general form of the import statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.).
There is no practical limit on the depth of a package hierarchy, except that imposed bythe
file system.
8. Finally, you specify either an explicit classname or a star (*), which indicates that the
Java compiler should import the entire package.
This code fragment shows both forms in use:
import java.util.Date;
import java.io.*;
All of the standard Java classes included with Java are stored in a package called
java.
The basic language functions are stored in a package inside of the java package called
java.lang. This is equivalent to the following line being at the top of all of your
programs:
import java.lang.*;
If a class with the same name exists in two different packages that you import using the
star form, the compiler will remain silent, unless you try to use one of the classes.
In that case, you will get a compile-time error and have to explicitly name the class
specifying its package.
It must be emphasized that the import statement is optional. Any place you use a
class name, you can use its fully qualified name, which includes its full package
hierarchy.
For example, this fragment uses an import statement:
import java.util.*;
class MyDate extends Date {
}
The same example without the import statement looks like this:
class MyDate extends java.util.Date {
}
In this version, Date is fully-qualified.
Example program:
package mypack;
public class Balance
{
String name;
double bal;
Balance(String n, double b)
{ name = n;
9. bal = b;
}
public void show( )
{
System.out.println(“name and salary is ”, +name“ ”+bal);
}
}
Import mypack;
class AccountBalance
{
public static void main(String args[])
{
Balance cur = new Balance(current,10000);
cur.show();
}
}
Output: name is : current 10000.
Chapter-2: Exceptions
Exception-Handling Fundamentals
An exception is an abnormal condition that arises in a code sequence at run time.
In other words, an exception is a run-time error.
In computer languages that do not support exception handling, errors must be checked and
handled manually through the use of error codes, and so on.
Java’s exception handling avoids these problems and, in the process, brings run-time error
management into the object-oriented world.
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code.
When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error. That method may choose to handle the
exception itself, or pass it on.
Either way, at some point, the exception is caught and processed. Exceptions can be
generated by the Java run-time system, or they can be manually generated by user code.
Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java
10. language or the constraints of the Java execution environment.
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
Program statements that user want to monitor for exceptions are contained within a try
block.
If an exception occurs within the try block, it is thrown. Users code can catch this
exception (using catch) and handle it in some rational manner.
System generated exceptions are automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword throw.
Any exception that is thrown out of a method must be specified as such by a throws clause.
Any code that must be executed after a try block completion is put in a finally block.
The general form of an exception-handling block:
Here, ExceptionType is the type of exception that has occurred.
Exception Types:
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at
the top of the exception class hierarchy.
Immediately below Throwable are two subclasses that partition exceptions into two
distinct branches.
One branch is headed by Exception. This class is used for exceptional conditions that user
programs should catch.
There is an important subclass of Exception, called RuntimeException.
Exceptions of this type are automatically defined for the programs that you write and
include things such as division by zero and invalid array indexing.
The other branch is topped by Error, which defines exceptions that are not expected to be
caught under normal circumstances by your program.
11. Exceptions of type Error are used by the Java run-time system to indicate errors having to
do with the run-time environment, itself. Ex: Stack overflow.
The top-level exception hierarchy is shown here:
Uncaught Exceptions:
For Example: When the Java run-time system detects the attempt to divide by zero, it
constructs a new exception object and then throws this exception.
This causes the execution of Exc0 to stop, because once an exception has been thrown, it
must be caught by an exception handler and dealt with immediately.
In this example, the exception is caught by the default handler provided by the Java run-
time system.
Any exception that is not caught by your program will ultimately be processed by the
default handler.
The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program.
Here is the exception generated when this example is executed:
Here, the class name Exc0, the method name main, the filename, Exc0.java; and the line
number, 4, the bottom of the stack is main’s line 7, which is the call to subroutine( ),
which caused the exception at line 4. All are included in the simple stack trace.
12. The type of exception thrown is a subclass of Exception called ArithmeticException,
which more specifically describes what type of error happened.
The stack trace will always show the sequence of method invocations that led up to the
error.
Using try and catch:
Whenever, User want to handle an exception manually then try catch block will be used.
doing so provides two benefits. First, it allows you to fix the error. Second, it prevents the
program from automatically terminating.
To guard against and handle a run-time error, simply enclose the code that you want to
monitor inside a try block. Immediately following the try block, include a catch clause that
specifies the exception type that you wish to catch.
For Example, the following program includes a try block and a catch clause that processes
the ArithmeticException generated by the division-by-zero error:
The call to println( ) inside the try block is never executed. Once an exception is thrown,
program control transfers out of the try block into the catch block.
Put differently, catch is not “called,” so execution never “returns” to the try block from a
catch. Thus, the line "This will not be printed." is not displayed.
Once the catch statement has executed, program control continues with the next line in the
program following the entire try / catch mechanism.
A try and its catch statement form a unit. The scope of the catch clause is restricted to
those statements specified by the immediately preceding try statement.
A catch statement cannot catch an exception thrown by another try statement.
The goal of most well-constructed catch clauses should be to resolve the exceptional
condition and then continue on as if the error had never happened.
13. Displaying a Description of an Exception:
Throwable overrides the toString( ) method (defined by Object) so that it returns a string
containing a description of the exception.
User can display this description in a println( ) statement by simply passing the exception
as an argument.
For example, the catch block in the preceding program can be rewritten like this:
When this version is substituted in the program, and the program is run, each divide-by-
zero error displays the following message:
Exception: java.lang.ArithmeticException: / by zero
Multiple catch Clauses:
In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses, each catching
a different type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first one
whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution continues after
the try / catch block.
The following example traps two different exception types:
This program will cause a division-by-zero exception if it is started with no command-line
arguments, since a will equal zero.
It will survive the division if user provide a command-line argument, setting a to
something larger than zero.
14. But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length
of 1, yet the program attempts to assign a value to c.
Here is the output generated by running it both ways:
C:>java MultipleCatches
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:>java MultipleCatches TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:
Index 42 out of bounds for length 1
After try/catch blocks.
Nested try Statements:
The try statement can be nested. That is, a try statement can be inside the block of
another try.
Each time a try statement is entered, the context of that exception is pushed on the
stack.
If an inner try statement does not have a catch handler for a particular exception, the
stack is unwound and the next try statement’s catch handlers are inspected for a match.
This continues until one of the catch statements succeeds, or until all of the nested try
statements are exhausted. If no catch statement matches, then the Java run-time system
will handle the exception.
Here is an example that uses nested try statements:
class NestTry {
public static void main(String args[ ]) {
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try
{
if(a==2) {
int c[] = { 1 };
15. c[42] = 99;
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
This program nests one try block within another. The program works as follows.
When you execute the program with no command line arguments, a divide-by-zero
exception is generated by the outer try block.
Execution of the program with one command-line argument generates a divide-by-zero
exception from within the nested try block.
Since the inner block does not catch this exception, it is passed on to the outer try
block, where it is handled.
If you execute the program with two command-line arguments, an array boundary
exception is generated from within the inner try block.
Here are sample runs that illustrate each case:
Output:
C:>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:
16. Index 42 out of bounds for length 1
Nesting of try statements can occur in less obvious ways when method calls are
involved.
For example, you can enclose a call to a method within a try block. Inside that method
is another try statement.
In this case, the try within the method is still nested inside the outer try block, which
calls the method.
throw:
It is possible for user program to throw an exception explicitly, using the throw
statement.
The general form of throw is :
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
Primitive types, such as int or char, as well as non-Throwable classes, such as String and
Object, cannot be used as exceptions.
There are two ways you can obtain a Throwable object: using a parameter in a catch
clause or creating one with the new operator.
The flow of execution stops immediately after the throw statement, any subsequent
statements are not executed.
The nearest enclosing try block is inspected to see if it has a catch statement that
matches the type of exception.
If it does find a match, control is transferred to that statement. If not, then the next
enclosing try statement is inspected, and so on.
If no matching catch is found, then the default exception handler halts the program and
prints the stack trace.
Sample program that creates and throws an exception:
17. The handler that catches the exception rethrows it to the outer handler.
This program gets two chances to deal with the same error. First, main( ) sets up an
exception context and then calls demoproc( ).
The demoproc( ) method then sets up another exception-handling context and
immediately throws a new instance of NullPointerException, which is caught on the
next line.
The exception is then rethrown. Here is the resulting output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
The program also illustrates how to create one of Java’s standard exception objects:
throw new NullPointerException("demo");
Here, new is used to construct an instance of NullPointerException.
Many of Java’s built-in run-time exceptions have at least two constructors: one with no
parameter and one that takes a string parameter.
When the second form is used, the argument specifies a string that describes the
exception. This string is displayed when the object is used as an argument to print( ) or
println( ).
It can also be obtained by a call to getMessage( ), which is defined by Throwable.
throws:
A throws clause lists the types of exceptions that a method might throw. This is necessary
for all exceptions, except those of type Error or RuntimeException, or any of their
subclasses.
All other exceptions that a method can throw must be declared in the throws clause. If
they are not, a compile-time error will result.
General form of a method declaration that includes a throws clause:
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
First, you need to declare that throwOne( ) throws IllegalAccessException. Second, main( )
must define a try / catch statement that catches this exception.
18. Output:
inside throwOne
caught java.lang.IllegalAccessException: demo
finally:
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path
that alters the normal flow through the method.
Depending upon how the method is coded, it is even possible for an exception to cause the
method to return prematurely.
This could be a problem in some methods. For example, if a method opens a file upon entry
and closes it upon exit, then you will not want the code that closes the file to be bypassed by
the exceptionhandling mechanism.
The finally keyword is designed to address this contingency.
finally creates a block of code that will be executed after a try /catch block has completed
and before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown. If an exception is
thrown, the finally block will execute even if no catch statement matches the exception.
Any time a method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed just
before the method returns.
The finally clause is optional. However, each try statement requires at least one catch or a
finally clause.
Here is an example program that shows three methods that exit in various ways, none
without executing their finally clauses:
class FinallyDemo
{ static void procA( ) {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
19. }
finally
{
System.out.println("procA's finally");
}
}
public static void main(String args[ ])
{ try {
procA( );
}
catch (Exception e)
{
System.out.println("Exception caught");
}
}
}
Output:
inside procA
procA's finally
Exception caught
In this example, procA( ) prematurely breaks out of the try by throwing an exception.
However, the finally block is still executed. If a finally block is associated with a try, the
finally block will be executed upon conclusion of the try.
Java’s Built-in Exceptions
Inside the standard package java.lang, Java defines several exception classes.
The most general of these exceptions are subclasses of the standard type RuntimeException.
These exceptions need not be included in any method’s throws list. In the language of Java,
these are called unchecked exceptions because the compiler does not check to see if a
method handles or throws these exceptions.
The unchecked exceptions defined in java.lang are listed in Table 10-1.
Table 10-2 lists those exceptions defined by java.lang that must be included in a method’s
throws list if that method can generate one of these exceptions and does not handle it itself.
These are called checked exceptions.
In addition to the exceptions in java. lang, Java defines several more that relate to its other
standard packages.
20. Table 10-1 Java’s Unchecked RuntimeException Subclasses Defined in java.lang
21. Creating Your Own Exception Subclasses
Although Java’s built-in exceptions handle most common errors, user will probably want to
create your own exception types to handle situations specific to your applications.
This is done by defining a subclass of Exception (which is, a subclass of Throwable).
The Exception class does not define any methods of its own. It does, inherit those methods
provided by Throwable.
Thus, all exceptions, including those that user create, have the methods defined by
Throwable available to them. They are shown in Table 10-3.
Exception defines four public constructors:Two support chained exceptions.The other two
are : Exception( ), Exception(String msg)
The first form creates an exception that has no description. The second form lets user
specify a description of the exception.
Sometimes it is override using toString( ): The version of toString( ) defined by Throwable
(and inherited by Exception) first displays the name of the exception followed by a colon,
which is then followed by description.
By overriding toString( ), you can prevent the exception name and colon from being
22. displayed. This makes for a cleaner output, which is desirable in some cases.
The following example declares a new subclass of Exception and then uses that subclass to
signal an error condition in a method. It overrides the toString( ) method, allowing a
carefully tailored description of the exception to be displayed.
Output:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
This example defines a subclass of Exception called MyException. This subclass has only a
constructor plus an overridden toString( ) method that displays the value of the exception.
The ExceptionDemo class defines a method named compute( ) that throws a MyException
object. The exception is thrown when compute( )’s integer parameter is greater than 10.
The main( ) method sets up an exception handler for MyException, then calls compute( )
with a legal value (less than 10) and an illegal one to show both paths through the code.
Here is the result:
Chained Exceptions
The chained exception feature allows user to associate another exception with an exception.
This second exception describes the cause of the first exception.
For example, imagine a situation in which a method throws an ArithmeticException because
of an attempt to divide by zero. However, the actual cause of the problem was that an I/O
error occurred, which caused the divisor to be set improperly.
23. Although the method must certainly throw an ArithmeticException, since that is the error
that occurred, you might also want to let the calling code know that the underlying cause
was an I/O error.
Chained exceptions let you handle this, and any other situation in which layers of
exceptions exist.
To allow chained exceptions, two constructors and two methods were added to Throwable.
The constructors are shown here:
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)
In the first form, causeExc is the exception that causes the current exception. That is,
causeExc is the underlying reason that an exception occurred.
The second form allows you to specify a description at the same time that you specify a
cause exception.
These two constructors have also been added to the Error, Exception, and
RuntimeException classes.
The chained exception methods supported by Throwable are getCause( ) and initCause(
). These methods are shown in Table 10-3.
Throwable getCause( )
Throwable initCause(Throwable causeExc)
The getCause( ) method returns the exception that underlies the current exception. If there is
no underlying exception, null is returned. The initCause( ) method associates causeExc with
the invoking exception and returns a reference to the exception.
Thus, you can associate a cause with an exception after the exception has been created.
However, the cause exception can be set only once.
This means user can call initCause( ) only once for each exception object.
initCause( ) is used to set a cause for legacy exception classes that don’t support the two
additional constructors.
Here is an example that illustrates the mechanics of handling chained exceptions:
class ChainExcDemo
{
Static void demoproc( ){
NullPointerException ex = new NullPointerException ("top layer");
ex.initCause (new ArithmeticException("cause"));
throw ex;
public static void main(String args[])
{
try{
24. demoproc( );
}
catch (NullPointerException ex)
{
System.out.println("Caught: " + ex);
System.out.println("Original cause: e.getCause());
}
}
}
Output:
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
In this example, the top-level exception is NullPointerException. To it is added a cause
exception, ArithmeticException.
When the exception is thrown out of demoproc( ), it is caught by main( ).
There, the top-level exception is displayed, followed by the underlying exception, which is
obtained by calling getCause( ).
Chained exceptions can be carried on to whatever depth is necessary. Thus, the cause
exception can, itself, have a cause.