UNIT-4 Notes
UNIT-4 Notes
Packages:
A package is simply a namespace under which you can categorize classes, analogous to a
"folder" or "path", so you can group classes with related purpose or functionality.
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
● Preventing naming conflicts. For example there can be two classes with name Employee in
two packages, college.staff.cse.Employee and college.staff.ee.Employee
● Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
● Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.
● Packages can be considered as data encapsulation (or data-hiding).
import java.util.*;
util is a subpackage created inside java package.
Built-in Packages
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:
1. java.lang: Contains language support classes(e.g classes which defines primitive data types,
math operations). This package is automatically imported.
2. java.io: Contains classes for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4. java.applet: Contains classes for creating Applets.
5. java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc). 6)
6. java.net: Contain classes for supporting networking operations.
User-defined packages: These are the packages that are defined by the user. 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.
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
obj.getNames(name);
}
}
User-Defined Packages
User-defined packages are those packages that are designed or created by the developer to
categorize classes and packages. They are much similar to the built-in that java offers. It can be
imported into other classes and used the same as we use built-in packages.
Syntax:
package package-name;
Step 1: Creating a package in java class. The format is very simple and easy. Just write a
package by following its name.
package example1;
Step 2: Include class in java package, But remember that class only has one package
declaration.
package example1;
class gfg {
public static void main(Strings[] args){
-------function--------
}
}
Step 3: Now the user-defined package is successfully created, we can import it into other
packages and use its functions it.
package example;
// Class
public class University {
// declaring method m1
public void m1() { System.out.println("GFG"); }
}
Package (Default) Access Modifier:
A class or method or variable declare without any access modifier then is considered that it has a
package(default)access modifier The default modifier act as public within the same package and
acts as private outside the package. If a class is declared as default then we can access that class
only within the current package i.e from the outside package we can’t access it. Hence, the
default access modifier is also known as the package–level access modifier. A similar rule also
applies for variables and methods in java.
import java.io.*;
import java.util.*;
class Package {
String s = "VTU";
String s1 = "KARNATAKA";
String fullName()
{
return s + s1;
}
Public members can be accessed from a This modifier can’t be accessed from a non-child
non-child class of outside package. class of the outside package.
Public members can be accessed from child We cannot access this modifier from the child
class of outside package. class of the outside package.
The public modifier is more accessible than This modifier is more restricted than the public
the package access modifier. access modifier.
import java.io.*;
import java.util.*;
// main method
public static void main(String[] args)
{
// creating an object of parent class
// using parent reference
A a = new A();
// calling method m1
b.m1();
// calling m1 method
a1.m1();
}
}
// helper method
private void m1() { System.out.println("VTU"); }
}
// driver class
class B {
// main method
public static void main(String[] args)
{
// creating an object of type class A
A a = new A();
Package import is a feature in java which allows us to reuse the classes available in a package.
Java provides import keyword to import classes of another package inside your class. Once a
class is imported, you can use the imported class anywhere in your class.
Package import basically makes availability of classes of that package in your class, so that you
can use the functionalities of that classes. To access a class of another package, first you need to
import that class or package in your class.
Example
import mypack.*;
import mypack.MyFirstPackageProgram;
import java.util.*;
How to import packages in Java?
Java has an import statement that allows you to import an entire package (as in earlier
examples), or use only certain classes and interfaces defined in the package.
The general form of import statement is:
import package.name.ClassName; // To import a certain class only
For example,
// body
}
The same task can be done using the fully qualified name as follows:
//body
Now, you can import Helper class from com.programiz package to your implementation class.
Once you import it, the class can be referred directly by its name. Here's how:
import com.programiz.Helper;
class UseHelper {
Output:
formattedValue = $99.50
Exceptions:
Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Error and Exception
Error: An Error indicates a serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
import java.io.*;
class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
return (a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}
OUTPUT:
/ by zero
Exception-Handling Fundamentals:
They form an interrelated subsystem in which the use of one implies the use of another.
Try: The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
Catch: The catch block is used to handle the uncertain condition of a try block. A try block is
always followed by a catch block, which handles the exception that occurs in the associated try
block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
Throw: The throw keyword is used to transfer control from the try block to the catch block.
class ThrowExcep {
static void help()
{
try {
throw new NullPointerException("error_unknown");
}
catch (NullPointerException e) {
System.out.println("Caught inside help().");
// rethrowing the exception
throw e;
}
}
Throws: The throws keyword is used for exception handling without try & catch block. It
specifies the exceptions that a method can throw to the caller and does not handle itself.
Finally: It is executed after the catch block. We use it to put some common code (to be executed
irrespective of whether an exception has occurred or not ) when there are multiple catch blocks.
class Division {
public static void main(String[] args)
{
int a = 10, b = 5, c = 5, result;
try {
result = a / (b - c);
System.out.println("result" + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught:Division by zero");
}
finally {
System.out.println("I am in final block");
}
}
}
Exception Types:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to
explain certain error situations. Below is the list of important built-in exceptions in Java.
1. ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic
operation.
2. ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or equal to the size of the array.
3. ClassNotFoundException: This Exception is raised when we try to access a class whose definition is
not found
4. FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
5. IOException: It is thrown when an input-output operation failed or interrupted
6. InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some processing, and
it is interrupted.
7. NoSuchFieldException: It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException: It is thrown when accessing a method that is not found.
9. NullPointerException: This exception is raised when referring to the members of a null object. Null
represents nothing
10. NumberFormatException: This exception is raised when a method could not convert a string into a
numeric format.
11. RuntimeException: This represents an exception that occurs during runtime.
12. StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an index is
either negative or greater than the size of the string
13. IllegalArgumentException : This exception will throw the error or error statement when the method
receives an argument which is not accurately fit to the given relation or condition. It comes under the
unchecked exception.
14. IllegalStateException : This exception will throw an error or error message when the method is not
accessed for the particular operation in the application. It comes under the unchecked exception.
Arithmetic exception:
Output:
NullPointer Exception:
class NullPointer_Demo
try {
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
Output: NullPointerException..
Uncaught Exceptions:
try {
// Inner try block
System.out.println("Inner try block started");
int num = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch block: Cannot divide by zero!");
}
Output:
An exception is an issue (run time error) that occurred during the execution of a program. When
an exception occurred the program gets terminated abruptly and, the code past the line that
generated the exception never gets executed.
Java provides us the facility to create our own exceptions which are basically derived classes of
Exception. Creating our own Exception is known as a custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the exception according to
user needs. In simple words, we can say that a User-Defined Exception or custom exception is
creating your own exception class and throwing that exception using the ‘throw’ keyword.
// A Class that represents use-defined exception
Chained Exceptions allows to relate one exception with another exception, i.e one exception
describes cause of another exception. For example, consider a situation in which a method
throws an ArithmeticException because of an attempt to divide by zero but the actual cause of
exception was an I/O error which caused the divisor to be zero. The method will throw only
ArithmeticException to the caller. So the caller would not come to know about the actual cause
of exception. Chained Exception is used in such type of situations.
// Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
// Creating an exception
NumberFormatException ex =
new NumberFormatException("Exception");
catch(NumberFormatException ex)
{
// displaying the exception
System.out.println(ex);
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception