Java Unit II
Java Unit II
Java Unit II
INTRODUCTION TO PACKAGES
Thus, package is a container of a group of related classes where some of the classes are accessible and are
exposed and others are kept for internal purpose. We can reuse existing classes from the packages as
many time as we need it in our program. Package names and directory structure are closely related. For
example if a package name is college.staff.csc, then there are three directories, college, staff and csc such
that csc is present in staff and staff is present college.
Re-usability: The classes contained in the packages of another program can be easily reused
Name Conflicts: Packages help us to uniquely identify a class, for example, we can have two classes
with the name Employee in two different packages, company.sales.Employee and
company.marketing.Employee.
Controlled Access:Offers access protection such as protected classes, default classes and private class.
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.
Data Encapsulation: They provide a way to hide classes, preventing other programs from accessing
classes that are meant for internal use only
Maintenance: With packages, you can organize your project better and easily locate related classes
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in
packages.
Built-in Packages:
Built-in packages or predefined packages are those that come along as a part of JDK (Java Development
Kit) to simplify the task of Java programmer. They consist of a huge number of predefined classes and
interfaces that are a part of Java API’s. Some of the commonly used built-in packages are:
Java APl (Application Program Interface) provides a large numbers of classes grouped into different
packages according to functionality. Most of the time we use the packages available with the Java API
java.lang: Contains language support classes (e.g classed which defines primitive data types, math
operations). This package is automatically imported.
java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support for Date / Time operations.
java.awt: Contain classes for implementing the components for graphical user interfaces (like button,
menus etc).
User Defined Packages: User-defined packages are those which are developed by users in order to group
related classes, interfaces and sub packages
CREATING PACKAGES:
To create our own package , we must first declare the name of package using the package keyword
followed by a package name. This must be first statement in a java source file.
Package firstpackage;
…….
When the source file is compiled , java will create a .class file and store it in the same directory.
Example:
package mypackage;
public class student
{
Statement;
}
Example:
Package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}}
How to compile Java packages:
This is just like compiling a normal java program. If you are not using any IDE, you need to follow
the steps given below to successfully compile your packages:
Example:
javac -d . Simple.java
1. Declare the package at the beginning of a file using the form package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the programs as classname.java file in the subdirectory created.
5. Compile the file . This creates .class file in subdirectory. Remember that name of the package
must be same as the directory under which this file is saved.
Accessing a Package
1. import package.*;
2. import package.classname;
1. import package.*;
If you use package.* then all the classes and interfaces of this package will be accessible but not
sub packages. The import keyword is used to make the classes and interface of another package
accessible to the current package.
import packagename.*;
Here the package name may denote a single package or a hierarchy of packages. The star (*) indicates the
entire package hierarchy.
import firstPackage.secondPackage.MyClass ;
By the use of this statement ,all the members of the class MyClass can be directly accessed using the class
name .
import package.ClassA ;
class PackageTest
{
Public static void main(String args[ ])
{
ClassA obj = new ClassA( ) ;
Obj.displayA( ) ;
}}
//creating a package
package pack;
public class Addition
{
private double d1,d2;
public Addition(double a,double b)
{
d1 = a;
d2 = b;
}
public void sum()
{
System.out.println ("Sum of two given numbers is : " + (d1+d2) );
}
}
Compiling the above program:
2) Using packagename.classname:
If you import package.classname then only declared class of this package will be accessible.
//save by A.java
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
3) Using fully qualified name:
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.
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
package package_name;
public class ClassOne
{
public void methodClassOne()
{
System.out.println("Hello there its ClassOne");
}}
package package_one;
public class ClassTwo
{
public void methodClassTwo()
{
System.out.println("Hello there i am ClassTwo");
}}
Extending Interfaces
An interface can extend another interface, similarly to the way that a class can extend another
class.
The extends keyword is used to extend an interface, and the child interface inherits the methods
of the parent interface.
Example Program on Extending Interface:
import java.io.*;
interface student
{
public void store(int a,String b);
public void display();
}
interface marks extends student
{
public void read(int a,int b,int c);
public void compute();
}
class Demo5 implements marks
{
int rno;
String name;
int m1,m2,m3;
public void store(int a,String b)
{
rno=a;
name=b;
}
public void display()
{
System.out.println("The Student Roll Number is "+rno);
System.out.println("The Student Name is "+name);
}
public void read(int x, int y, int z)
{
m1=x;
m2=y;
m3=z;
}
public void compute()
{
int tot=m1+m2+m3;
float avg=(tot)/3;
System.out.println("The total is "+tot);
System.out.println("The average is "+avg);
}
public static void main(String args[])
{
Demo5 d=new Demo5();
d.store(01,"Aman");
d.display();
d.read(40,50,65);
d.compute();
}}
interface InnerInterface{
void innerMethod();
}
}
class OnlyOuter implements OuterInterface{
public void outerMethod() {
System.out.println("This is OuterInterface method");
}
}
obj_1.outerMethod();
obj_2.innerMethod();
}
Variables in Interfaces:
We can use interfaces to import shared constants into multiple classes by simply declaring an
interface that contains variables that are initialized to the desired values. When we include that interface
in a class (that is, when you “implement” the interface), all of those variable names will be in scope as
constants.
If an interface contains no methods, then any class that includes such an interface doesn’t actually
implement anything. It is as if that class were importing the constant fields into the class name space as
final variables.
Example: Java program to demonstrate variables in interface.
interface left
{
int i=10;
}
interface right
{
int i=100;
}
class Test implements left,right
{
public static void main(String args[])
{
System.out.println(left.i);
System.out.println(right.i);
}}
Example : Java program to implement interface and inheriting the properties from a class.
interface Teacher
{
void display1();
}
class Student
{
void display2()
{
System.out.println("Hi I am Student");
}}
class College extends Student implements Teacher
{
public void display1()
{
System.out.println("Hi I am Teacher");
}}
class Interface_Class
{
public static void main(String args[])
{
College c=new College();
c.display1();
c.display2();
}}
APPLYING INTERFACE:
To understand the power of interfaces, let‟s look at a more practical example. In earlier chapters,
you developed a class called Stack that implemented a simple fixed-size stack. However, there are many
ways to implement a stack.
For example, the stack can be of a fixed size or it can be “growable.” The stack can also be held
in an array, a linked list, a binary tree, and so on. No matter how the stack is implemented, the interface to
the stack remains the same. That is, the methods push( ) and pop( ) define the interface to the stack
independently of the details of the implementation. Because the interface to a stack is separate from its
implementation, it is easy to define a stack interface, leaving it to each implementation to define the
specifics. Let‟s look at two examples.
First, here is the interface that defines an integer stack. Put this in a file called IntStack.java.
import java.io.*;
class BRRead
{
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do
{
c = (char) br.read();
System.out.println(c);
}
while(c != 'q');
}}
Scanner Class:
The Scanner class breaks the input into tokens using a delimiter which is whitespace bydefault.
It provides many methods to read and parse various primitive values.
METHOD DESCRIPTION
public String next() returns the next token from the scanner
public String nextLine() moves the scanner position to the next line and returns the value as a
string.
public byte nextByte() scans the next token as a byte.
public short nextShort() scans the next token as a short value.
public int nextInt() scans the next token as an int value
public long nextLong() scans the next token as a long value.
public float nextFloat() scans the next token as a float value.
public double nextDouble() scans the next token as a double value
}
}
2. Writing console output using write() method
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 acept escape sequences.
Example
FILE CLASS:
The java.io package include a File class for creating files and directories.
The File class contain several methods for supporting the various operations such as
Creating a file
Opening a file
Closing a file
Deleting a file
Getting name of the file
Renaming a file
Getting the size of the file
Checking the existence of a file
Checking whether the file is writable
Checking whether the file is readable
Syntax for creating an object to File class:
RANDOMACCESSFILE
In java, 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.
Unlike IO streams that allow reading and writing data sequentially, random access file allows you
to read and write a small chunk of data at any position in the file, using a file pointer.
Random access file is ideal for manipulating a particular file format at low level, such as reading,
creating and updating MP3 files, PDF files, etc and even your own file format.
RandomAccessFile Constructors
You can create a RandomAccessFile object by supplying the file path as a String or a File object,
plus the access mode:
Modes of RandomAccessFile
“rws”: same as “rw”, plus any changes to the file’s content and its metadata (such as the last modification
time) take effect immediately.
“rwd”: same as “rw”, plus any changes to the file’s content, but not its metadata take effect immediately.
Methods of RandomAccessFile
The RandomAccessFile class provides the following methods:
close(): It closes this random access fle stream and releases any system resources associated with the
stream.
seek(long pos): moves the file pointer to a specified position in the file.
skipBytes(int n): moves the file pointer advance n bytes from the current position. This skips over n
bytes of input.
For reading and writing, as the RandomAccessFile class implements both the DataOutput and DataInput
interfaces
Syntax:
The method seek() is used to set the current position of the file pointer
Here,newPos specifies the new position,in bytes,of the file pointer from the beginning of the file.
CONSOLE CLASS
Console class is used to read from and write to the console
It implements the Flushable interface
Console supplies no constructor ,a console object is obtained by calling System.console()
Syntax:
public static Console console ( )
If the console is available,its reference is returned otherwise null is returned.
Method Description
public String readLine() used to read a single line of text from the console
public String readLine(String fmt,Object... args) it provides a formatted prompt then reads the single
line of text from the console.
public char[] readPassword() used to read password that is not being displayed
on the console.
public char[] readPassword(String fmt,Object... it provides a formatted prompt then reads the
args) password that is not being displayed on the
console.
void flush() Causes buffered output to be written physically to
the console
Console printf(String fmtString,Object …args) Writes args to the console using the format
specified by fmtstring
Reader reader() Returns a reference to Reader connected to the
console
PrintWriter writer() Returns a reference to the Writer connected to the
console
Example on Reading Console Input And Writing Console Output
import java.io.*;
class ConsoleDemo
{
public static void main(String args[])
{
String str;
Console con;
con=System.Console();
if (con==null)
return;
str=con.readLine(“Enter a string:”);
con.printf(“Here is ur string: %s”,str);
}}
Output:
Enter a string:
Have a nice day
Here is ur string: Have a nice day
SERIALIZATION
Serialization in Java is a mechanism of writing the state of 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. The serialization and deserialization process is platform-independent, it means you can serialize
an object in a platform and deserialize in different platform.
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.
Advantages of Java Serialization
It is mainly used to travel object's state on the network (which is known as marshaling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to "mark" Java
classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are
also marker interfaces.
The String class and all the wrapper classes implement the java.io.Serializable interface by
default.
EXAMPLE
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.
import java.io.*;
class Depersist
{
public static void main(String args[])
{
try
{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}
catch(Exception e)
{
System.out.println(e);
}
}}
ENUMERATION
Enumerations was added to Java language in JDK5.
Enumeration means a list of named constant.
In Java, enumeration defines a class type.
An Enumeration can have constructors, methods and instance variables.
It is created using enum keyword.
Each enumeration constant is public, static and final by default.
Even though enumeration defines a class type and have constructors, you do not instantiate an
enum using new.
Enumeration variables are used and declared in much a same way as you do a primitive variable.
Syntax for defining Enumeration:
enum enumerationtype{identifier,identifier2,…….}
Example:
enum Season { WINTER, SPRING, SUMMER, FALL }
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY}
Syntax for declaring Enumeration variable:
enumerationtype variablename1,variablename2,…..;
Example:
Season s;
Day d;
enumeration variable can accept only enumeration constant as its value.
s= Season. WINTER;
d= Day. SUNDAY
Initializing specific value to the enum constants:
The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize
the specific value to the enum constants by defining fields and constructors. As specified earlier, Enum
can have fields, constructors and methods.
enum Season{ WINTER(5), SPRING(10), SUMMER(15), FALL(20)};
Methods of Enumeration
All enumerations automatically contain predefined methods: values( ) valueOf( )and ordinal() Their
general forms are shown here:
public static enum-type[ ] values( );
public static enum-type valueOf(String str);
public final int ordinal();
The values( ) method returns an array that contains a list of the enumeration constants.
The valueOf( ) method returns the enumeration constant whose value corresponds to the string passed in
str.
The ordinal() method returns this enumeration constant's ordinal.
The following program demonstrates the values( ), valueOf( ) and ordinal() methods:
enum Season { WINTER, SPRING, SUMMER, FALL }
class EnumDemo2 {
public static void main(String args[])
{
Season s;
Season allseasons[] = Season.values(); // use values()
for(Season x : allseasons)
System.out.println(x);
System.out.println();
s = Season.valueOf("SUMMER"); // use valueOf()
System.out.println("s contains " + s);
System.out.println("WINTER ordinal="+Season.WINTER.ordinal());
System.out.println("SPRING ordinal="+Season.SPRING.ordinal());
System.out.println("SUMMER ordinal="+Season.SUMMER.ordinal());
System.out.println(" FALL ordinal="+Season. FALL.ordinal());
}}
Output:
WINTER
SPRING
SUMMER
FALL
s contains SUMMER
WINTER ordinal=0
SPRING ordinal=1
SUMMER ordinal=2
FALL ordinal=3
AUTOBOXING AND UNBOXING:
The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and
opposite operation is known as unboxing. This is the new feature of Java5. So java programmer doesn't
need to write the conversion code.
Advantage of Autoboxing and Unboxing:
No need of conversion between primitives and Wrappers manually so less coding is required.
Simple Example of Autoboxing in java:
class BoxingExample1
{
public static void main(String args[])
{
int a=50;
Integer a2=new Integer(a); //Boxing
Integer a3=5; //Boxing
System.out.println(a2+" "+a3);
}}
Output:50 5
Simple Example of Unboxing in java:
The automatic conversion of wrapper class type into corresponding primitive type, is known as
Unboxing. Let's see the example of unboxing:
class UnboxingExample1
{
public static void main(String args[])
{
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}}
Output: 50
GENERICS
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-
defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to
create classes that work with different data types.
A class, interface, or method that operates on a parameterized type is called generic, as in generic class or
generic method.
The General Form of a Generic Class
class class-name <type-param-list>{ // ...}
Syntax for declaring a generic class:
class-name<type-arg-list> var-name =new class-name<type-arg-list> (cons-arg-list)