Java Unit-Ii Notes
Java Unit-Ii Notes
Java Unit-Ii Notes
PACKAGES
In java, a package is a container of classes, interfaces, and sub-packages. We may think of it as a folder in a
file directory.
We use the packages to avoid naming conflicts and to organize project-related classes, interfaces, and sub-
packages into a bundle.
Built-in Packages
User-defined Packages
Built-in Packages
The built-in packages are the packages from java API. The Java API is a library of pre-defined classes,
interfaces, and sub-packages. The built-in packages were included in the JDK.
There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax, swing, net, sql,
etc.
We need to import the built-in packages to use them in our program. To import a package, we use the import
statement.
User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their own packages.
DEFINIG A PACKAGE
We use the package keyword to create or define a package in java programming language.
Syntax
package packageName;
Example
package myPackage;
Now, save the above code in a file DefiningPackage.java, and compile it using the following command.
CLASSPATH
javac -d . DefiningPackage.java
The above command creates a directory with the package name myPackage, and the DefiningPackage.class
is saved into it.
java myPackage.DefiningPackage
When we use IDE like Eclipse, Netbeans, etc. the package structure is created automatically.
ACCESS PROTECTION
In java, the access modifiers define the accessibility of the class and its members. For example, private
members are accessible within the same class members only. Java has four access modifiers, and they are
default, private, protected, and public.
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The class acts as a
container of data and methods. So, the access modifier decides the accessibility of class members across the
different packages.
In java, the accessibility of the members of a class or interface depends on its access specifiers. The
following table provides information about the visibility of both data members and methods.
The public members can be accessed everywhere.
The private members can be accessed only inside the same class.
The protected members are accessible to every child class (same package or other packages).
The default members are accessible within the same package but not outside the package.
Example
class ParentClass{
int a = 10;
void showData() {
System.out.println("Inside ParentClass");
void accessData() {
System.out.println("Inside ChildClass");
}
}
obj.showData();
obj.accessData();
IMPORTING PACKAGES
In java, the import keyword used to import built-in and user-defined packages. When a package has
imported, we can refer to all the classes of that package using their name directly.
The import statement must be after the package statement, and before any other statement.
Using an import statement, we may import a specific class or all the classes from a package.
🔔 Using one import statement, we may import only one package or a class.
🔔 Using an import statement, we can not import a class directly, but it must be a part of a package.
Using an importing statement, we can import a specific class. The following syntax is employed to import a
specific class.
Syntax
import packageName.ClassName;
Example
package myPackage;
import java.util.Scanner;
int i = read.nextInt();
In the above code, the class ImportingExample belongs to myPackage package, and it also importing a class
called Scanner from java.util package.
Syntax
import packageName.*;
INTERFACE:
An interface is similar to a class, but it contains abstract methods and static final variables only. The interface
in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the interface has an
implementation, and all the variables in the interface are constants.
All the methods of an interface, implemented by the class that implements it.
The interface in java enables java to support multiple-inheritance. An interface may extend only one
interface, but a class may implement any number of interfaces.
🔔 Specifying the keyword abstract for interface methods is optional, it automatically added.
Defining an interface is similar to that of a class. We use the keyword interface to define an interface. All the
members of an interface are public by default. The following is the syntax for defining an interface.
Syntax
interface InterfaceName{
...
members declaration;
...
Example
interface HumanInterfaceExample {
void work();
In the above code defines an interface HumanInterfaceExample that contains two abstract methods learn(),
work() and one constant duration.
Every interface in Java is auto-completed by the compiler. For example, in the above example code, no
member is defined as public, but all are public automatically.
interface HumanInterfaceExample {
IMPLEMENTING AN INTERFACE
An interface is implemented by a class. The class that implements an interface must provide code for all the
methods defined in the interface, otherwise, it must be defined as an abstract class.
The class uses a keyword implements to implement an interface. A class can implement any number of
interfaces. When a class wants to implement more than one interface, we use the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class.
Syntax
...
boby-of-the-class
...
Example
interface Human {
void work();
System.out.println("Develop applications");
trainee.learn("coding");
trainee.work();
In the above code defines an interface Human that contains two abstract methods learn(), work() and one
constant duration. The class Programmer implements the interface. As it implementing the Human interface
it must provide the body of all the methods those defined in the Human interface.
When a class wants to implement more than one interface, we use the implements keyword is followed by a
comma-separated list of the interfaces implemented by the class.
Syntax
...
boby-of-the-class
...
Example
interface Human {
interface Recruitment {
return true;
return false;
System.out.println("Attend interview");
if(selected)
return true;
return false;
System.out.println("Develop applications");
}
}
trainee.learn("Coding");
trainee.screening(30);
trainee.interview(true);
trainee.work();
NESTED INTERFACES
An interface may be defined inside another interface, and also inside a class. The interface that defined inside
another interface or a class is known as nested interface. The nested interface is also refered as inner
interface.
🔔 The nested interface declared within a class can be with any access modifier.
The nested interface cannot be accessed directly. We can only access the nested interface by using outer
interface or outer class name followed by dot( . ), followed by the nested interface name.
The nested interface that defined inside another interface must be accessed as OuterInterface.InnerInterface.
Let's look at an example code to illustrate nested interfaces inside another interface.
Example
interface OuterInterface{
void outerMethod();
interface InnerInterface{
void innerMethod();
obj_1.outerMethod();
obj_2.innerMethod();
}
Nested interface inside a class
The nested interface that defined inside a class must be accessed as ClassName.InnerInterface.
Example
class OuterClass{
interface InnerInterface{
void innerMethod();
obj.innerMethod();
}
VARIABLES IN JAVA INTERFACES
An interface is a completely abstract class. An interface is a container of abstract methods and static final
variables. The interface contains the static final variables. The variables defined in an interface can not be
modified by the class that implements the interface, but it may use as it defined in the interface.
🔔 If any variable in an interface is defined without public, static, and final keywords then, the compiler
automatically adds the same.
🔔 The class that implements an interface can not modify the interface variable, but it may use as it defined in
the interface.
Example
interface SampleInterface{
EXTENDING AN INTERFACE
An interface can extend another interface. When an interface wants to extend another interface, it uses the
keyword extends. The interface that extends another interface has its own members and all the members
defined in its parent interface too. The class which implements a child interface needs to provide code for the
methods defined in both child and parent interfaces, otherwise, it needs to be defined as abstract class.
🔔 An interface can extend another interface.
🔔 The class that implements child interface needs to provide code for all the methods defined in both child
and parent interfaces.
Example
interface ParentInterface{
void parentMethod();
void childMethod();
obj.childMethod();
obj.parentMethod();
}
}
In java, the IO operations are performed using the concept of streams. Generally, a stream means a
continuous flow of data. In java, a stream is a logical container of data that allows us to read from and write
to it. A stream can be linked to a data source, or data destination, like a console, file or network connection
by java IO system. The stream-based IO operations are faster than normal IO operations.
The stream-based IO operations are performed using two separate streams input stream and output stream.
The input stream is used for input operations, and the output stream is used for output operations. The java
stream is composed of bytes.
Every program creates 3 streams automatically, and these streams are attached to the console.
The Java streams support many different kinds of data, including simple bytes, primitive data types, localized
characters, and objects.
Byte Stream
Character Stream
The following picture shows how streams are categorized, and various built-in classes used by the java IO
system.
Both character and byte streams essentially provides a convenient and efficient way to handle data streams in
Java.
BYTE STREAM
the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8 bits of data.
In Java 1.0 version all IO operations were byte oriented, there was no other stream (character stream).
Byte stream is defined by two abstract classes, InputStream and OutputStream. The InputStream class used
for byte stream based input operations, and the OutputStream class used for byte stream based output
operations.
The InputStream and OutputStream classes have several concreate classes to perform various IO operations
based on the byte stream.
The following picture shows the classes used for byte stream operations.
InputStream class
The InputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
We can use the BufferedInputStream class to read data from the console. The BufferedInputStream class use
a method read( ) to read a value from the console, or file, or socket.
import java.io.*;
try {
char c = (char)read.read();
catch(Exception e) {
System.out.println(e);
finally {
read.close();
import java.io.*;
try {
char c = (char)input.read();
catch(Exception e) {
System.out.println(e);
finally {
input.close();
We can use the BufferedOutputStream class to write data into the console, file, socket. The
BufferedOutputStream class use a method write( ) to write data.
import java.io.*;
try {
out.write(data.getBytes());
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
CHARACTER STREAM
When the IO stream manages 16-bit Unicode characters, it is called a character stream. The unicode set is
basically a type of character set where each character corresponds to a specific numeric value within the
given character set, and every programming language has a character set.
In java, the character stream is a 16 bits carrier. The character stream in java allows us to transmit 16 bits of
data.
The character stream was introduced in Java 1.1 version. The charater stream
The java character stream is defined by two abstract classes, Reader and Writer. The Reader class used for
character stream based input operations, and the Writer class used for charater stream based output
operations.
The Reader and Writer classes have several concreate classes to perform various IO operations based on the
character stream.
The following picture shows the classes used for character stream operations.
Reader class
The Reader class has defined as an abstract class, and it has the following methods which have implemented
by its concrete classes.
Writer class
The Writer class has defined as an abstract class, and it has the following methods which have implemented
by its concrete classes.
Reading data using BufferedReader
We can use the BufferedReader class to read data from the console. The BufferedInputStream class needs
InputStreamReaderclass. The BufferedReader use a method read( ) to read a value from the console, or file,
or socket.
import java.io.*;
name = in.readLine();
}
Example 2 - Reading from a file
import java.io.*;
try {
char c = (char)input.read();
catch(Exception e) {
System.out.println(e);
finally {
input.close();
We can use the FileWriter class to write data into the file. The FileWriter class use a method write( ) to write
data.
import java.io.*;
out.write(msg);
System.out.println("Writing done!!!");
catch(Exception e) {
System.out.println(e);
finally {
out.close();
CONSOLE IO OPERATIONS
Reading input data using the BufferedReader class is the traditional technique. This way of the reading
method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is
wrapped in a BufferedReader, we can read input from the console.
Example
import java.io.*;
try {
name = in.readLine();
catch(Exception e) {
System.out.println(e);
finally {
in.close();
Reading input data using the Scanner class is the most commonly used method. This way of the reading
method is used by wrapping the System.in (standard input stream) which is wrapped in a Scanner, we can
read input from the console.
import java.util.Scanner;
name = in.next();
Example
import java.io.*;
String name;
if(con != null) {
else {
In java, there are two methods to write console output. Using the 2 following methods, we can write output
data to the console.
The PrintStream is a bult-in class that provides two methods print() and println() to write console output. The
print() and println() methods are the most widely used methods for console output.
Both print() and println() methods are used with System.out stream.
The print() method writes console output in the same line. This method can be used with console output only.
The println() method writes console output in a separete line (new line). This method can be used with
console ans also with other output sources.
Example
list[i] = i*10;
for(int i:list)
for(int i:list)
Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to the console, it
also accept escape sequences.
Example
list[i] = i + 65;
for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
FILE CLASS
The File is a built-in class in Java. In java, the File class has been defined in the java.io package. The File
class represents a reference to a file or directory. The File class has various methods to perform operations
like creating a file or directory, reading from a file, updating file content, and deleting a file or directory.
import java.io.*;
//f.createNewFile()
//f.delete();
//f.setReadOnly()
The following java code to list all the files in a directory including the files present in all its subdirectories.
Example
import java.util.Scanner;
import java.io.*;
if (!f_ref.exists()) {
printLine();
printLine();
} else {
String ch = "y";
while (ch.equalsIgnoreCase("y")) {
printFiles(path);
ch = read.next().toLowerCase();
if (ch.equalsIgnoreCase("y")) {
System.out.print("Enter the sub-directory name: ");
if (!f_ref_2.exists()) {
printLine();
printLine();
if (file.isFile())
else
}
public static void printLine() {
System.out.println("----------------------------------------");
There multiple ways to read data from a file and to write data to a file. The most commonly used ways are as
follows.
In java, we can use a byte stream to handle files. The byte stream has the following built-in classes to
perform various operations on a file.
FileInputStream - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the byte stream. The FileInputStream class provides a method read() to
read data from a file byte by byte.
FileOutputStream - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the byte stream. The FileOutputStream class provides a method write()
to write data to a file byte by byte.
Example
import java.io.*;
FileInputStream in = null;
try {
in = new FileInputStream("C:\\Raja\\Input-File.txt");
int c;
out.write(c);
}
catch(Exception e){
System.out.println(e);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
FileReader - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the character stream. The FileReader class provides a method read() to
read data from a file character by character.
FileWriter - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the character stream. The FileWriter class provides a method write() to
write data to a file character by character.
Example
import java.io.*;
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("C:\\Raja\\Input-File.txt");
int c;
out.write(c);
catch(Exception e) {
System.out.println(e);
finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
}
RANDOM ACCESS FILE
The java.io package has a built-in class RandomAccessFile that enables a file to be accessed randomly. The
RandomAccessFile class has several methods used to move the cursor position in a file.
A random access file behaves like a large array of bytes stored in a file.
The Random Access File class in java has the following constructors.
Access Modes
r - Creates the file with read mode; Calling write methods will result in an IOException.
rw - Creates the file with read and write mode.
rwd - Creates the file with read and write mode - synchronously. All updates to file content is
written to the disk synchronously.
rws - Creates the file with read and write mode - synchronously. All updates to file content or
meta data is written to the disk synchronously.
The Random Access File class in java has the following methods.
Example
import java.io.*;
{
try
double d = 1.5;
float f = 14.56f;
// Writing to file
f_ref.seek(0);
// read() method :
f_ref.seek(0);
// readBoolean() method :
// readByte() method :
f_ref.writeChar('c');
f_ref.seek(0);
// readChar() :
f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);
// read double
f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);
// readFloat() :
f_ref.seek(0);
// readFully() :
f_ref.readFully(arr);
f_ref.seek(0);
f_ref.readFully(arr, 0, 8);
ex.printStackTrace();
}
}
CONSOLE CLASS
The java.io package has a built-in class Console used to read from and write to the console, if one exists.
This class was added to the Java SE 6. The Console class implements teh Flushable interface.
In java, most the input functionalities of Console class available through System.in, and the output
functionalities available through System.out.
The Console class does not have any constructor. We can obtain the Console class object by calling
System.console().
Example
import java.io.*;
String name;
if(con != null) {
else {
}
The following example program for writing to the console using Console class.
Example
import java.io.*;
list[i] = i + 65;
for(int i:list) {
System.out.write(i);
System.out.write('\n');
Using serialization and deserialization, we can transfer the Object Code from one Java Virtual machine to
another.
Serialization
The Serialization is achieved with the help of interface Serializable. The class whose object needs to be
serialized must implement the Serializable interface.
We use the ObjectOutputStream class to write a serialized object to write to a destination. The
ObjectOutputStream class provides a method writeObject() to serializing an object.
Step 1 - Define the class whose object needs to be serialized; it must implement Serializable
interface.
Step 2 - Create a file reference with file path using FileOutputStream class.
Step 3 - Create reference to ObjectOutputStream object with file reference.
Step 4 - Use writeObject(object) method by passing the object that wants to be serialized.
Step 5 - Close the FileOutputStream and ObjectOutputStream.
Example
import java.io.*;
stud.studName = "Rama";
stud.studBranch = "IT";
try {
oos.writeObject(stud);
oos.close();
fos.close();
catch(Exception e) {
System.out.println(e);
}
Deserialization
The Deserialization is achieved with the help of class ObjectInputStream. This class provides a method
readObject() to deserializing an object.
Step 1 - Create a file reference with file path in which serialized object is available using
FileInputStream class.
Step 2 - Create reference to ObjectInputStream object with file reference.
Step 3 - Use readObject() method to access serialized object, and typecaste it to destination
type.
Step 4 - Close the FileInputStream and ObjectInputStream.
Example
import java.io.*;
try {
fis.close();
ois.close();
catch(Exception e) {
System.out.println(e);
}
ENUMERATION
In java, an Enumeration is a list of named constants. The enum concept was introduced in Java SE 5 version.
The enum in Java programming the concept of enumeration is greatly expanded with lot more new features
compared to the other languages like C, and C++.
In java, the enumeration concept was defined based on the class concept. When we create an enum in java, it
converts into a class type. This concept enables the java enum to have constructors, methods, and instance
variables.
All the constants of an enum are public, static, and final. As they are static, we can access directly using
enum name.
The main objective of enum is to define our own data types in Java, and they are said to be enumeration data
types.
To create enum in Java, we use the keyword enum. The syntax for creating enum is similar to that of class.
In java, an enum can be defined outside a class, inside a class, but not inside a method.
Example
enum WeekDay{
for(WeekDay d:WeekDay.values())
System.out.println(d);
}
🔔 Every enum is converted to a class that extends the built-in class Enum.
🔔 As an enum represents a class, it can have methods, constructors. It also gets a few extra methods from the
Enum class, and one of them is the values() method.
Constructors enum
In a java programming language, an enum can have both the type of constructors default and parameterized.
The execution of constructor depends on the constants we defined in the enum. For every constant in an
enum, the constructor is executed.
If an enum has a parameterized constructor, the parameter value should be passed when we define constant.
Example
enum WeekDay{
String msg;
WeekDay(){
System.out.println("Default constructor!");
WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
n the above example, the constant SUNDAY is created by calling the parameterized constructor, other
constants created by calling default constructor.
Methods enum
In a java programming language, an enum can have methods. These methods are similar to the methods of a
class. All the methods defined in an enum can be used with all the constants defined by the same enum.
Example
enum WeekDay{
String msg;
WeekDay(){
System.out.println("Default constructor!");
}
WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
void printMessage() {
day.printMessage();
All the primitive data types have defined using the class concept, these classes known as wrapper classes. In
java, every primitive type has its corresponding wrapper class.
All the wrapper classes in Java were defined in the java.lang package.
The following table shows the primitive type and its corresponding wrapper class.
The Java 1.5 version introduced a concept that converts primitive type to corresponding wrapper type and
reverses of it.
Autoboxing
The process of converting a primitive type value into its corresponding wrapper class object is called
autoboxing or simply boxing. For example, converting an int value to an Integer class object.
The compiler automatically performs the autoboxing when a primitive type value has assigned to an object of
the corresponding wrapper class.
We can also perform autoboxing manually using the method valueOf( ), which is provided by every wrapper
class.
Example - Autoboxing
import java.lang.*;
Integer i = num;
Integer j = Integer.valueOf(num);
Auto un-boxing
The process of converting an object of a wrapper class type to a primitive type value is called auto un-boxing
or simply unboxing. For example, converting an Integer object to an int value.
The compiler automatically performs the auto un-boxing when a wrapper class object has assigned to
aprimitive type.
We can also perform auto un-boxing manually using the method intValue( ), which is provided by Integer
wrapper class. Similarly every wrapper class has a method for auto un-boxing.
import java.lang.*;
int i = num;
int j = num.intValue();
}
GENERICS
The java generics is a language feature that allows creating methods and class which can handle any type of
data values. The generic programming is a way to write generalized programs, java supports it by java
generics.
The java generics is similar to the templates in the C++ programming language.
🔔 The java generics allows only non-primitive type, it does not support primitive types like int, float, char,
etc.
The java generics feature was introduced in Java 1.5 version. In java, generics used angular brackets “< >”.
In java, the generics feature implemented using the following.
Generic Method
Generic Classes
Generic methods
Generics allows creating generic methods which can work with a different type of data values.
Using a generic method, we can create a single method that can be called with arguments of different types.
Based on the types of the arguments passed to the generic method, the compiler handles each method call
appropriately.
obj.displayData(45.6f, 10);
obj.displayData(10, 10);
obj.displayData("Hi", 'c');
}
In the above example code, the method displayData( ) is a generic method that allows a different type of
parameter values for every function call.
Generic Class
A class can be defined as a generic class that allows creating a class that can work with different types.
A generic class declaration looks like a non-generic class declaration, except that the class name is followed
by a type parameter section.
T obj;
this.obj = anotherObj;
public T getData() {
return this.obj;
System.out.println(actualObj1.getData());
System.out.println(actualObj2.getData());
System.out.println(actualObj3.getData());