Java Unit-II Notes
Java Unit-II Notes
PACKAGES IN JAVA
A package is a collection of similar types of classes, interfaces and sub-packages.
Types of packages
Package are classified into two type which are given below.
1. Predefined or built-in package
2. User defined package
1. Predefined or built-in package
These are the packages which are already designed by the Sun Microsystem and supply as a part of
java API, every predefined package is collection of predefined classes, interfaces and sub-package.
Following are the list of predefined packages in java
java.lang − This package provides the language basics.
java.util − This packages provides classes and interfaces (API’s) related to collection frame work,
events, data structure and other utility classes such as date.
java.io − This packages provides classes and interfaces for file operations, and other input and
output operations.
java.awt − This packages provides classes and interfaces to create GUI components in Java.
java.time − The main API for dates, times, instants, and durations.
2. User defined package
If any package is design by the user is known as user defined package.
User defined package are those which are developed by java programmer and supply as a part of
their project to deal with common requirement.
DEFINING A PACKAGE
Rules to create user defined package
Package statement should be the first statement of any package program.
Choose an appropriate class name or interface name and whose modifier must be public.
Any package program can contain only one public class or only one public interface but it can
contain any number of normal classes.
Package program should not contain any main() method.
Modifier of constructor of the class which is present in the package must be public. (This is not
applicable in case of interface because interface have no constructor.)
The modifier of method of class or interface which is present in the package must be public (This
rule is optional in case of interface because interface methods by default public)
Every package program should be save either with public class name or public Interface name
If you omit the package statement, the class names are put into the default package, which has no
name.
Syntax
package packagename;
Example
package mypack;
Compile package programs
For compilation of package program first we save program with public className.java and it
compile using below syntax:
Syntax
javac -d . className.java
Explanation
In above syntax "-d" is a specific tool which tells to java compiler create a separate folder for the
given package in given path.
When we give specific path then it create a new folder at that location and when we use . (dot)
then it crate a folder at current working directory.
Note: Any package program can be compile but can not be execute or run. These program can be
executed through user defined program which are importing package program.
Example of Package Program
Package program which is save with A.java and compile by javac -d . A.java.
package mypack;
public class A
{
public void show()
{
System.out.println("Sum method");
}
}
IMPORTING PACKAGES
To import the java package into a class, we need to use the java import keyword which is used to access
the package and its classes into the java program.
Use import to access built-in and user-defined packages into your java source file to refer to a
class in another package by directly using its name.
syntax:
import package.name.ClassName; // To import a certain class only
import package.name.* // To import the whole package
Example:
import java.util.Date; // imports only Date class
import java.io.*; // imports everything inside java.io package
Example
import mypack.A;
public class Hello
{
public static void main(String args[])
{
A a=new A();
a.show();
System.out.println("show() class A");
}
}
CLASSPATH
CLASSPATH can be set by any of the following ways:
CLASSPATH can be set permanently in the environment:
In Windows, choose control panel
System
Advanced
Environment Variables
choose “System Variables” (for all the users) or “User Variables” (only the currently login user)
choose “Edit” (if CLASSPATH already exists) or “New”
Enter “CLASSPATH” as the variable name
Enter the required directories and JAR files (separated by semicolons) as the value (e.g.,
“.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”).
Take note that you need to include the current working directory (denoted by ‘.’) in the
CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
> SET CLASSPATH
CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
Instead of using the CLASSPATH environment variable, you can also use the command-line
option -classpath or -cp of the javac and java commands, for example,
> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
ACCESS PROTECTION
In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used
with the element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
When no access modifier is specified for a class, method, or data member – It is said to be having
the default access modifier 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.
Example
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");
}
}
//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.
2. private
The private access modifier is accessible only within the class.
The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in
which they are declared.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces can not be declared as private because private means “only
visible within the enclosing class”.
Example
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");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
3. protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier is specified using the keyword protected.
Example
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();
}
}
4. public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
The public access modifier is specified using the keyword public.
Example
//save by A.java
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();
}
}
Table: class member access
Let's understand the access modifiers in Java by a simple table.
Private YES NO NO NO
In class, you can instantiate variables and In an interface, you can’t instantiate
1.
create an object. variables and create an object.
The access specifiers used with classes are In Interface only one specifier is used-
3.
private, protected, and public. Public.
There properties can be reused commonly in a There properties commonly usable in any
specific application. application of java environment.
The default access specifier of abstract class There default access specifier of interface method
methods are default. are public.
These class properties can be reused in other These properties can be reused in any other class
class using extend keyword. using implements keyword.
Inside abstract class we can take constructor. Inside interface we can not take any constructor.
For the abstract class there is no restriction For the interface it should be compulsory to
like initialization of variable at the time of initialization of variable at the time of variable
variable declaration. declaration.
There are no any restriction for abstract class For the interface variable can not declare variable
variable. as private, protected, transient, volatile.
Example
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A obj = new A();
obj.print();
obj.show();
}
}
STREAM BASED I/O (JAVA.IO)
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
STREAM
In Java, streams are the sequence of data that are read from the source and written to the
destination.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1. System.in: This is the standard input stream that is used to read characters from the keyboard
or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a program
on an output device like the computer screen.
3. System.err: This is the standard error stream that is used to output all the error data that a
program might throw, on a computer screen or any standard output device.
TYPES OF STREAMS
Depending on the type of operations, streams can be divided into two primary classes:
InPutStream − The InputStream is used to read data from a source.
2. Character Stream
1. BYTE STREAM
Java byte streams are used to perform input and output of 8-bit bytes.
Byte Stream Classes
All byte stream classes are derived from base abstract classes called InputStream
and OutputStream.
InputStream Class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream
of bytes.
Subclasses of InputStream
In order to use the functionality of InputStream, we can use its subclasses. Some of them are:
Stream class Description
Constructor Description
RandomAccessFile(File Creates a random access file stream to read from, and optionally
file, String mode) to write to, the file specified by the File argument.
RandomAccessFile(String Creates a random access file stream to read from, and optionally
name, String mode) to write to, a file with the specified name.
Methods
void close() It closes this random access file stream and releases any
system resources associated with the stream.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
Example
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample
{
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args)
{
try
{
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
SERIALIZATION
In java, the Serialization is the process of converting an object into a byte stream so that it can
be stored on to a file, or memory, or a database for future access.
The reverse operation of serialization is called deserialization where byte-stream is converted
into an object.
Using serialization and deserialization, we can transfer the Object Code from one Java Virtual
machine to another.
For serializing the object, we call the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
Let's see the example given below:
import java.io.Serializable;
public class Student implements Serializable
{
int id;
String name;
public Student(int id, String name)
{
this.id = id;
this.name = name;
}
}
In the above example, Student class implements Serializable interface. Now its objects can be
converted into stream.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.
Constructor
Method Description
1) public final void writeObject(Object obj) writes the specified object to the
throws IOException {} ObjectOutputStream.
2) public void flush() throws IOException {} flushes the current output stream.
3) public void close() throws IOException {} closes the current output stream.
Example of Java Serialization
In this example, we are going to serialize the object of Student class.
The writeObject() method of ObjectOutputStream class provides the functionality to serialize the
object.
We are saving the state of the object in the file named f.txt.
import java.io.*;
class Persist
{
public static void main(String args[])
{
try
{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}
catch(Exception e)
{
System.out.println(e);}
}
}
ENUMERATION
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 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.
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.
Points to remember for Java Enum
Enum improves type safety
Enum can be easily used in switch
Enum can be traversed
Enum can have fields, constructors and methods
Enum may implement many interfaces but cannot extend any class because it internally
extends Enum class
Simple Example of Java Enum
class EnumExample1
{
public enum Season { WINTER, SPRING, SUMMER, FALL}
public static void main(String[] args)
{
for (Season s : Season.values())
System.out.println(s);
}
}
AUTOBOXING
The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing.
(OR)
Converting a primitive value into an object of the corresponding wrapper class is called
autoboxing.
For example, converting int to Integer class.
No need of conversion between primitives and Wrappers manually so less coding is required.
The following table lists the primitive types and their corresponding wrapper classes, which
are used by the Java compiler for autoboxing: