Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Java Unit-II Notes

Uploaded by

Bhumika Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java Unit-II Notes

Uploaded by

Bhumika Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

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.

PACKAGES IN JAVA
A package is a collection of similar types of classes, interfaces and sub-packages.
Types of packages
Package are classified into two type which are given below.
1. Predefined or built-in package
2. User defined package
1. Predefined or built-in package
These are the packages which are already designed by the Sun Microsystem and supply as a part of
java API, every predefined package is collection of predefined classes, interfaces and sub-package.
Following are the list of predefined packages in java
 java.lang − This package provides the language basics.
 java.util − This packages provides classes and interfaces (API’s) related to collection frame work,
events, data structure and other utility classes such as date.
 java.io − This packages provides classes and interfaces for file operations, and other input and
output operations.
 java.awt − This packages provides classes and interfaces to create GUI components in Java.
 java.time − The main API for dates, times, instants, and durations.
2. User defined package
 If any package is design by the user is known as user defined package.
 User defined package are those which are developed by java programmer and supply as a part of
their project to deal with common requirement.
DEFINING A PACKAGE
Rules to create user defined package
 Package statement should be the first statement of any package program.
 Choose an appropriate class name or interface name and whose modifier must be public.
 Any package program can contain only one public class or only one public interface but it can
contain any number of normal classes.
 Package program should not contain any main() method.
 Modifier of constructor of the class which is present in the package must be public. (This is not
applicable in case of interface because interface have no constructor.)
 The modifier of method of class or interface which is present in the package must be public (This
rule is optional in case of interface because interface methods by default public)
 Every package program should be save either with public class name or public Interface name
 If you omit the package statement, the class names are put into the default package, which has no
name.
Syntax
package packagename;
Example
package mypack;
Compile package programs
For compilation of package program first we save program with public className.java and it
compile using below syntax:
Syntax
javac -d . className.java
Explanation
 In above syntax "-d" is a specific tool which tells to java compiler create a separate folder for the
given package in given path.
 When we give specific path then it create a new folder at that location and when we use . (dot)
then it crate a folder at current working directory.
Note: Any package program can be compile but can not be execute or run. These program can be
executed through user defined program which are importing package program.
Example of Package Program
Package program which is save with A.java and compile by javac -d . A.java.
package mypack;
public class A
{
public void show()
{
System.out.println("Sum method");
}
}
IMPORTING PACKAGES
 To import the java package into a class, we need to use the java import keyword which is used to access
the package and its classes into the java program.
 Use import to access built-in and user-defined packages into your java source file to refer to a
class in another package by directly using its name.
syntax:
import package.name.ClassName; // To import a certain class only
import package.name.* // To import the whole package
Example:
import java.util.Date; // imports only Date class
import java.io.*; // imports everything inside java.io package
Example
import mypack.A;
public class Hello
{
public static void main(String args[])
{
A a=new A();
a.show();
System.out.println("show() class A");
}
}
CLASSPATH
CLASSPATH can be set by any of the following ways:
 CLASSPATH can be set permanently in the environment:
 In Windows, choose control panel
 System
 Advanced
 Environment Variables
 choose “System Variables” (for all the users) or “User Variables” (only the currently login user)
 choose “Edit” (if CLASSPATH already exists) or “New”
 Enter “CLASSPATH” as the variable name
 Enter the required directories and JAR files (separated by semicolons) as the value (e.g.,
“.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”).
 Take note that you need to include the current working directory (denoted by ‘.’) in the
CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
 > SET CLASSPATH
 CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
 > SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
 Instead of using the CLASSPATH environment variable, you can also use the command-line
option -classpath or -cp of the javac and java commands, for example,
> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
ACCESS PROTECTION
In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used
with the element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
 When no access modifier is specified for a class, method, or data member – It is said to be having
the default access modifier by default.
 The default modifier is accessible only within package.
 It cannot be accessed from outside the package.
 It provides more accessibility than private. But, it is more restrictive than protected, and public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
2. private
 The private access modifier is accessible only within the class.
 The private access modifier is specified using the keyword private.
 The methods or data members declared as private are accessible only within the class in
which they are declared.
 Any other class of the same package will not be able to access these members.
 Top-level classes or interfaces can not be declared as private because private means “only
visible within the enclosing class”.
Example
 In this example, we have created two classes A and Simple.
 A class contains private data member and private method.
 We are accessing these private members from outside the class, so there is a compile-time
error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
3. protected
 The protected access modifier is accessible within package and outside the package but through
inheritance only.
 The protected access modifier is specified using the keyword protected.
Example
 In this example, we have created the two packages pack and mypack.
 The A class of pack package is public, so can be accessed from outside the package.
 But msg method of this package is declared as protected, so it can be accessed from outside the
class only through inheritance.
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
4. public
 The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
 The public access modifier is specified using the keyword public.
Example
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Table: class member access
Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private YES NO NO NO

Default YES YES NO NO

Protected YES YES YES NO

Public YES YES YES YES


INTERFACES
 Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
 The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.
DIFFERENCE BETWEEN CLASS AND INTERFACE

S. No. Class Interface

In class, you can instantiate variables and In an interface, you can’t instantiate
1.
create an object. variables and create an object.

Class can contain concrete(with The interface cannot contain


2.
implementation) methods concrete(with implementation) methods

The access specifiers used with classes are In Interface only one specifier is used-
3.
private, protected, and public. Public.

Why do we use an Interface?


 It is used to achieve total abstraction.
 Since java does not support multiple inheritances in the case of class, by using an interface it can
achieve multiple inheritances.
 Any class can extend only 1 class but can any class implement infinite number of interface.
 Interfaces are used to implement abstraction. So the question arises why use interfaces when
we have abstract classes?
 The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public and static.
DIFFERENCE BETWEEN ABSTRACT CLASS AND INTERFACE

Abstract class Interface

It is collection of abstract method and


It is collection of abstract method.
concrete methods.

There properties can be reused commonly in a There properties commonly usable in any
specific application. application of java environment.

It does not support multiple inheritance. It support multiple inheritance.

Abstract class is preceded by abstract


It is preceded by Interface keyword.
keyword.

Which may contain either variable or


Which should contains only constants.
constants.

The default access specifier of abstract class There default access specifier of interface method
methods are default. are public.

These class properties can be reused in other These properties can be reused in any other class
class using extend keyword. using implements keyword.

Inside abstract class we can take constructor. Inside interface we can not take any constructor.

For the abstract class there is no restriction For the interface it should be compulsory to
like initialization of variable at the time of initialization of variable at the time of variable
variable declaration. declaration.

There are no any restriction for abstract class For the interface variable can not declare variable
variable. as private, protected, transient, volatile.

There are no any restriction for abstract class


For the interface method can not declare method
method modifier that means we can use any
as, protected, static, private, final, synchronized.
modifiers.
DEFINING INTERFACES:
The interface keyword is used to declare an interface.
Syntax
interface interface_name
{
declare constant fields
declare methods that abstract
}
Example
interface A
{
public static final int a = 10;
void display();
}
IMPLEMENTING INTERFACES
A class uses the implements keyword to implement an interface.
Example
interface A
{
public static final int a = 10;
void display();
}
class B implements A
{
public void display()
{
System.out.println("Hello");
}
}
class InterfaceDemo
{
public static void main (String[] args)
{
B obj= new B();
obj.display();
System.out.println(a);
}
}
APPLYING INTERFACES
To understand the power of interfaces, let’s look at a more practical example.
Example: interface IntStack
{
void push(int item);
int pop();
}
class FixedStack implements IntStack
{
private int stck[];
private int top;
FixedStack(int size)
{
stck = new int[size];
top = -1;
}
public void push(int item)
{
if(top==stck.length-1)
System.out.println("Stack is full.");
else
stck[++top] = item;
}
public int pop()
{
if(top ==-1)
{
System.out.println("Stack underflow.");
return 0;
}
else
return stck[top--];
}
}
class InterfaceTest
{
public static void main(String args[])
{
FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
for(int i=0; i<5; i++)
mystack1.push(i);
for(int i=0; i<8; i++)
mystack2.push(i);
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}
VARIABLES IN INTERFACE
 Variables can be declared inside of interface declarations. They are implicitly final and static,
meaning they cannot be changed by the implementing class.
 You 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.
Example
interface SharedConstants
{
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int NEVER = 4;
}
class Question implements SharedConstants
{
BufferedReader br=new BufferedReader(new InputStreamreader(System.in));
int ask()
{
System.out.println(“would u like to have a cup of coffee?)
String ans=br.readLine();
if (ans= =”no”)
return NO;
else if (ans==”yes”)
return YES;
else if (ans==”notnow”)
return LATER;
else
return NEVER;
}
}
class AskMe
{
public static void main(String args[])
{
Question q = new Question();
System.out.println(q.ask());
}
}
EXTENDING INTERFACES
 One interface can inherit another by use of the keyword extends.
 When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within 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("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class InterfaceDemo
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
NESTED INTERFACE
 An interface i.e. declared within another interface or class is known as nested interface.
 The nested interfaces are used to group related interfaces so that they can be easy to maintain.
 The nested interface must be referred by the outer interface or class. It can't be accessed directly.
 Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
 Nested interfaces are declared static implicitely.
Syntax of nested interface which is declared within the interface
interface interface_name
{
...........
interface nested_interface_name
{
……….
}
}
Syntax of nested interface which is declared within the class
class class_name
{
...........
interface nested_interface_name
{
...........
}
}
Example of nested interface which is declared within the interface
In this example, we are going to learn how to declare the nested interface and how we can access it.
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
Showable.Message message=new TestNestedInterface1();
message.msg();
}
}
Example of nested interface which is declared within the class
Let's see how can we define an interface inside the class and how can we access it.
class A
{
interface Message
{
void msg();
}
}
class TestNestedInterface2 implements A.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
A.Message message=new TestNestedInterface2();
message.msg();
}
}
MULTIPLE INHERITANCE IN JAVA BY INTERFACE
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as
multiple inheritance.

Example
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A obj = new A();
obj.print();
obj.show();
}
}
STREAM BASED I/O (JAVA.IO)
 Java I/O (Input and Output) is used to process the input and produce the output.
 Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
 We can perform file handling in Java by Java I/O API.
STREAM
In Java, streams are the sequence of data that are read from the source and written to the
destination.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1. System.in: This is the standard input stream that is used to read characters from the keyboard
or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the result of a program
on an output device like the computer screen.
3. System.err: This is the standard error stream that is used to output all the error data that a
program might throw, on a computer screen or any standard output device.
TYPES OF STREAMS
Depending on the type of operations, streams can be divided into two primary classes:
 InPutStream − The InputStream is used to read data from a source.

 OutPutStream − The OutputStream is used for writing data to a destination.

Depending upon the data a stream can be classified into:


1. Byte Stream

2. Character Stream
1. BYTE STREAM
Java byte streams are used to perform input and output of 8-bit bytes.
Byte Stream Classes
All byte stream classes are derived from base abstract classes called InputStream
and OutputStream.
InputStream Class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream
of bytes.
Subclasses of InputStream
In order to use the functionality of InputStream, we can use its subclasses. Some of them are:
Stream class Description

BufferedInputStream Used for Buffered Input Stream.


DataInputStream Contains method for reading java standard datatype

FileInputStream Input stream that reads from a file


Methods of InputStream
The InputStream class provides different methods that are implemented by its subclasses.
Here are some of the commonly used methods:
 read() - reads one byte of data from the input stream
 read(byte[] array) - reads bytes from the stream and stores in the specified array
 available() - returns the number of bytes available in the input stream
 mark() - marks the position in the input stream up to which data has been read
 reset() - returns the control to the point in the stream where the mark was set
 close() - closes the input stream
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes.
Subclasses of OutputStream
In order to use the functionality of OutputStream, we can use its subclasses. Some of them are:
Stream class Description
BufferedOutputStream Used for Buffered Output Stream.
DataOutputStream An output stream that contain method for writing java standard data type

FileOutputStream Output stream that write to a file.


PrintStream Output Stream that contain print() and println() method
Methods of OutputStream
The OutputStream class provides different methods that are implemented by its subclasses. Here are
some of the methods:
 write() - writes the specified byte to the output stream
 write(byte[] array) - writes the bytes from the specified array to the output stream
 flush() - forces to write all data present in output stream to the destination
 close() - closes the output stream
2. CHARACTER STREAM
Character stream is used to read and write a single character of data.
Character Stream Classes
All the character stream classes are derived from base abstract classes Reader and Writer.
Reader Class
The Reader class of the java.io package is an abstract super class that represents a stream of
characters.
Sub classes of Reader Class
In order to use the functionality of Reader, we can use its subclasses. Some of them are:
Stream class Description
BufferedReader Handles buffered input stream.
FileReader Input stream that reads from file.
InputStreamReader Input stream that translate byte to character
Methods of Reader
The Reader class provides different methods that are implemented by its subclasses. Here are
some of the commonly used methods:
 ready() - checks if the reader is ready to be read
 read(char[] array) - reads the characters from the stream and stores in the specified array
 read(char[] array, int start, int length) - reads the number of characters equal to length from
the stream and stores in the specified array starting from the start
 mark() - marks the position in the stream up to which data has been read
 reset() - returns the control to the point in the stream where the mark is set
 skip() - discards the specified number of characters from the stream
Writer Class
 The Writer class of the java.io package is an abstract super class that represents a stream of
characters.
 Since Writer is an abstract class, it is not useful by itself. However, its subclasses can be used to
write data.
Subclasses of Writer
Stream class Description
BufferedWriter Handles buffered output stream.
FileWriter Output stream that writes to file.
PrintWriter Output Stream that contain print() and println() method.
Methods of Writer
The Writer class provides different methods that are implemented by its subclasses. Here are
some of the methods:
 write(char[] array) - writes the characters from the specified array to the output stream
 write(String data) - writes the specified string to the writer
 append(char c) - inserts the specified character to the current writer
 flush() - forces to write all the data present in the writer to the corresponding destination
 close() - closes the writer
READING CONSOLE INPUT
There are times when it is important for you to get input from users for execution of programs. To do
this you need Java Reading Console Input Methods.
Java Reading Console Input Methods
1. Using BufferedReader Class
2. Using Scanner Class
3. Using Console Class
1. Using BufferedReader Class
 Reading input data using the BufferedReader class is the traditional technique. This way of the
reading method is used by wrapping the System.in (standard input stream) in
an InputStreamReader which is wrapped in a BufferedReader, we can read input from the
console.
 The BufferedReader class has defined in the java.io package.
 We can use read() method in BufferedReader to read a character.
int read() throws IOException
Reading Console Input Characters Example:
import java.io.*;
class ReadingConsoleInputTest
{
public static void main(String args[])
{
char ch;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, char 'x' to exit.");
do
{
ch = (char) br.read();
System.out.println(ch);
} while(ch != 'x');
}
}
How to read a string input in java?
readLine() method is used to read the string in the BufferedReader.
Program to take String input from Keyboard in Java
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
2. Using the Scanner Class
Scanner is one of the predefined class which is used for reading the data dynamically from the
keyboard.
Import Scanner Class in Java
java.util.Scanner
Constructor of Scanner Class
Scanner(InputStream)
This constructor create an object of Scanner class by talking an object of InputStream class. An object
of InputStream class is called in which is created as a static data member in the System class.
Syntax of Scanner Class in Java
Scanner sc=new Scanner(System.in);
Here the object 'in' is use the control of keyboard

Instance methods of Scanner Class

S.No Method Description

1 public byte nextByte() Used for read byte value

2 public short nextShort() Used for read short value

3 public int nextInt() Used for read integer value

4 public long nextLong() Used for read numeric value

5 public float nextLong() Used for read numeric value

6 public double nextDouble() Used for read double value

7 public char nextChar() Used for read character

8 public boolean nextBoolean() Used for read boolean value

Used for reading any kind of data in the


9 public String nextLine()
form of String data.
Example of Scanner Class in Java
import java.util.Scanner
public class ScannerDemo
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter first no= ");
int num1=s.nextInt();
System.out.println("Enter second no= ");
int num2=s.nextInt();
System.out.println("Sum of no is= "+(num1+num2));
}
}
3. Using the Console Class
 This is another way of reading user input from the console in Java.
 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.
 The Console class is defined in the java.io class which needs to be imported before using the
console class.
Example
import java.io.*;
class consoleEg
{
public static void main(String args[])
{
String name;
System.out.println ("Enter your name: ");
Console c = System.console();
name = c.readLine();
System.out.println ("Your name is: " + name);
}
}
WRITING CONSOLE OUTPUT
 print and println methods in System.out are mostly used for console output.
 These methods are defined by the class PrintStream which is the type of object referenced by
System.out.
 System.out is the byte stream.
 PrintStream is the output derived from OutputStream. write method is also defined in
PrintStream for console output.
void write(int byteval)
//Java code to Write a character in Console Output
import java.io.*;
class WriteCharacterTest
{
public static void main(String args[])
{
int byteval;
byteval = 'J';
System.out.write(byteval);
System.out.write('\n');
}
}

JAVA FILE CLASS


The File class of the java.io package is used to perform various operations on files and directories.
File and Directory
A file is a named location that can be used to store related information. For example,
main.java is a Java file that contains information about the Java program.
A directory is a collection of files and subdirectories. A directory inside a directory is known as
subdirectory.
Create a Java File Object
To create an object of File, we need to import the java.io.File package first. Once we import the
package, here is how we can create objects of file.
File f = new File(String pathName);
Here, we have created a file object named file. The object can be used to work with files and
directories.
Note: In Java, creating a file object does not mean creating a file. Instead, a file object is an abstract
representation of the file or directory pathname (specified in the parenthesis).
Java File Operation Methods

Operation Method Package

To create file createNewFile() java.io.File

To read file read() java.io.FileReader

To write file write() java.io.FileWriter

To delete file delete() java.io.File

JAVA CREATE FILES


To create a new file, we can use the createNewFile() method. It returns
 true if a new file is created.
 false if the file already exists in the specified location.
Example: Create a new File
// importing the File class
import java.io.File;
class MainDemo
{
public static void main(String[] args)
{
// create a file object for the current location
File f = new File("newFile.txt");
try
{
// trying to create a file based on the object
boolean value = f.createNewFile();
if (value)
{
System.out.println("The new file is created.");
}
else
{
System.out.println("The file already exists.");
}
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
In the above example, we have created a file object named f. The file object is linked with the
specified file path.
File f = new File("newFile.txt");
Here, we have used the file object to create the new file with the specified path.
If newFile.txt doesn't exist in the current location, the file is created and this message is shown.
The new file is created.
However, if newFile.txt already exists, we will see this message.
The file already exists.

JAVA READ FILES


To read data from the file, we can use subclasses of either InputStream or Reader.
Example: Read a file using FileReader
Suppose we have a file named input.txt with the following content.
This is a line of text inside the file.
Now let's try to read the file using Java FileReader.
import java.io.FileReader;
class MainDemo2
{
public static void main(String[] args)
{
char[] a = new char[100];
try
{
// Creates a reader using the FileReader
FileReader input = new FileReader("input.txt");
// Reads characters
input.read(a);
System.out.println("Data in the file:");
System.out.println(a);
// Closes the reader
input.close();
}
catch(Exception e)
{
e.getStackTrace();
}
}
}
JAVA WRITE TO FILES
To write data to the file, we can use subclasses of either OutputStream or Writer.
Example: Write to file using FileWriter
import java.io.FileWriter;
class Main
{
public static void main(String args[])
{
String data = "This is the data in the output file";
try
{
// Creates a Writer using FileWriter
FileWriter output = new FileWriter("output.txt");
// Writes string to the file
output.write(data);
System.out.println("Data is written to the file.");
// Closes the writer
output.close();
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
RANDOM ACCESS FILE OPERATIONS
The Java.io.RandomAccessFile class file behaves like a large array of bytes stored in the file system.
Constructor

Constructor Description

RandomAccessFile(File Creates a random access file stream to read from, and optionally
file, String mode) to write to, the file specified by the File argument.

RandomAccessFile(String Creates a random access file stream to read from, and optionally
name, String mode) to write to, a file with the specified name.

Methods

Modifier Method Description


and Type

void close() It closes this random access file stream and releases any
system resources associated with the stream.

FileChannel getChannel() It returns the unique FileChannel object associated with


this file.

int readInt() It reads a signed 32-bit integer from this file.

String readUTF() It reads in a string from this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.

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

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.

void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
Example
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample
{
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args)
{
try
{
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
SERIALIZATION

 In java, the Serialization is the process of converting an object into a byte stream so that it can
be stored on to a file, or memory, or a database for future access.
 The reverse operation of serialization is called deserialization where byte-stream is converted
into an object.
 Using serialization and deserialization, we can transfer the Object Code from one Java Virtual
machine to another.
 For serializing the object, we call the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream class.
 We must have to implement the Serializable interface for serializing the object.
Let's see the example given below:
import java.io.Serializable;
public class Student implements Serializable
{
int id;
String name;
public Student(int id, String name)
{
this.id = id;
this.name = name;
}
}
In the above example, Student class implements Serializable interface. Now its objects can be
converted into stream.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.
Constructor

1) public ObjectOutputStream(OutputStream creates an ObjectOutputStream that


out) throws IOException {} writes to the specified OutputStream.
Important Methods

Method Description

1) public final void writeObject(Object obj) writes the specified object to the
throws IOException {} ObjectOutputStream.

2) public void flush() throws IOException {} flushes the current output stream.

3) public void close() throws IOException {} closes the current output stream.
Example of Java Serialization
 In this example, we are going to serialize the object of Student class.
 The writeObject() method of ObjectOutputStream class provides the functionality to serialize the
object.
 We are saving the state of the object in the file named f.txt.
import java.io.*;
class Persist
{
public static void main(String args[])
{
try
{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}
catch(Exception e)
{
System.out.println(e);}
}
}
ENUMERATION
 The Enum in Java is a data type which contains a fixed set of constants.
 It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and WEST), season (SPRING,
SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and
BLACK) etc.
 According to the Java naming conventions, we should have all constants in capital letters. So, we
have enum constants in capital letters.
 Java Enums can be thought of as classes which have a fixed set of constants (a variable that does
not change).
 The Java enum constants are static and final implicitly.
 Enums are used to create our own data type like classes.
 The enum data type (also known as Enumerated Data Type) is used to define an enum in Java.
Unlike C/C++, enum in Java is more powerful. Here, we can define an enum either inside the class
or outside the class.
 Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods in Java
enum.
Points to remember for Java Enum
 Enum improves type safety
 Enum can be easily used in switch
 Enum can be traversed
 Enum can have fields, constructors and methods
 Enum may implement many interfaces but cannot extend any class because it internally
extends Enum class
Simple Example of Java Enum
class EnumExample1
{
public enum Season { WINTER, SPRING, SUMMER, FALL}
public static void main(String[] args)
{
for (Season s : Season.values())
System.out.println(s);
}
}
AUTOBOXING
The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing.
(OR)
Converting a primitive value into an object of the corresponding wrapper class is called
autoboxing.
For example, converting int to Integer class.
No need of conversion between primitives and Wrappers manually so less coding is required.
The following table lists the primitive types and their corresponding wrapper classes, which
are used by the Java compiler for autoboxing:

Simple Example of Autoboxing in java:


class BoxingExample
{
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
GENERICS IN JAVA
The Java Generics programming is introduced to deal with type-safe objects. It makes the code stable
by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics
force the java programmer to store a specific type of objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
Type-safety: We can hold only a single type of objects in generics. It doesnt allow to store other
objects.
Without Generics, we can store any type of objects.
List list = new ArrayList();
list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The
good programming strategy says it is far better to handle the problem at compile time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
Syntax to use generic collection
ClassOrInterface<Type>
Example to use Generics in java
ArrayList<String>

You might also like