Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Unit-Ii Notes

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

UNIT II

PACKAGES
In java, a package is a container of classes, interfaces, and sub-packages. We may think of it as a folder in a
file directory.

We use the packages to avoid naming conflicts and to organize project-related classes, interfaces, and sub-
packages into a bundle.

In java, the packages have divided into two types.

 Built-in Packages
 User-defined Packages

Built-in Packages

The built-in packages are the packages from java API. The Java API is a library of pre-defined classes,
interfaces, and sub-packages. The built-in packages were included in the JDK.

There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax, swing, net, sql,
etc.

We need to import the built-in packages to use them in our program. To import a package, we use the import
statement.

User-defined Packages

The user-defined packages are the packages created by the user. User is free to create their own packages.

DEFINIG A PACKAGE

We use the package keyword to create or define a package in java programming language.

Syntax

package packageName;

The package statement must be the first statement in the program.

The package name must be a single word.

The package name must use Camel case notation.

Example

package myPackage;

public class DefiningPackage {


public static void main(String[] args) {

System.out.println("This class belongs to myPackage.");

Now, save the above code in a file DefiningPackage.java, and compile it using the following command.

CLASSPATH

javac -d . DefiningPackage.java

The above command creates a directory with the package name myPackage, and the DefiningPackage.class
is saved into it.

Run the program use the following command.

java myPackage.DefiningPackage

When we use IDE like Eclipse, Netbeans, etc. the package structure is created automatically.

ACCESS PROTECTION

In java, the access modifiers define the accessibility of the class and its members. For example, private
members are accessible within the same class members only. Java has four access modifiers, and they are
default, private, protected, and public.

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.
The public members can be accessed everywhere.

The private members can be accessed only inside the same class.

The protected members are accessible to every child class (same package or other packages).

The default members are accessible within the same package but not outside the package.

Example

class ParentClass{

int a = 10;

public int b = 20;

protected int c = 30;

private int d = 40;

void showData() {

System.out.println("Inside ParentClass");

System.out.println("a = " + a);

System.out.println("b = " + b);

System.out.println("c = " + c);

System.out.println("d = " + d);

class ChildClass extends ParentClass{

void accessData() {

System.out.println("Inside ChildClass");

System.out.println("a = " + a);

System.out.println("b = " + b);

System.out.println("c = " + c);

//System.out.println("d = " + d); // private member can't be accessed

}
}

public class AccessModifiersExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

obj.showData();

obj.accessData();

IMPORTING PACKAGES

In java, the import keyword used to import built-in and user-defined packages. When a package has
imported, we can refer to all the classes of that package using their name directly.

The import statement must be after the package statement, and before any other statement.

Using an import statement, we may import a specific class or all the classes from a package.

🔔 Using one import statement, we may import only one package or a class.

🔔 Using an import statement, we can not import a class directly, but it must be a part of a package.

🔔 A program may contain any number of import statements.

Importing specific class

Using an importing statement, we can import a specific class. The following syntax is employed to import a
specific class.

Syntax
import packageName.ClassName;

Example

package myPackage;

import java.util.Scanner;

public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);

In the above code, the class ImportingExample belongs to myPackage package, and it also importing a class
called Scanner from java.util package.

Importing all the classes


Using an importing statement, we can import all the classes of a package. To import all the classes of the
package, we use * symbol. The following syntax is employed to import all the classes of a package.

Syntax

import packageName.*;

INTERFACE:

An interface is similar to a class, but it contains abstract methods and static final variables only. The interface
in Java is another mechanism to achieve abstraction.

We may think of an interface as a completely abstract class. None of the methods in the interface has an
implementation, and all the variables in the interface are constants.

All the methods of an interface, implemented by the class that implements it.

The interface in java enables java to support multiple-inheritance. An interface may extend only one
interface, but a class may implement any number of interfaces.

🔔 An interface is a container of abstract methods and static final variables.


🔔 An interface, implemented by a class. (class implements interface).

🔔 An interface may extend another interface. (Interface extends Interface).

🔔 An interface never implements another interface, or class.

🔔 A class may implement any number of interfaces.

🔔 We can not instantiate an interface.

🔔 Specifying the keyword abstract for interface methods is optional, it automatically added.

🔔 All the members of an interface are public by default.

Defining an interface in java

Defining an interface is similar to that of a class. We use the keyword interface to define an interface. All the
members of an interface are public by default. The following is the syntax for defining an interface.

Syntax

interface InterfaceName{

...

members declaration;

...

Example

interface HumanInterfaceExample {

void learn(String str);

void work();

int duration = 10;

In the above code defines an interface HumanInterfaceExample that contains two abstract methods learn(),
work() and one constant duration.

Every interface in Java is auto-completed by the compiler. For example, in the above example code, no
member is defined as public, but all are public automatically.

The above code automatically converted as follows.


Converted code

interface HumanInterfaceExample {

public abstract void learn(String str);

public abstract void work();

public static final int duration = 10;

IMPLEMENTING AN INTERFACE

An interface is implemented by a class. The class that implements an interface must provide code for all the
methods defined in the interface, otherwise, it must be defined as an abstract class.

The class uses a keyword implements to implement an interface. A class can implement any number of
interfaces. When a class wants to implement more than one interface, we use the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class.

Syntax

class className implements InterfaceName{

...

boby-of-the-class

...

Example

interface Human {

void learn(String str);

void work();

int duration = 10;

class Programmer implements Human{

public void learn(String str) {

System.out.println("Learn using " + str);


}

public void work() {

System.out.println("Develop applications");

public class HumanTest {

public static void main(String[] args) {

Programmer trainee = new Programmer();

trainee.learn("coding");

trainee.work();

In the above code defines an interface Human that contains two abstract methods learn(), work() and one
constant duration. The class Programmer implements the interface. As it implementing the Human interface
it must provide the body of all the methods those defined in the Human interface.

Implementing multiple Interfaces

When a class wants to implement more than one interface, we use the implements keyword is followed by a
comma-separated list of the interfaces implemented by the class.

Syntax

class className implements InterfaceName1, InterfaceName2, ...{

...

boby-of-the-class

...

Example

interface Human {

void learn(String str);


void work();

interface Recruitment {

boolean screening(int score);

boolean interview(boolean selected);

class Programmer implements Human, Recruitment {

public void learn(String str) {

System.out.println("Learn using " + str);

public boolean screening(int score) {

System.out.println("Attend screening test");

int thresold = 20;

if(score > thresold)

return true;

return false;

public boolean interview(boolean selected) {

System.out.println("Attend interview");

if(selected)

return true;

return false;

public void work() {

System.out.println("Develop applications");

}
}

public class HumanTest {

public static void main(String[] args) {

Programmer trainee = new Programmer();

trainee.learn("Coding");

trainee.screening(30);

trainee.interview(true);

trainee.work();

NESTED INTERFACES

An interface may be defined inside another interface, and also inside a class. The interface that defined inside
another interface or a class is known as nested interface. The nested interface is also refered as inner
interface.

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

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.

Nested interface inside another interface

The nested interface that defined inside another interface must be accessed as OuterInterface.InnerInterface.

Let's look at an example code to illustrate nested interfaces inside another interface.
Example

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

}
Nested interface inside a class

The nested interface that defined inside a class must be accessed as ClassName.InnerInterface.

Example

class OuterClass{

interface InnerInterface{

void innerMethod();

class ImplementingClass implements OuterClass.InnerInterface{

public void innerMethod() {

System.out.println("This is InnerInterface method");

public class NestedInterfaceExample {

public static void main(String[] args) {

ImplementingClass obj = new ImplementingClass();

obj.innerMethod();

}
VARIABLES IN JAVA INTERFACES

An interface is a completely abstract class. An interface is a container of abstract methods and static final
variables. The interface contains the static final variables. The variables defined in an interface can not be
modified by the class that implements the interface, but it may use as it defined in the interface.

🔔 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 can not modify the interface variable, but it may use as it defined in
the interface.

Example

interface SampleInterface{

int UPPER_LIMIT = 100;

//int LOWER_LIMIT; // Error - must be initialised

public class InterfaceVariablesExample implements SampleInterface{

public static void main(String[] args) {

System.out.println("UPPER LIMIT = " + UPPER_LIMIT);

// UPPER_LIMIT = 150; // Can not be modified

EXTENDING AN INTERFACE

An interface can extend another interface. When an interface wants to extend another interface, it uses the
keyword extends. The interface that extends another interface has its own members and all the members
defined in its parent interface too. The class which implements a child interface needs to provide code for the
methods defined in both child and parent interfaces, otherwise, it needs to be defined as abstract class.
🔔 An interface can extend another interface.

🔔 An interface can not extend multiple interfaces.

🔔 An interface can implement neither an interface nor a class.

🔔 The class that implements child interface needs to provide code for all the methods defined in both child
and parent interfaces.

Example

interface ParentInterface{

void parentMethod();

interface ChildInterface extends ParentInterface{

void childMethod();

class ImplementingClass implements ChildInterface{

public void childMethod() {

System.out.println("Child Interface method!!");

public void parentMethod() {

System.out.println("Parent Interface mehtod!");

public class ExtendingAnInterface {

public static void main(String[] args) {

ImplementingClass obj = new ImplementingClass();

obj.childMethod();

obj.parentMethod();

}
}

STREAM BASED I/O


STREAM

In java, the IO operations are performed using the concept of streams. Generally, a stream means a
continuous flow of data. In java, a stream is a logical container of data that allows us to read from and write
to it. A stream can be linked to a data source, or data destination, like a console, file or network connection
by java IO system. The stream-based IO operations are faster than normal IO operations.

The Stream is defined in the java.io package.

To understand the functionality of java streams, look at the following picture.

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.

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.
Both character and byte streams essentially provides a convenient and efficient way to handle data streams in
Java.

BYTE STREAM

the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8 bits of data.

In Java 1.0 version all IO operations were byte oriented, there was no other stream (character stream).

Byte stream is 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.
InputStream class

The InputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.

OutputStream class

The OutputStream class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.

Reading data using BufferedInputStream

We can use the BufferedInputStream class to read data from the console. The BufferedInputStream class use
a method read( ) to read a value from the console, or file, or socket.

Example 1 - Reading from console

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {


BufferedInputStream read = new BufferedInputStream(System.in);

try {

System.out.print("Enter any character: ");

char c = (char)read.read();

System.out.println("You have entered '" + c + "'");

catch(Exception e) {

System.out.println(e);

finally {

read.close();

Example 2 - Reading from a file

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {

FileInputStream fileInputStream = new FileInputStream(new File("d:\\chaitanya\\Sample.txt"));

BufferedInputStream input = new BufferedInputStream(fileInputStream);

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 data using BufferedOutputStream

We can use the BufferedOutputStream class to write data into the console, file, socket. The
BufferedOutputStream class use a method write( ) to write data.

Example - Writing data into a file

import java.io.*;

public class WritingDemo {

public static void main(String[] args) throws IOException {

String data = "Java tutorials by BTech Smart Class";

BufferedOutputStream out = null;

try {

FileOutputStream fileOutputStream = new FileOutputStream(new File("d:\\chaitanya\\Sample.txt"));

out = new BufferedOutputStream(fileOutputStream);

out.write(data.getBytes());

System.out.println("Writing data into a file is success!");

catch(Exception e) {

System.out.println(e);
}

finally {

out.close();

CHARACTER STREAM

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 character stream was introduced in Java 1.1 version. The charater stream

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.
Reader class

The Reader class has defined as an abstract class, and it has the following methods which have implemented
by its concrete classes.

Writer class

The Writer class has defined as an abstract class, and it has the following methods which have implemented
by its concrete classes.
Reading data using BufferedReader

We can use the BufferedReader class to read data from the console. The BufferedInputStream class needs
InputStreamReaderclass. The BufferedReader use a method read( ) to read a value from the console, or file,
or socket.

Example 1 - Reading from console

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader in = new BufferedReader(isr);

String name = "";

System.out.print("Please enter your name: ");

name = in.readLine();

System.out.println("Hello, " + name + "!");

}
Example 2 - Reading from a file

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) throws IOException {

Reader in = new FileReader();

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 data using FileWriter

We can use the FileWriter class to write data into the file. The FileWriter class use a method write( ) to write
data.

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:\\Raja\\dataFile.txt");

String msg = "The sample data";


try {

out.write(msg);

System.out.println("Writing done!!!");

catch(Exception e) {

System.out.println(e);

finally {

out.close();

CONSOLE IO OPERATIONS

Reading console input


There are three ways to read console input. Using the 3 following ways, we can read input data from the
console.

 Using BufferedReader class


 Using Scanner class
 Using Console class

1. Reading console input 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.

Example

import java.io.*;

public class ReadingDemo {


public static void main(String[] args) throws IOException {

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

String name = "";

try {

System.out.print("Please enter your name : ");

name = in.readLine();

System.out.println("Hello, " + name + "!");

catch(Exception e) {

System.out.println(e);

finally {

in.close();

2. Reading console input using Scanner class

Reading input data using the Scanner class is the most commonly used method. This way of the reading
method is used by wrapping the System.in (standard input stream) which is wrapped in a Scanner, we can
read input from the console.

The Scanner class has defined in the java.util package.


Example

import java.util.Scanner;

public class ReadingDemo {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

String name = "";

System.out.print("Please enter your name : ");

name = in.next();

System.out.println("Hello, " + name + "!");

3. Reading console input using Console class


Reading input data using the Console class is the most commonly used method. This class was introduced in
Java 1.6 version.

The Console class has defined in the java.io package.

Example

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) {

String name;

Console con = System.console();

if(con != null) {

name = con.readLine("Please enter your name : ");


System.out.println("Hello, " + name + "!!");

else {

System.out.println("Console not available.");

Writing console output

In java, there are two methods to write console output. Using the 2 following methods, we can write output
data to the console.

 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 separete line (new line). This method can be used with
console ans 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 accept 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 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.


The File class in java has the following methods.
Example

import java.io.*;

public class FileClassTest {

public static void main(String args[]) {

File f = new File("C:\\Raja\\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());

//f.createNewFile()
//f.delete();

//f.setReadOnly()

The following java code to list all the files in a directory including the files present in all its subdirectories.

Example

import java.util.Scanner;

import java.io.*;

public class ListingFiles {

public static void main(String[] args) {

String path = null;

Scanner read = new Scanner(System.in);

System.out.print("Enter the root directory name: ");

path = read.next() + ":\\";

File f_ref = new File(path);

if (!f_ref.exists()) {

printLine();

System.out.println("Root directory does not exists!");

printLine();

} else {

String ch = "y";

while (ch.equalsIgnoreCase("y")) {

printFiles(path);

System.out.print("Do you want to open any sub-directory (Y/N): ");

ch = read.next().toLowerCase();

if (ch.equalsIgnoreCase("y")) {
System.out.print("Enter the sub-directory name: ");

path = path + "\\\\" + read.next();

File f_ref_2 = new File(path);

if (!f_ref_2.exists()) {

printLine();

System.out.println("The sub-directory does not exists!");

printLine();

int lastIndex = path.lastIndexOf("\\");

path = path.substring(0, lastIndex);

System.out.println("***** Program Closed *****");

public static void printFiles(String path) {

System.out.println("Current Location: " + path);

File f_ref = new File(path);

File[] filesList = f_ref.listFiles();

for (File file : filesList) {

if (file.isFile())

System.out.println("- " + file.getName());

else

System.out.println("> " + file.getName());

}
public static void printLine() {

System.out.println("----------------------------------------");

FILE READING & WRITING

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.

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:\\Raja\\Input-File.txt");

out = new FileOutputStream("C:\\Raja\\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.

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:\\Raja\\Input-File.txt");

out = new FileWriter("C:\\Raja\\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

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.

Random Access File Constructors

The Random Access File class in java has the following constructors.

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.

Random Access File methods

The Random Access File class in java has the following methods.
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:\\Raja\\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.io package has a built-in class Console used to read from and write to the console, if one exists.
This class was added to the Java SE 6. The Console class implements teh Flushable interface.

In java, most the input functionalities of Console class available through System.in, and the output
functionalities available through System.out.

Console class Constructors

The Console class does not have any constructor. We can obtain the Console class object by calling
System.console().

Console class methods

The Console class in java has the following methods.


The following example program for reading a string using Console class.

Example

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) {

String name;

Console con = System.console();

if(con != null) {

name = con.readLine("Please enter your name : ");

System.out.println("Hello, " + name + "!!");

else {

System.out.println("Console not available.");

}
The following example program for writing to the console using Console class.

Example

import java.io.*;

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

SERIALIZATION AND DESERIALIZATION


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 deserialization is reverse of serialization. The deserialization
is the process of reconstructing the object from the serialized state.

Using serialization and deserialization, we can transfer the Object Code from one Java Virtual machine to
another.

Serialization

The Serialization is achieved with the help of interface Serializable. The class whose object needs to be
serialized must implement the Serializable interface.

We use the ObjectOutputStream class to write a serialized object to write to a destination. The
ObjectOutputStream class provides a method writeObject() to serializing an object.

We use the following steps to serialize an object.

 Step 1 - Define the class whose object needs to be serialized; it must implement Serializable
interface.
 Step 2 - Create a file reference with file path using FileOutputStream class.
 Step 3 - Create reference to ObjectOutputStream object with file reference.
 Step 4 - Use writeObject(object) method by passing the object that wants to be serialized.
 Step 5 - Close the FileOutputStream and ObjectOutputStream.

Example

import java.io.*;

public class SerializationExample {

public static void main(String[] args) {

Student stud = new Student();

stud.studName = "Rama";

stud.studBranch = "IT";

try {

FileOutputStream fos = new FileOutputStream("my_data.txt");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(stud);

oos.close();

fos.close();

System.out.println("The object has been saved to my_data file!");

catch(Exception e) {

System.out.println(e);

}
Deserialization

The Deserialization is achieved with the help of class ObjectInputStream. This class provides a method
readObject() to deserializing an object.

We use the following steps to serialize an object.

 Step 1 - Create a file reference with file path in which serialized object is available using
FileInputStream class.
 Step 2 - Create reference to ObjectInputStream object with file reference.
 Step 3 - Use readObject() method to access serialized object, and typecaste it to destination
type.
 Step 4 - Close the FileInputStream and ObjectInputStream.

Example

import java.io.*;

public class DeserializationExample {

public static void main(String[] args) throws Exception{

try {

FileInputStream fis = new FileInputStream("my_data.txt");

ObjectInputStream ois = new ObjectInputStream(fis);

Student stud2 = (Student) ois.readObject();

System.out.println("The object has been deserialized.");

fis.close();

ois.close();

System.out.println("Name = " + stud2.studName);

System.out.println("Department = " + stud2.studBranch);

catch(Exception e) {

System.out.println(e);

}
ENUMERATION

In java, an Enumeration is a list of named constants. The enum concept was introduced in Java SE 5 version.
The enum in Java programming the concept of enumeration is greatly expanded with lot more new features
compared to the other languages like C, and C++.

In java, the enumeration concept was defined based on the class concept. When we create an enum in java, it
converts into a class type. This concept enables the java enum to have constructors, methods, and instance
variables.

All the constants of an enum are public, static, and final. As they are static, we can access directly using
enum name.

The main objective of enum is to define our own data types in Java, and they are said to be enumeration data
types.

Creating enum in Java

To create enum in Java, we use the keyword enum. The syntax for creating enum is similar to that of class.

In java, an enum can be defined outside a class, inside a class, but not inside a method.

Example

enum WeekDay{

MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

public class EnumerationExample {

public static void main(String[] args) {

WeekDay day = WeekDay.FRIDAY;

System.out.println("Today is " + day);

System.out.println("\nAll WeekDays: ");

for(WeekDay d:WeekDay.values())

System.out.println(d);
}

🔔 Every enum is converted to a class that extends the built-in class Enum.

🔔 Every constant of an enum is defined as an object.

🔔 As an enum represents a class, it can have methods, constructors. It also gets a few extra methods from the
Enum class, and one of them is the values() method.

Constructors enum

In a java programming language, an enum can have both the type of constructors default and parameterized.
The execution of constructor depends on the constants we defined in the enum. For every constant in an
enum, the constructor is executed.

If an enum has a parameterized constructor, the parameter value should be passed when we define constant.

Example

enum WeekDay{

MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,


SUNDAY("Holiday");

String msg;

WeekDay(){

System.out.println("Default constructor!");

WeekDay(String str){

System.out.println("Parameterized constructor!");
msg = str;

public class EnumerationExample {

public static void main(String[] args) {

WeekDay day = WeekDay.SUNDAY;

System.out.println("\nToday is " + day + " and its " + day.msg);

n the above example, the constant SUNDAY is created by calling the parameterized constructor, other
constants created by calling default constructor.

Methods enum

In a java programming language, an enum can have methods. These methods are similar to the methods of a
class. All the methods defined in an enum can be used with all the constants defined by the same enum.

Example

enum WeekDay{

MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,


SUNDAY("Holiday");

String msg;

WeekDay(){

System.out.println("Default constructor!");
}

WeekDay(String str){

System.out.println("Parameterized constructor!");

msg = str;

void printMessage() {

System.out.println("Today is also " + msg);

public class EnumerationExample {

public static void main(String[] args) {

WeekDay day = WeekDay.SUNDAY;

System.out.println("\nToday is " + day);

day.printMessage();

🔔 enum can not extend another enum and a class.

🔔 enum can implement interfaces.

🔔 enum does not allow to create an object of it.

🔔 Every enum extends a built-in class Enum by default.


AUTOBOXING AND UNBOXING

All the primitive data types have defined using the class concept, these classes known as wrapper classes. In
java, every primitive type has its corresponding wrapper class.

All the wrapper classes in Java were defined in the java.lang package.

The following table shows the primitive type and its corresponding wrapper class.

The Java 1.5 version introduced a concept that converts primitive type to corresponding wrapper type and
reverses of it.

Autoboxing

The process of converting a primitive type value into its corresponding wrapper class object is called
autoboxing or simply boxing. For example, converting an int value to an Integer class object.

The compiler automatically performs the autoboxing when a primitive type value has assigned to an object of
the corresponding wrapper class.

We can also perform autoboxing manually using the method valueOf( ), which is provided by every wrapper
class.

Example - Autoboxing

import java.lang.*;

public class AutoBoxingExample {

public static void main(String[] args) {


// Auto boxing : primitive to Wrapper

int num = 100;

Integer i = num;

Integer j = Integer.valueOf(num);

System.out.println("num = " + num + ", i = " + i + ", j = " + j);

Auto un-boxing

The process of converting an object of a wrapper class type to a primitive type value is called auto un-boxing
or simply unboxing. For example, converting an Integer object to an int value.

The compiler automatically performs the auto un-boxing when a wrapper class object has assigned to
aprimitive type.

We can also perform auto un-boxing manually using the method intValue( ), which is provided by Integer
wrapper class. Similarly every wrapper class has a method for auto un-boxing.

Example - Auto unboxing

import java.lang.*;

public class AutoUnboxingExample {

public static void main(String[] args) {

// Auto un-boxing : Wrapper to primitive

Integer num = 200;

int i = num;

int j = num.intValue();

System.out.println("num = " + num + ", i = " + i + ", j = " + j);

}
GENERICS

The java generics is a language feature that allows creating methods and class which can handle any type of
data values. The generic programming is a way to write generalized programs, java supports it by java
generics.

The java generics is similar to the templates in the C++ programming language.

🔔 Most of the collection framework classes are generic classes.

🔔 The java generics allows only non-primitive type, it does not support primitive types like int, float, char,
etc.

The java generics feature was introduced in Java 1.5 version. In java, generics used angular brackets “< >”.
In java, the generics feature implemented using the following.

 Generic Method
 Generic Classes

Generic methods

Generics allows creating generic methods which can work with a different type of data values.

Using a generic method, we can create a single method that can be called with arguments of different types.
Based on the types of the arguments passed to the generic method, the compiler handles each method call
appropriately.

Example - Generic method

public class GenericFunctions {

public <T, U> void displayData(T value1, U value2) {

System.out.println("(" + value1.getClass().getName() + ", " + value2.getClass().getName() +


")");

public static void main(String[] args) {

GenericFunctions obj = new GenericFunctions();

obj.displayData(45.6f, 10);

obj.displayData(10, 10);

obj.displayData("Hi", 'c');

}
In the above example code, the method displayData( ) is a generic method that allows a different type of
parameter values for every function call.

Generic Class

A class can be defined as a generic class that allows creating a class that can work with different types.

A generic class declaration looks like a non-generic class declaration, except that the class name is followed
by a type parameter section.

Example - Generic class

public class GenericsExample<T> {

T obj;

public GenericsExample(T anotherObj) {

this.obj = anotherObj;

public T getData() {

return this.obj;

public static void main(String[] args) {

GenericsExample<Integer> actualObj1 = new GenericsExample<Integer>(100);

System.out.println(actualObj1.getData());

GenericsExample<String> actualObj2 = new GenericsExample<String>("Java");

System.out.println(actualObj2.getData());

GenericsExample<Float> actualObj3 = new GenericsExample<Float>(25.9f);

System.out.println(actualObj3.getData());

You might also like