Unit 4
Unit 4
Unit 4
Packages
Introduction to Packages
One of the main features of the Object Oriented Programming language is the ability to reuse the code that is
already created. One way for achieving this is by extending the classes and implementing the interfaces. Java
provides a mechanism to partition the classes into smaller chunks. This mechanism is the Package. The Package
is container of classes. The class is the container of the data and code. The package also addresses the problem
of name space collision that occurs when we use same name for multiple classes. Java provides convenient way
to keep the same name for classes as long as their subdirectories are different.
Benefits of packages:
Creating a Package
While creating a package, you should choose a name for the package and include a package statement along
with that name at the top of every source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement in
each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed
in the current default package.
To compile the Java programs with package statements, you have to use -d option as shown below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the compiled class files
will be placed in that folder.
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
UNIT-4
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current
package.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
If you use fully qualified name then only declared class of this package will be accessible. Now there is no
need to import. But you need to use fully qualified name every time when you are accessing the class or
interface.
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date
class.
Write a JAVA program that import and use the defined your package in the previous Problem .
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We
can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package through
child class. If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
1) Private
The private access modifier is accessible only within the class.
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
UNIT-4
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by A.java
UNIT-4
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Categories of Packages
The Java Packages are categorized into two categories (i) Java API Packages (ii) User
Defined Packages.
Java API Packages –Java API provides large number of classes grouped into different
packages according to the functionality. Most of the time we use the package available with
Java API.
java
Java.lang Package
The java.lang package includes the following classes.
Packages are organized in hierarchical structure, that means a package can contain another
package, which in turn contains several classes for performing different tasks. There are two
ways to access the classes of the packages.
fully qualified class name- this is done specifying package name containing the class and
appending the class to it with dot (.) operator.
Example: java.util.StringTokenizer(); Here, "java.util" is the package and
"StringTokenizer()" is the class in that package. This is used when we want to refer to only
one class in a package.
import statement –this is used when we want to use a class or many classes in many places in
our program. Example: (1) import java.util.*;
(2) import java.util.StringTokenizer;
Naming Conventions
Packages can be named using the Java Standard naming rules. Packages begin with "lower
case" letters. It is easy for the user to distinguish it from the class names. All the class Name
by convention begin with "upper case" letters. Example:
double d= java.lang.Math.sqrt(3);
Here, "java.lang" is the package, and "Math" is the class name, and "sqrt()" is the method
name.
User Define Packages
To create a package is quite easy: simply include a package command in the first line of the
source file. A class specified in that file belongs to that package. The package statement
defines a name space in which classes are stored. If you omit the package statement, the class
names are put in the default package, which has no name.
The general form of the package statement will be as followed: package pkg;
Here, "pkg" is the package name. Example: package MyPackage;
Java Uses file system directories to store packages. For example, the " .class" files for any
classes you declare to be part of the "MyPackage" must be store in the "MyPackage"
directory. The directory name "MyPackage" is different from "mypackage".
Notes: 1. The case for the package name is significant.
The directory name must match with package name.
We can create hierarchy of packages. To do so, simply separate package name from the
above one with it by use of the dot (.) operator. The general form of multileveled package
statement is shown here: package pkg1.pkg2.pkg3;
UNIT-4
hashCode() : For every object, JVM generates a unique number which is hashcode. It returns
distinct integers for distinct objects. A common misconception about this method is that
hashCode() method returns the address of object, which is not correct. It convert the internal
address of object to an integer by using an algorithm. The hashCode() method
is native because in Java it is impossible to find address of an object, so it uses native
languages like C/C++ to find address of the object.
Use of hashCode() method : Returns a hash value that is used to search object in a
collection. JVM(Java Virtual Machine) uses hashcode method while saving objects into
hashing related data structures like HashSet, HashMap, Hashtable etc. The main advantage of
saving objects based on hash code is that searching becomes easy.
// Constructor
Student()
{
roll_no = last_roll;
last_roll++;
}
// Overriding hashCode()
UNIT-4
@Override
public int hashCode()
{
return roll_no;
}
// Driver code
public static void main(String args[])
{
Student s = new Student();
Output :
Student@64
Student@64
Note that 4*160 + 6*161 = 100
equals(Object obj) : Compares the given object to “this” object (the object on which the
method is called). It gives a generic way to compare objects for equality. It is recommended
to override equals(Object obj) method to get our own equality condition on Objects. For more
on override of equals(Object obj) method refer – Overriding equals method in Java
Note : It is generally necessary to override the hashCode() method whenever this method is
overridden, so as to maintain the general contract for the hashCode method, which states that
equal objects must have equal hash codes.
getClass() : Returns the class object of “this” object and used to get actual runtime class of
the object. It can also be used to get metadata of this class. The returned Class object is the
object that is locked by static synchronized methods of the represented class. As it is final so
we don’t override it.
Output:
Class of Object obj is : java.lang.String
Note :After loading a .class file, JVM will create an object of the type java.lang.Class in the
Heap area. We can use this class object to get Class level information. It is widely used
in Reflection
UNIT-4
finalize() method : This method is called just before an object is garbage collected. It is
called by the Garbage Collector on an object when garbage collector determines that there are
no more references to the object. We should override finalize() method to dispose system
resources, perform clean-up activities and minimize memory leaks. For example before
destroying Servlet objects web container, always called finalize method to perform clean-up
activities of the session.
Note :finalize method is called just once on an object even though that object is eligible for
garbage collection multiple times.
t = null;
System.out.println("end");
}
@Override
protected void finalize()
{
System.out.println("finalize method called");
}
}
Output:
366712642
finalize method called
end
clone() : It returns a new object that is exactly the same as this object. For clone() method
refer Clone()
Java Enums
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST), season (SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED,
YELLOW, BLUE, GREEN, WHITE, and BLACK) etc. According to the Java naming
conventions, we should have all constants in capital letters. So, we have enum constants in
UNIT-4
capital letters.
Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change). The Java enum constants are static and final implicitly. It is available since
JDK 1.5.
Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is
more powerful. Here, we can define an enum either inside the class or outside the class.
Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods in
Java enum.
Output:
WINTER
SPRING
SUMMER
FALL
UNIT-4
Unlike some of the StrictMath class numeric methods, all implementations of the equivalent
function of Math class can't define to return the bit-for-bit same results. This relaxation
permits implementation with better-performance where strict reproducibility is not required.
If the size is int or long and the results overflow the range of value, the methods addExact(),
subtractExact(), multiplyExact(), and toIntExact() throw an ArithmeticException.
For other arithmetic operations like increment, decrement, divide, absolute value, and
negation overflow occur only with a specific minimum or maximum value. It should be
checked against the maximum and minimum value as appropriate.
Example 1
public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28;
double y = 4;
// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));
Output:
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known
as autoboxing and vice-versa unboxing.
Change the value in Method: Java supports only call by value. So, if we pass a primitive
value, it will not change the original value. But, if we convert the primitive value in an object,
it will change the original value.
Serialization: We need to convert the objects into streams to perform the serialization. If we
have a primitive value, we can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
java.util package: The java.util package provides the utility classes to deal with objects.
Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:
long Long
float Float
double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.
333
UNIT-4
Formatter Class
The Formatter is a built-in class in java used for layout justification and
alignment, common formats for numeric, string, and date/time data, and
locale-specific output in java programming. The Formatter class is defined
as final class inside the java. util package.
Introduction
The java.util.Formatter class provides support for layout justification and
alignment, common formats for numeric, string, and date/time data, and locale-
specific output.Following are the important points about Formatter −
Formatters are not necessarily safe for multithreaded access.Thread safety is
optional and is the responsibility of users of methods in this class.
Class declaration
Following is the declaration for java.util.Formatter class −
public final class Formatter
extends Object
implements Closeable, Flushable
Class constructors
Sr.No. Constructor & Description
1
Formatter()
This constructor constructs a new formatter.
2
Formatter(Appendable a)
This constructor constructs a new formatter with the specified
destination.
3
Formatter(Appendable a, Locale l)
This constructor constructs a new formatter with the specified
destination and locale.
4 Formatter(File file)
UNIT-4
5
Formatter(File file, String csn)
This constructor constructs a new formatter with the specified file
and charset.
6
Formatter(File file, String csn, Locale l)
This constructor constructs a new formatter with the specified file,
charset, and locale.
7
Formatter(Locale l)
This constructor constructs a new formatter with the specified locale.
8 Formatter(OutputStream os)
This constructor constructs a new formatter with the specified output
stream.
11 Formatter(PrintStream ps)
This constructor constructs a new formatter with the specified print
stream.
12 Formatter(String fileName)
This constructor constructs a new formatter with the specified file
name.
UNIT-4
Methods
Methods Description
nextByte() Generates random bytes and puts them into a specified byte array.
nextDouble() Returns the next pseudorandom Double value between 0.0 and 1.0
from the random number generator's sequence
between 0.0 and 1.0 from this random number generator's sequence
nextGaussian() Returns the next pseudorandom Gaussian double value with mean 0.0
and standard deviation 1.0 from this random number generator's
sequence.
setSeed() Sets the seed of this random number generator using a single long
seed.
Example 1
1. import java.util.Random;
2. public class JavaRandomExample1 {
3. public static void main(String[] args) {
4. //create random object
5. Random random= new Random();
6. //returns unlimited stream of pseudorandom long values
7. System.out.println("Longs value : "+random.longs());
8. // Returns the next pseudorandom boolean value
9. boolean val = random.nextBoolean();
10. System.out.println("Random boolean value : "+val);
11. byte[] bytes = new byte[10];
12. //generates random bytes and put them in an array
13. random.nextBytes(bytes);
14. System.out.print("Random bytes = ( ");
15. for(int i = 0; i< bytes.length; i++)
16. {
UNIT-4
Output:
The java.time, java.util, java.sql and java.text packages contains classes for representing date
and time. Following classes are important for dealing with date in java.
java.time.LocalDate class
java.time.LocalTime class
java.time.LocalDateTime class
java.time.MonthDay class
java.time.OffsetTime class
java.time.OffsetDateTime class
java.time.Clock class
java.time.ZonedDateTime class
java.time.ZoneId class
java.time.ZoneOffset class
java.time.Year class
java.time.YearMonth class
java.time.Period class
java.time.Duration class
java.time.Instant class
java.time.DayOfWeek enum
java.time.Month enum
TemporalAdjuster Class
TemporalAdjuster is to do the date mathematics. For example to get the "Second Saturday of
the Month" or "Next Tuesday".
Create the following java program using any editor of your choice in say C:/> JAVA
Java8Tester.java
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester to see the result
C:\JAVA>java Java8Tester
See the result.
In this page, we will learn about Java exceptions, its type and the difference
between checked and unchecked exceptions.
In Java, an exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that
is why we use exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in your program and there occurs an exception at
statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not
be executed. If we perform exception handling, the rest of the statement will be
executed. That is why we use exception handling in Java.
UNIT-4
1. Checked Exception
2. Unchecked Exception
3. Error
UNIT-4
The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions e.g. IOException, SQLException etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
3) Error
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed by
finally block later.
finally The "finally" block is used to execute the important code of the program. It
is executed whether an exception is handled or not.
Output:
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
If an exception occurs at the particular statement of try block, the rest of the block
code will not execute. So, it is recommended not to keeping the code in try block
that will not throw an exception.
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw an exception
3. }finally{}
Example 1
Output:
Example 2
4. try
5. {
6. int data=50/0; //may throw exception
7. }
8. //handling the exception
9. catch(ArithmeticException e)
10. {
11. System.out.println(e);
12. }
13. System.out.println("rest of the code");
14. }
15.
16. }
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 3
In this example, we also kept the code in a try block that will not throw an
exception.
17. }
Output:
java.lang.ArithmeticException: / by zero
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
o Prints the stack trace (Hierarchy of methods where the exception occurred).
Points to remember
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e.
catch for ArithmeticException must come before catch for Exception.
Example 1
Let's see a simple example of java multi-catch block.
20. }
21. System.out.println("rest of the code");
22. }
23. }
Output:
Example 2
Output:
Example 3
In this example, try block contains two exceptions. But at a time only one exception
occurs and its corresponding catch block is invoked.
Output:
Syntax:
1. ....
2. try
3. {
4. statement 1;
5. statement 2;
6. try
7. {
8. statement 1;
9. statement 2;
10. }
11. catch(Exception e)
12. {
13. }
14. }
15. catch(Exception e)
16. {
17. }
18. ....
UNIT-4
1. class Excep6{
2. public static void main(String args[]){
3. try{
4. try{
5. System.out.println("going to divide");
6. int b =39/0;
7. }catch(ArithmeticException e){System.out.println(e);}
8.
9. try{
10. int a[]=new int[5];
11. a[5]=4;
12. }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
13.
14. System.out.println("other statement);
15. }catch(Exception e){System.out.println("handeled");}
16.
17. System.out.println("normal flow..");
18. } }
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
12. Output:5
13. finally block is always executed
14. rest of the code...
UNIT-4
Case 2
Let's see the java finally example where exception occurs and not handled.
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Test it Now
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception. We will see custom
exceptions later.
1. throw exception;
Output:
An exception is first thrown from the top of the stack and if it is not caught, it drops down the call
stack to the previous method,If not caught there, the exception again drops down to the previous
method, and so on until they are caught or until they reach the very bottom of the call stack.This is
called exception propagation.
In the above example exception occurs in m() method where it is not handled,so it
is propagated to previous n() method where it is not handled, again it is propagated
to p() method where exception is handled.
Exception can be handled in any method in call stack either in main() method,p()
method,n() method or m() method.
Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as NullPointerException, it is programmers fault that
he is not performing check up before the code being used.
o error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
UNIT-4
Output:
exception handled
normal flow...
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
o In case you handle the exception, the code will be executed fine whether
exception occurs during the program or not.
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
UNIT-4
o A)In case you declare the exception, if exception does not occur, the code will
be executed fine.
o B)In case you declare the exception if exception occures, an exception will be
thrown at runtime because throws does not handle the exception.
1) Java throw keyword is used to explicitly throw Java throws keyword is used to declare an
an exception. exception.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException.
UNIT-4
1. import java.io.*;
2. class Parent{
3. void msg(){System.out.println("parent");}
4. }
5.
6. class TestExceptionChild1 extends Parent{
UNIT-4
1. import java.io.*;
2. class Parent{
3. void msg()throws ArithmeticException{System.out.println("parent");}
4. }
5.
6. class TestExceptionChild2 extends Parent{
7. void msg()throws Exception{System.out.println("child");}
8.
9. public static void main(String args[]){
10. Parent p=new TestExceptionChild2();
11. try{
12. p.msg();
13. }catch(Exception e){}
14. }
15. }
Test it Now
Output:Compile Time Error
UNIT-4
By the help of custom exception, you can have your own exception and message.
1. class TestCustomException1{
2.
3. static void validate(int age)throws InvalidAgeException{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. try{
12. validate(13);
13. }catch(Exception m){System.out.println("Exception occured: "+m);}
14.
15. System.out.println("rest of the code...");
16. }
17. }
Test it Now
Output:Exception occured: InvalidAgeException:not valid
rest of the code...