Java Unit II

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

UNIT II PACKAGES

INTRODUCTION TO PACKAGES

A java package is a group of similar types of classes, interfaces and sub-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.

Packages are used for:

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

Types of packages in Java:

1) User defined package: The package we create is called user-defined package.

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 API Packages:

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.io: Contains classes for supporting input / output operations.

java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support for Date / Time operations.

java.applet: Contains classes for creating Applets.

java.awt: Contain classes for implementing the components for graphical user interfaces (like button,
menus etc).

java.net: Contain classes for supporting networking operations.

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;

Public class FirstClass

…….

……. ( Body of class )

Here package name is firstPackage.

The class FirstClass is now considered a part of this package.


This file is saved as FirstClass.java and located in a directory named 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:

1. java -d directory javafilename

Example:

javac -d . Simple.java

How to run java package program:

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

To create our own package following steps are there:

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

How to access package from another package:


There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

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( ) ;
}}

Example of package that import the packagename.*:


//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello java");
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}}
Output: Hello java
Program 1: Write a program to create a package pack with Addition class.

//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.

Example of package by import package.classname:

//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.

Example of package by import fully qualified name:


//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output: Hello

SUB PACKAGES IN JAVA


A package inside another package is known as sub package.
package letmecalculate.multiply;
public class Multiplication
{
int product(int a, int b)
{
return a*b;
}}
If I create a package inside letmecalculate package then that will be called sub package.
Lets say I have created another package inside letmecalculate and the sub package name is multiply.
CLASSPATH:
The CLASSPATH is an environment variable that tells the Java compiler where to look for class
files to import.
If the package pack is available in different directory, in that case the compiler should be given
information regarding the package location by mentioning the directory name of the package in the
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

Creating our first package:


File name – ClassOne.java

package package_name;
public class ClassOne
{
public void methodClassOne()
{
System.out.println("Hello there its ClassOne");
}}

Creating our second package:


File name – ClassTwo.java

package package_one;
public class ClassTwo
{
public void methodClassTwo()
{
System.out.println("Hello there i am ClassTwo");
}}

ACCESS PROTECTION IN JAVA PACKAGES


In java, the access modifiers define the accessibility of the class and its members.
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.
Java has four access modifiers, and they are default, private, protected, and public.
Public: Same class, Same package, Subclasses, Everyone.
Public members can be accessed from everywhere within your application either through inheritance or
through object reference.
Private: Same class.
Private members are accessible only within the same class and also are not inherited.
Protected: Same class, Same package, Subclasses.
 members of the same class
 members of any class in the same package (same as default)
 subclasses (any level of subclass hierarchy) in other packages (only through inheritance).
 object reference (Parent or Child) in subclasses
Default: Same class, Same package.
 Default (no modifier) members can be accessed by members of the same class and members of
any class in the same package.
 Default members are inherited by another class only if both parent and child are in same package.
INTERFACES:
 The interface keyword is used to declare an interface.
 An interface is just like Java Class, but it only has static constants and abstract method.
 Java uses Interface to implement multiple inheritance.
 A Java class can implement multiple Java Interfaces.
 All methods in an interface are implicitly public and abstract.
Declaring Interfaces:
Syntax
Interface
{
//methods
}
Example:
interface Animal
{
public void eat();
public void travel();
}
Implementing Interfaces:
 A class uses the implements keyword to implement an interface.
 To use an interface in your class, append the keyword "implements" after your class name
followed by the interface name.
Example for Implementing Interface:
public class MammalInt implements Animal
{}

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();
}}

Extending Multiple Interfaces:


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are
not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
public interface Hockey extends Sports, Event
if the Hockey interface extended both Sports and Event
Nested Interfaces:
In java, an interface may be defined inside another interface, and also inside a class. The interface
that defined inside another interface or a class is konwn as nested interface. The nested interface is also
refered as inner interface.
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 declared within an interface is public by default.
 The nested interface declared within a class can be with any access modifier.
 Every nested interface is static by default.
interface OuterInterface{
void outerMethod();

interface InnerInterface{
void innerMethod();
}
}
class OnlyOuter implements OuterInterface{
public void outerMethod() {
System.out.println("This is OuterInterface method");
}
}

class OnlyInner implements OuterInterface.InnerInterface{


public void innerMethod() {
System.out.println("This is InnerInterface method");
}
}

public class NestedInterfaceExample {

public static void main(String[] args) {


OnlyOuter obj_1 = new OnlyOuter();
OnlyInner obj_2 = new OnlyInner();

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.

This interface will be used by both stack implementations.


// Define an integer stack interface.
interface IntStack
{
void push(int item); // store an item
int pop(); // retrieve an item
}
Applications are:
 Abstractions
 Multiple Inheritance
Difference between Interface and Abstract class:
Abstract Class Interface
Contains some abstract methods and some concrete Only abstract methods
methods
Contains instance variables Only static and final variables
Doesn’t support multiple inheritance support multiple inheritance
public class Apple extends Food { … } public class Person implements
Student,Athlete,Chef { … }
STREAM BASED INPUT/OUTPUT
Input/output
 Java I/O is a powerful concept, which provides the all input and output operations. Most of the
classes of I/O streams are available in java.io package.
 Java has many input and output streams that are used to read and write data.
Stream
 Java performs I/O through Streams.
 A stream means continuous flow of data.
 In Java, stream is basically a sequence of bytes, which has a continuous flow between Java
programs and data storage.
Types of Stream
Stream is basically divided into following types based on data flow direction.
Input Stream:
Input stream is represented as an input source. It is used to read the binary data from the source.
Output Stream:
Output stream represent a destination source. It is basically used to send out/write the data to
destination.
Byte Streams:
Byte stream is used to input and output to perform 8-bits bytes.

SOME IMPORTANT BYTE STREAM CLASSES.


STREAM CLASS DESCRIPTION
Buffered Input Stream Used for Buffered Input Stream.
Buffered Output Stream Used for Buffered Output Stream.
Data Input Stream Contains method for reading java standard data type
Data Output Stream An output stream that contain method for writing java standard data type
File Input Stream Input stream that reads from a file
File Output Stream Output stream that write to a file.
Input Stream Abstract class that describe stream input.
Output Stream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method

Byte Stream Classes are in divided in two groups


Input Stream Classes - These classes are subclasses of an abstract class, Input Stream and they are used
to read bytes from a source (file, memory or console).
Input Stream is an abstract class and hence we can't create its object but we can use its subclasses
for reading bytes from the input stream.
Output Stream Classes - These classes are subclasses of an abstract class, Output Stream and they are
used to write bytes to a destination (file, memory or console).
Output Stream class is a base class of all the classes that are used to write bytes to a file, memory
or console. Output Stream is an abstract class and hence we can't create its object but we can use its
subclasses for writing bytes to the output stream.
Character Streams:
Character stream basically works on 16 bit-Unicode value convention. This stream is used to read
and write data in the format of 16 bit Unicode characters.

SOME IMPORTANT CHARACTER STREAM CLASSES:


STREAM CLASS DESCRIPTION
Buffered Reader Handles buffered input stream.
Buffered Writer Handles buffered output stream.
File Reader Input stream that reads from file.
File Writer Output stream that writes to file
Input Stream Reader Input stream that translate byte to character
Output Stream Reader Output stream that translate character to byte
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output
Print Writer Output Stream that contain print() and println() method.

READING CONSOLE INPUT


We use the object of Buffered Reader class to take inputs from the keyboard.
To take input from a user, we use Buffered Reader class by creating an object of it. For that, we have to
write the following code.
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
BufferedReader - This is a class that is used for taking character input.
b - object of BufferedReader class
InputStreamReader - It converts bytes to characters.
System.in - It is input stream. User inputs are read from this.
Thus, we are taking user input from System.in which is converted from bytes to characters by the
class InputStreamReader. This value is stored in the object b of the class BufferedReader.
Reading data
Once we have taken input from the user, we need to read the data. Let's see how to read data.
Reading characters
To read characters, read() method is used with the object of the BufferedReader class.
Since read function returns an integer value, we need to convert it to character by typecasting it.
The version of read( ) that we will be using is
int read( ) throws IOException
There are many ways to read data from the console input keyboard. For example:
 InputStreamReader
 Console
 Scanner
 DataInputStream etc
InputStreamReader class: InputStreamReader class can be used to read data from keyboard.It performs
two tasks:
1.connects to input stream of keyboard
2.converts the byte-oriented stream into character-oriented stream
BufferedReader class: BufferedReader class can be used to read data line by line by readLine() method
In below example, we are connecting the BufferedReader stream with the InputStreamReader
stream for reading the line by line data from the keyboard.
import java.io.*;
class IODemo
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}}
Example: Reading characters from the keyboard
class Test
{
public static void main( String args[])
{
BufferedReader b = new Bufferedreader(new InputstreamReader(System.in));
char ch = (char)b.read();
}}

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

Example of the Scanner class


import java.util.Scanner;
class ScannerTest
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}}
Reading strings
We use readLine() method with the object of the BufferedReader class. Its general form is shown
here:
String readLine( ) throws IOException
class Test
{
public static void main( String args[])
{
BufferedReader b = new Bufferedreader(new InputstreamReader(System.in));
String s = b.readLine();
}}

// Read a string from console using a BufferedReader


import java.io.*;
class BRReadLines
{
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do
{
str = br.readLine();
System.out.println(str);
}
while(!str.equals("stop"));
}}

WRITING CONSOLE OUTPUT


In java, there are two methods to write console output.

 Using print() and println() methods


 Using write() method

1. Writing console output using print() and println() methods


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 separate line (new line). This method can be used with
console and also with other output sources.
Example
public class WritingDemo
{
public static void main(String[] args)
{
int[] list = new int[5];
for(int i = 0; i < 5; i++)
list[i] = i*10;
for(int i:list)
System.out.print(i); //prints in same line
System.out.println("");
for(int i:list)
System.out.println(i); //Prints in separate lines

}
}
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

public class WritingDemo


{
public static void main(String[] args)
{
int[] list = new int[26];
for(int i = 0; i < 26; i++)
{
list[i] = i + 65;
}
for(int i:list)
{
System.out.write(i);
System.out.write('\n');
}
}
}

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:

File fileobject=new File(“file name”);


Example:

File infile=new File(“demo.txt”);

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:

 public RandomAccessFile(File file, String mode)


 public RandomAccessFile(String name, String mode)

Modes of RandomAccessFile

The access mode can be one of the following values:

“r”: reading only mode.

“rw”: reading and writing mode.

“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.

write(): It writes the specifed byte to this fle

read(): It reads a byte of data from this fle.

length(): It returns the length of this fle

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.

getFilePointer(): returns the current position of the file pointer.

For reading and writing, as the RandomAccessFile class implements both the DataOutput and DataInput
interfaces

Reading methods: read(byte[]), readByte(), readInt(), readLong(), etc.

Writing methods: write(byte[]), writeByte(), writeInt(), writeLong(), etc.

Syntax:

void seek(long newPos)throws IOException

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.

//writing and reading with random access


import java.io.*;
class RandomIO
{
public static void main(String args[])
{
RandamAccessFile file=null;
Try
{
file=new RandomAccessFile(“rand.dat”, “rw”);
//Writing to the file
file.writeChar(‘x’);
file.writeInt(333);
file.writeDouble(3.1412);
file.seek(0);//go to the beginning
System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2); //go to the second item
System.out.println(file.readInt());
//go to the end and append false to the file
file.seek(file.length());
file.writeBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
catch(IOException e)
{
System.out.println(e);
}
Output:
x
333
3.1412
333
False

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.

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);
}
}}

Example of Java Deserialization


Deserialization is the process of reconstructing the object from the serialized state. It is the
reverse operation of serialization. Let's see an example where we are reading the data from a deserialized
object.

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)

You might also like