0% found this document useful (0 votes)
19 views32 pages

Unit Ii Java-1

This document covers Java packages, interfaces, and stream-based I/O, detailing how to define and use packages, access protection, and the implementation of interfaces. It explains the differences between abstract classes and interfaces, as well as the structure and usage of byte and character streams for input and output operations. Additionally, it provides examples of Java programs demonstrating these concepts, including package creation, interface implementation, and I/O operations.

Uploaded by

Vinay Vinnu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views32 pages

Unit Ii Java-1

This document covers Java packages, interfaces, and stream-based I/O, detailing how to define and use packages, access protection, and the implementation of interfaces. It explains the differences between abstract classes and interfaces, as well as the structure and usage of byte and character streams for input and output operations. Additionally, it provides examples of Java programs demonstrating these concepts, including package creation, interface implementation, and I/O operations.

Uploaded by

Vinay Vinnu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT - II

Packages - Defining a Package, CLASSPATH, Access protection, importing


packages. Interfaces - defining an interface, implementing interfaces, nested
interfaces, applying interfaces, variables in interfaces and extending interfaces.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character
streams, Reading console Input and Writing Console Output, File class,
Reading and writing Files, Random access file operations, The Console class,
Serialization, Enumerations, auto boxing, generics.

Defining a Package:
A package is a collection of classes and interfaces. To create packages simply
include a package command as the first statement in a Java source file.
Types of packages:
There are two different types of packages in Java. They are:
1. Built-in packages
2. User defined packages
Built-in packages: These are the packages which are already available in Java
language. These packages provide all most all necessary classes, interfaces and
methods for programmer to perform any task in his programs.
Ex: java.lang, java.io, java.util etc.

User-defined packages:
These are defined by the users
The general form of the package statement:
package pkg;

Here, pkg is the name of the package. For example, the following statement
creates a package called MyPackage:
package MyPackage;
The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];

Importing Packages:

Java includes the import statement to bring certain classes, or entire packages,
into visibility.
The general form of the import statement:
import pkg1 [.pkg2].(classname | *);

Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).Finally,
you specify either an explicit classname or a star (*), which indicates that the
Java compiler should import the entire package.
Example:

Write a java program to add two numbers using package

Step1:create a folder named pack1


Step2: create one class which contains one method. We will store this class in
a file named a.java. This file will be stored in a folder pack1.The code for this is
as follows

C:\VAAGESWARI>md pack1
C:\VAAGESWARI>cd pack1
C:\VAAGESWARI\pack1>edit a.java
package pack1;
public class a
{
public void add(int x, int y)
{
System.out.println("Addition of two numbers is "+(x+y));
}
}

C:\VAAGESWARI\pack1>javac a.java
C:\VAAGESWARI\pack1>cd..

Step3:Now we will write another java program named packdemo.java. This


program will use the methods defined in class “a”. This source file is stored in
the subdirectory pack1.The java code for this file is.
C:\VAAGESWARI>edit packdemo.java

import pack1.*;
class packdemo
{
public static void main(String args[])
{
a a1=new a(); // a is package class name
a1.add(10,20);
}
}
Step4: Now open the command prompt and issue the following commands in
order to run the package programs
C:\VAAGESWARI>javac packdemo.java
C:\VAAGESWARI>java packdemo
Output:-

Addition of two numbers is 30


CLASSPATH

Suppose our program is running in c:\ and the package pack is available in the
directory d:\sub. In this case, the compiler should be given information
regarding the package location by mentioning the directory name of the
package in class path.

Class path represents an Operating system’s environment variable which


stores active directory path such that all the files in those directories are
available to any programs in the system. Generally, it is written in all capital
letter as CLASSPATH.

The class path is an environment variable that tells the JAVA compiler where
to look for class files to import. CLASSPATH is generally set to a directory or a
JAR(Java Archive) file.

C:\>set CLASSPATH= D:\sub;.;%CLASSPATH%;

In the preceding command, we are setting the class path to sub directory and
current directory(.). And then we typed %CLASSPATH% which means retain the
already available class path as it is. This is necessary especially when the class
path in your system is already set to an important application that should not
disturbed

Access protection

Access specifier is a keyword that specifies how to access or retrieve the


members of a class. There are four Access specifiers in java

1. private

2. public

3. protected

4. default
1. Private members of a class are not accessible in other classes of
same package or another package
2. Public members of a class are available in other classes of same
package or another package.
3. Protected members are available to classes in the same package;
they are not available in other packages.
4. Default members are available to the classes in the same package
but not in other packages.

Defining an Interface
Interface declaration is same as class except that it consists of the methods
that are declared have no method body.

General form of an interface:

access interface name


{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

When no access modifier is included, then default access results, and the
interface is only available to other members of the package in which it is
declared. When it is declared as public, the interface can be used by any other
code. In this case, the interface must be the only public interface declared in
the file, and the file must have the same name as the interface. name is the
name of the interface, and can be any valid identifier. Notice that the methods
that are declared have no bodies. They end with a semicolon after the
parameter list. They are, essentially, abstract methods. Each class that
includes such an interface must implement all of the methods.

Example:
interface i1
{
void add(int a,int b);
}
Implementing Interfaces

Once an interface has been defined, one or more classes can implement that
interface. To implement an interface, include the implements clause in a class
definition, and then create the methods required by the interface.

The general form of a class that includes the implements clause looks like this:

class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}

If a class implements more than one interface, the interfaces are separated
with a comma. If a class implements two interfaces that declare the same
method, then the same method will be used by clients of either interface. The
methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature
specified in the interface definition.

Example:

class IDemo implements i1


{
public void add(int a,int b)
{
System.out.println(“sum is”+(a+b));
}
}

Advantages of interface in java:

Advantages of using interfaces are as follows:

1.Without bothering about the implementation part, we can achieve the


security of implementation
2.In java, multiple inheritance is not allowed, however you can use interface to
make use of it as you can implement more than one interface.

Ex: Write a java program to print “welcome to interface” using Interface


interface i1
{
public void display();
}
class abc implements i1
{
public void display()
{
System.out.println("Welcome to Interface");
}
}
class IDemo
{
public static void main(String[] args)
{
abc a=new abc();
a.display();
}
}

Output:

C:\>javac IDemo.java

C:\>java IDemo
Welcome to Interface

Ex: Write a java program for multiple Inheritance.


interface csea
{
public void display();
}
interface cseb
{
public void show();
}
interface csec
{
public void disp();
}
class vaag implements csea,cseb,csec
{
public void display()
{
System.out.println("welcome to csea");
}
public void show()
{
System.out.println("welcome to cseb");
}
public void disp()
{
System.out.println("welcome to csec");
}
}
public class MultipleInheritance
{
public static void main(String[] args)
{
vaag v=new vaag();
v.display();
v.show();
v.disp();
}
}
Output:
C:\>javac MultipleInheritance.java

C:\>java MultipleInheritance
welcome to csea
welcome to cseb
welcome to csec

Nested interfaces

An interface which is declared inside another interface or class is called Nested


interface.

Example:

interface i1
{
public void display();
interface i2
{
public void show();
}
}
class abc implements i1
{
public void display()
{
System.out.println("welcome to csea");
}
public void show()
{
System.out.println("welcome to cseb");
}
}
public class NIDemo
{
public static void main(String[] args)
{
abc a=new abc();
a.display();
a.show();
}
}
Output:

C:\>javac NIDemo.java

C:\>java NIDemo
welcome to csea
welcome to cseb

Applying Interfaces
The interface is powerful tool. The same interface can be used by different
classes for some method. Then this method can be implemented by each class
in its own way. Thus same interface can provide variety of implementations.
The selection of different implementations is done at the runtime.

Accessing multiple implementations of an interface through an interface


reference variable is the most powerful way that Java achieves run-time
polymorphism.

Example:
interface i1
{
public void calc(int a,int b);
}
class abc implements i1
{
public void calc(int a,int b)
{
System.out.println("sum is"+(a+b));
}
}
class xyz implements i1
{
public void calc(int a,int b)
{
System.out.println("sub is"+(a-b));
}
}
class AIDemo
{
public static void main(String[] args)
{
i1 inter;
abc ob1=new abc();
inter=ob1;
inter.calc(10,3);
xyz ob2=new xyz();
inter=ob2;
inter.calc(12,8);
}
}
Output:

C:\>javac AIDemo.java

C:\>java AIDemo
sum is13
sub is4

Variables in Interfaces
The variable in an interface is public, static, and final by default.

If any variable in an interface is defined without public, static, and final


keywords then, the compiler automatically adds the same.

No access modifier is allowed except the public for interface variables.

Every variable of an interface must be initialized in the interface itself.

The class that implements an interface cannot modify the interface variable,
but it may use as it defined in the interface.

interface i2
{
public void display();
final int balance=1000;
}
class abc implements i2
{
public void display()
{
if(balance>=1000)
{
System.out.println("you are allowed to do the transaction");
}
else
{
System.out.println("you are not allowed");
}
}
}
class VDemo
{
public static void main(String[] args)
{
abc a=new abc();
a.display();
}
}
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends. The syntax is
the same as for inheriting classes. When a class implements an interface that
inherits another interface, it must provide implementations for all methods
required by the interface inheritance chain.

Example:

interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class MyClass implements B
{
public void meth1()
{
System.out.println("welcome to meth1");
}
public void meth2()
{
System.out.println("welcome to meth2");
}
public void meth3()
{
System.out.println("welcome to meth3");
}
}
class INExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

Output:

C:\>javac INExtend.java
C:\>java INExtend
welcome to meth1
welcome to meth2
welcome to meth3
Differences between Abstract class and Interface

Abstract class Interface


1. An abstract class is written when 1. An interface is written when all the
there are some common features features are implemented differently in
shared by all the objects. different objects.
2.When an abstract class is written, it 2. An interface is written when the
is the duty of the programmer to programmer wants to leave the
provide sub classes to it implementation to the third party
vendors.
3.An abstract class can contain 3. An interface cannot contain
instance variables also instance variables, It contains only
constants.
4. An abstract class contains some 4. An interface can contain abstract
abstract methods and also some methods.
concrete methods.
5.All the abstract methods of the 5. All the methods of interface should
abstract class should be implemented be implemented in its implementation
in its sub classes classes.
6. Abstract class is declared by using 6.Interface is declared using the
the keyword abstract. keyword interface

Stream based I/O (java.io) –

The Stream classes:


Stream is basically a channel on which the data flow from sender to receiver.
An input object that reads the stream of data from a file is called input
stream.

The output object that writes the streams of data to a file is called output
stream.

The Stream is defined in the java.io package.

In java, 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.
In Java, every program creates 3 streams automatically, and these streams are
attached to the console.
 System.out: standard output stream for console output operations.
 System.in: standard input stream for console input operations.
 System.err: standard error stream for console error output operations.
The Java streams support many different kinds of data, including simple bytes,
primitive data types, localized characters, and objects.
Java provides two types of streams, and they are as follows.
 Byte Stream
 Character Stream
The following picture shows how streams are categorized, and various built-in
classes used by the java IO system.

Byte Stream in java


In java, the byte stream is an 8 bits carrier. The byte stream in java allows us
to transmit 8 bits of data.
The java byte streamis 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.
Character Stream:

In java, 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 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.

Reading console Input and Writing Console Output


In java,System is a class defined in java.lang and in,out and err are the
variables of the class System.
Hence System.out is an object used for standard output stream and System.in
and System.err are the objects for standard input stream and error.
When we want to read some characters from the console we should make use
System.in.
The character stream class BufferedReader is used for this purpose.In fact we
should pass the variables System.in to BufferedReader object.Along with it we
should also mention the abstract class of BuufereReader class which is
InputStreamReader.
Example 1:
import java.io.*;
public class AddDemo
{
public static void main(String[] args)throws Exception
{
System.out.println("\n Welcome to vaageswari college of Engineering
Students\n");
int a,b,c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a value");
a = Integer.parseInt(br.readLine());
System.out.println("Enter b value");
b = Integer.parseInt(br.readLine());
c=a+b;
System.out.println("Sum is"+c);
}
}
C:\>javac AddDemo.java
C:\>java AddDemo
Welcome to vaageswari college of Engineering Students
Enter a value
10
Enter b value
23
Sum is33
Example 2 - Reading from a file
import java.io.*;
public class ReadingDemo
{
public static void main(String[] args) throws IOException
{
Reader in = new FileReader("C:\\CSE\\dataFile.txt");
try
{
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
input.close();
}
}
}

Writing Console Output:


The simple method used for writing the output on the console is write().
Syntax is:
System.out.write(int b)
The byte specified by b has to be written on the console. But typically print() or
println() is used to write the output on the console. These methods are
available in PrintWriter class.

Example - Writing data into a file


import java.io.*;
public class WritingDemo
{
public static void main(String[] args) throws IOException
{
Writer out = new FileWriter("C:\\CSE\\dataFile.txt");
String msg = "Welcome to CSE";

try
{
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
out.close();
}
}
}

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.
The File class in java has the following constructors.
S.No. Constructor with Description

1 File(String pathname)
It creates a new File instance by converting the givenpathname string
into an abstract pathname. If the given string isthe empty string, then
the result is the empty abstract pathname.

2 File(String parent, String child)


It Creates a new File instance from a parent abstractpathname and a
child pathname string. If parent is null then the new File instance is
created as if by invoking thesingle-argument File constructor on the
given child pathname string.

3 File(File parent, String child)


It creates a new File instance from a parent abstractpathname and a
child pathname string. If parent is null then the new File instance is
created as if by invoking thesingle-argument File constructor on the
given child pathname string.

4 File(URI uri)
It creates a new File instance by converting the given file: URI into an
abstract pathname.
The File class in java has the following methods.
S.No. Methods with Description

1 String getName()
It returns the name of the file or directory that referenced by the current
File object.

2 String getParent()
It returns the pathname of the pathname's parent, or null if the
pathname does not name a parent directory.

3 String getPath()
It returns the path of curent File.

4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.

5 String getAbsolutePath()
It returns the current file or directory path from the root.

6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.

7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.

8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.

9 boolean exists()
It returns true if the current file or directory exist; otherwise returns
false.

10 boolean canRead()
It returns true if and only if the file specified exists and can be read by
the application; false otherwise.

11 boolean canWrite()
It returns true if and only if the file specified exists and the application is
allowed to write to the file; false otherwise.

12 long length()
It returns the length of the current file.

13 long lastModified()
It returns the time that specifies the file was last modified.
S.No. Methods with Description

14 boolean createNewFile()
It returns true if the named file does not exist and was successfully
created; false if the named file already exists.

15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or
directory is successfully deleted; false otherwise.

16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the
virtual machine terminates.

17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.

18 boolean mkdirs()
It returns true if and only if the directory was created, along with all
necessary parent directories; false otherwise.

19 boolean renameTo(File dest)


It renames the current file. And returns true if and only if the renaming
succeeded; false otherwise.

20 boolean setLastModified(long time)


It sets the last-modified time of the file or directory. And returns true if
and only if the operation succeeded; false otherwise.

21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and
only if the operation succeeded; false otherwise.

22 String[] list()
It returns an array of strings containing names of all the files and
directories in the current directory.

23 String[] list(FilenameFilter filter)


It returns an array of strings containing names of all the files and
directories in the current directory that satisfy the specified filter.

24 File[] listFiles()
It returns an array of file references containing names of all the files and
directories in the current directory.
S.No. Methods with Description

25 File[] listFiles(FileFilter filter)


It returns an array of file references containing names of all the files and
directories in the current directory that satisfy the specified filter.

26 boolean equals(Object obj)


It returns true if and only if the argument is not null and is an abstract
pathname that denotes the same file or directory as this abstract
pathname.

27 int compareTo(File pathname)


It Compares two abstract pathnames lexicographically. It returns zero if
the argument is equal to this abstract pathname, a value less than zero
if this abstract pathname is lexicographically less than the argument, or
a value greater than zero if this abstract pathname is lexicographically
greater than the argument.

28 int compareTo(File pathname)


Compares this abstract pathname to another object. Returns zero if the
argument is equal to this abstract pathname, a value less than zero if
this abstract pathname is lexicographically less than the argument, or a
value greater than zero if this abstract pathname is lexicographically
greater than the argument.

Example:
import java.io.*;
public class FileClassTest
{
public static void main(String args[])
{
File f = new File("C:\\CSE\\datFile.txt");
System.out.println("Executable File : " + f.canExecute());
System.out.println("Name of the file : " + f.getName());
System.out.println("Path of the file : " + f.getAbsolutePath());
System.out.println("Parent name : " + f.getParent());
System.out.println("Write mode : " + f.canWrite());
System.out.println("Read mode : " + f.canRead());
System.out.println("Existance : " + f.exists());
System.out.println("Last Modified : " + f.lastModified());
System.out.println("Length : " + f.length());
}
}
Output:

File Reading & Writing

In java, there multiple ways to read data from a file and to write data to a file.
The most commonly used ways are as follows.
 Using Byte Stream (FileInputStream and FileOutputStream)
 Using Character Stream (FileReader and FileWriter)

File Handling using Byte Stream


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.
Let's look at the following example program that reads data from a file and
writes the same to another file using FileInoutStream and FileOutputStream
classes.
Example:
import java.io.*;
public class FileReadingTest
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;

try
{
in = new FileInputStream("C:\\CSE\\Input-File.txt");
out = new FileOutputStream("C:\\CSE\\Output-File.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
System.out.println("Reading and Writing has been success!!!");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}

File Handling using Character Stream


In java, we can use a character stream to handle files. The character stream
has the following built-in classes to perform various operations on a file.
 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.
Let's look at the following example program that reads data from a file and
writes the same to another file using FIleReader and FileWriter classes.
Example:
import java.io.*;
public class FileIO
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;

try
{
in = new FileReader("C:\\CSE\\Input-File.txt");
out = new FileWriter("C:\\CSE\\Output-File.txt");

int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
System.out.println("Reading and Writing in a file is done!!!");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}

Random access file operations


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.
RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.
S.No. Constructor with Description

1 RandomAccessFile(File 23nitiali, String mode)


It creates a random access file stream to read from, and optionally to
write to, the file specified by the File argument.

2 RandomAccessFile(String 23nitiali, String mode)


It creates a random access file stream to read from, and optionally to
write to, a file with the specified 23nitiali.

Access Modes
Using the RandomAccessFile, a file may created in th following 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.
RandomAccessFile methods
The RandomAccessFile class in java has the following methods.

S.No. Methods with Description

1 int read()
It reads byte of data from a file. The byte is returned as an integer in
the range 0-255.

2 int read(byte[] b)
It reads byte of data from file upto b.length, -1 if end of file is reached.

3 int read(byte[] b, int offset, int len)


It reads bytes 23nitializing from offset position upto b.length from the
buffer.

4 23nitial readBoolean()
It reads a 23nitial value from from the file.
S.No. Methods with Description

5 byte readByte()
It reads signed eight-bit value from file.

6 char readChar()
It reads a character value from file.

7 double readDouble()
It reads a double value from file.

8 float readFloat()
It reads a float value from file.

9 long readLong()
It reads a long value from file.

10 int 24nitial()
It reads a integer value from file.

11 void readFully(byte[] b)
It reads bytes 24nitializing from offset position upto b.length from the
buffer.

12 void readFully(byte[] b, int offset, int len)


It reads bytes 24nitializing from offset position upto b.length from the
buffer.

13 String readUTF()
t reads in a string from the file.

14 void seek(long pos)


It sets the file-pointer(cursor) measured from the beginning of the file,
at which the next read or write occurs.

15 long length()
It returns the length of the file.
S.No. Methods with Description

16 void write(int b)
It writes the specified byte to the file from the current cursor position.

17 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method
in class Float, and then writes that int value to the file as a four-byte
quantity, high byte first.

18 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits
method in class Double, and then writes that long value to the file as an
eight-byte quantity, high byte first.

Example:
import java.io.*;
public class RandomAccessFileDemo
{
public static void main(String[] args)
{
try
{
double d = 1.5;
float f = 14.56f;

// Creating a new RandomAccessFile - "F2"


RandomAccessFile f_ref = new RandomAccessFile("C:\\CSE\\Input-File.txt", "rw");

// Writing to file
f_ref.writeUTF("Hello, Good Morning!");

// File Pointer at index position - 0


f_ref.seek(0);

// read() method :
System.out.println("Use of read() method : " + f_ref.read());

f_ref.seek(0);
byte[] b = {1, 2, 3};

// Use of .read(byte[] b) method :


System.out.println("Use of .read(byte[] b) : " + f_ref.read(b));

// readBoolean() method :
System.out.println("Use of readBoolean() : " + f_ref.readBoolean());

// readByte() method :
System.out.println("Use of readByte() : " + f_ref.readByte());

f_ref.writeChar('c');
f_ref.seek(0);

// readChar() :
System.out.println("Use of readChar() : " + f_ref.readChar());

f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);

// read double
System.out.println("Use of readDouble() : " + f_ref.readDouble());

f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);

// readFloat() :
System.out.println("Use of readFloat() : " + f_ref.readFloat());

f_ref.seek(0);
// Create array upto geek.length
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);

String str1 = new String(arr);


System.out.println("Use of readFully() : " + str1);

f_ref.seek(0);

// readFully(byte[] b, int off, int len) :


f_ref.readFully(arr, 0, 8);
String str2 = new String(arr);
System.out.println("Use of readFully(byte[] b, int off, int len) : " + str2);
}
catch (IOException ex)
{
System.out.println("Something went Wrong");
ex.printStackTrace();
}
}
}

Console class
The Java Console class is be used to get input from console. It provides
methods to read texts and passwords. If you read password using Console
class, it will not be displayed to the user.
Methods:
String readLine() It is used to read a single line of text from the console.
char[] readPassword() It is used to read password that is not being displayed
on the console.
Ex:
import java.io.*;
class ReadStringTest
{
public static void main(String args[])
{
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output:
Enter your name: VAAGESWARI
Welcome VAAGESWARI
Ex2:
import java.io.Console;
class ReadPasswordTest
{
public static void main(String args[])
{
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}
Output:
Enter password:
Password is: 123

Serialization
The process of saving an object to a file (or) the process of sending an object
across the network is called serialization. But strictly speaking the process of
converting the object from java supported form to the network supported form
of file supported form.
To do the serialization we required fallowing classes
1. FileOutputStream
2. ObjectOutputStream
Deserialization:-
The process of reading the object from file supported form or network
supported form to the java supported form is called deserialization.
We can achieve the deserialization by using fallowing classes.
1. FileInputStream
2. ObjectInputStream
Ex:-Student.java
import java.io.Serializable;
public class Student implements Serializable
{
int id;
String name;
int marks;
public Student(int id, String name,int marks)
{
this.id = id;
this.name = name;
this.marks=marks;
}
}
To perform serialization :- we are writing the object data to the file called
abc.txt file we are transferring that file across the network.
import java.io.*;
class Serializable1
{
public static void main(String args[])throws Exception
{
Student s1 =new Student(211,"ravi",100);
FileOutputStream fos=new FileOutputStream("abc.txt",true);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.flush();
System.out.println("Serializable process success");
}
}

Enumerations:
An enum is a data type which contains 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) etc.
The enum constants are static and final implicitely. It is available from Java 5.
Points to remember for Enum:
enum improves type safety
enum can be easily used in switch
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 enum in java:


class EnumEx
{
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY}
public static void main(String args[])
{
Day day=Day.MONDAY;
switch(day)
{
case SUNDAY:
System.out.println("sunday");
break;
case MONDAY:
System.out.println("monday");
break;
default:
System.out.println("other day");
}
}
}
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:
Generic is a mechanism for creating a general model in which generic methods
and generic classes enable programmers to specify a single method and single
class for performing the desired task.
Creating generic class:
class MyGen<T>
{
T obj;
void display(T obj)
{
System.out.println("given value is"+obj);
}
}
class TestGenerics3
{
public static void main(String args[])
{
MyGen<Integer> m=new MyGen<Integer>();
m.display(2);
MyGen<String> m1=new MyGen<String>();
m1.display("abc");
}
}

You might also like