0% found this document useful (0 votes)
24 views54 pages

Notes of Java Unit 4

Uploaded by

Sannat Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
24 views54 pages

Notes of Java Unit 4

Uploaded by

Sannat Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 54

Java I/O Tutorial

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
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with
the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

Let's see the code to print output and an error message to the console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character

OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:

OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.

Let's understand the working of Java OutputStream and InputStream by the figure given
below.

OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some
sink.

Useful methods of OutputStream

Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.

2) public void write(byte[])throws is used to write an array of byte to the current outpu
IOException stream.

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.

Java Stream Filter


Java stream provides a method filter() to filter stream elements on the basis of given
predicate. Suppose you want to get only even elements of your list then you can do this
easily with the help of filter method.

This method takes predicate as an argument and returns a stream of consisting of


resulted elements.

Signature
The signature of Stream filter() method is given below:

1. Stream<T> filter(Predicate<? super T> predicate)

Parameter
predicate: It takes Predicate reference as an argument. Predicate is a functional
interface. So, you can also pass lambda expression here.

Return
It returns a new stream.

Java Stream filter() example


In the following example, we are fetching and iterating filtered data.

1. import java.util.*;
2. class Product{
3. int id;
4. String name;
5. float price;
6. public Product(int id, String name, float price) {
7. this.id = id;
8. this.name = name;
9. this.price = price;
10. }
11. }
12. public class JavaStreamExample {
13. public static void main(String[] args) {
14. List<Product> productsList = new ArrayList<Product>();
15. //Adding Products
16. productsList.add(new Product(1,"HP Laptop",25000f));
17. productsList.add(new Product(2,"Dell Laptop",30000f));
18. productsList.add(new Product(3,"Lenevo Laptop",28000f));
19. productsList.add(new Product(4,"Sony Laptop",28000f));
20. productsList.add(new Product(5,"Apple Laptop",90000f));
21. productsList.stream()
22. .filter(p ->p.price> 30000) // filtering price
23. .map(pm ->pm.price) // fetching price
24. .forEach(System.out::println); // iterating price
25. }
26. }

Output:

90000.0
Java BufferedOutputStream Class
Java BufferedOutputStream class is used for buffering an output stream. It internally
uses buffer to store data. It adds more efficiency than to write data directly into a
stream. So, it makes the performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see
the syntax for adding the buffer in an OutputStream:

1. OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\


\testout.txt"));

Java BufferedOutputStream class


declaration
Let's see the declaration for Java.io.BufferedOutputStream class:

1. public class BufferedOutputStream extends FilterOutputStream

Java BufferedOutputStream class


constructors

Constructor Description

BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for writin
the data to the specified output stream.

BufferedOutputStream(OutputStream os, It creates the new buffered output stream which is used for writin
int size) the data to the specified output stream with a specified buffer siz
Java BufferedOutputStream class methods

Method Description

void write(int b) It writes the specified byte to the buffered output stream.

void write(byte[] b, int It write the bytes from the specified byte-input stream into a specifie
off, int len) byte array, starting with the given offset

void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:


In this example, we are writing the textual information in the BufferedOutputStream
object which is connected to the FileOutputStream object. The flush() flushes the data of
one stream and send it into another. It is required if you have connected the one stream
with another.

1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedOutputStreamExample{
4. public static void main(String args[])throws Exception{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. BufferedOutputStream bout=new BufferedOutputStream(fout);
7. String s="Welcome to javaTpoint.";
8. byte b[]=s.getBytes();
9. bout.write(b);
10. bout.flush();
11. bout.close();
12. fout.close();
13. System.out.println("success");
14. }
15. }
Output:

Success

testout.txt

Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file
behaves like a large array of bytes. There is a cursor implied to the array called
file pointer, by moving the cursor we do the read write operations. If end-of-file is
reached before the desired number of byte has been read than EOFException is thrown.
It is a type of IOException.

Constructor

Constructor Description

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

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

Method

Modifier Method Method


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 fil

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 o
this file, at which the next read or write occurs.

void writeDouble(double It converts the double argument to a long using th


v) doubleToLongBits method in class Double, and then writes tha
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 floatToIntBit
method in class Float, and then writes that int value to the fil
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 o
this file, at which the next read or write occurs.

Example
1. import java.io.IOException;
2. import java.io.RandomAccessFile;
3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }

The myFile.TXT contains text "This class is used for reading and writing to random access
file."

after running the program it will contains

This class is used for reading I love my country and my peoplele.

Java Database Connectivity


There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used
dynamically load the driver class.

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class


Here, Java program is loading oracle driver to esteblish database connection.
1. Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLException


2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

Example to establish connection with the Oracle database

1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object of statement
responsible to execute queries with the database.

Syntax of createStatement() method


1. public Statement createStatement()throws SQLException

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. This metho
returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query

1. ResultSet rs=stmt.executeQuery("select * from emp");


2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close() method
Connection interface is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException


Example to close connection

1. con.close();

Serialization and Deserialization in


Java
Serialization in Java is a mechanism of writing the state of an object into a byte-stream.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization where byte-stream is


converted into an object. The serialization and deserialization process is platform-
independent, it means you can serialize an object on one platform and deserialize it on
a different platform.

For serializing the object, we call the writeObject() method


of ObjectOutputStream class, and for deserialization we call the readObject() method
of ObjectInputStream class.

We must have to implement the Serializable interface for serializing the object.

Advantages of Java Serialization


It is mainly used to travel object's state on the network (that is known as marshalling).
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to
"mark" Java classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.

The Serializable interface must be implemented by the class whose object needs to be
persisted.

The String class and all the wrapper classes implement the java.io.Serializable interface
by default.

Let's see the example given below:

Student.java
1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

In the above example, Student class implements Serializable interface. Now its objects
can be converted into stream. The main class implementation of is showed in the next
code.

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 out) It creates an ObjectOutputStream that writes t


throws IOException {} the specified OutputStream.

Method Description

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

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

3) public void close() throws IOException {} It closes the current output stream.

ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
Constructor

1) public ObjectInputStream(InputStream in) throws It creates an ObjectInputStream that read


IOException {} from the specified InputStream.

Method Description

1) public final Object readObject() throws IOException, It reads an object from the input stream.
ClassNotFoundException{}

2) public void close() throws IOException {} It closes ObjectInputStream.

Example of Java Serialization


In this example, we are going to serialize the object of Student class from above code.
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.

1. import java.io.*;
2. class Persist{
3. public static void main(String args[]){
4. try{
5. //Creating the object
6. Student s1 =new Student(211,"ravi");
7. //Creating stream and writing the object
8. FileOutputStream fout=new FileOutputStream("f.txt");
9. ObjectOutputStream out=new ObjectOutputStream(fout);
10. out.writeObject(s1);
11. out.flush();
12. //closing the stream
13. out.close();
14. System.out.println("success");
15. }catch(Exception e){System.out.println(e);}
16. }
17. }

Output:
Success

Example of Java Deserialization


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

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

1. import java.io.*;
2. class Depersist{
3. public static void main(String args[]){
4. try{
5. //Creating stream to read the object
6. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
7. Student s=(Student)in.readObject();
8. //printing the data of the serialized object
9. System.out.println(s.id+" "+s.name);
10. //closing the stream
11. in.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

OUTPUT:-

211 Ravi

Java Serialization with Inheritance (IS-A


Relationship)
If a class implements Serializable interface then all its sub classes will also be
serializable. Let's see the example given below:
SerializeISA.java

1. import java.io.Serializable;
2. class Person implements Serializable{
3. int id;
4. String name;
5. Person(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }
10. class Student extends Person{
11. String course;
12. int fee;
13. public Student(int id, String name, String course, int fee) {
14. super(id,name);
15. this.course=course;
16. this.fee=fee;
17. }
18. }
19. public class SerializeISA
20. {
21. public static void main(String args[])
22. {
23. try{
24. //Creating the object
25. Student s1 =new Student(211,"ravi","Engineering",50000);
26. //Creating stream and writing the object
27. FileOutputStream fout=new FileOutputStream("f.txt");
28. ObjectOutputStream out=new ObjectOutputStream(fout);
29. out.writeObject(s1);
30. out.flush();
31. //closing the stream
32. out.close();
33. System.out.println("success");
34. }catch(Exception e){System.out.println(e);}
35. try{
36. //Creating stream to read the object
37. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
38. Student s=(Student)in.readObject();
39. //printing the data of the serialized object
40. System.out.println(s.id+" "+s.name+" "+s.course+" "+s.fee);
41. //closing the stream
42. in.close();
43. }catch(Exception e){System.out.println(e);}
44. }
45. }

Output:

success
211 ravi Engineering 50000

success

211 ravi Engineering 50000

Java Socket Class


The Socket class acts as an endpoint for communication between two machines. It
implements client sockets.

Methods

Method Description

bind(SocketAddress bindpoint) This method binds the given socket to the specified loca
address.
close() This method closes the socket.

connect(SocketAddress endpoint) The connect() method connects this socket to the serve
connect(SocketAddress endpoint, This method connects this socket to the server with a specifie
int timeout) timeout value.

getChannel() It returns a unique SocketChannel object associated with th


socket.

getInetAddress() It returns the address to which the socket is connected.

getInputStream() It returns an input stream for the specified socket.

getKeepAlive() This method tests if the SO_KEEPALIVE option is enabled or not.

getLocalAddress() It returns the local address to which the given socket is bound.

getLocalPort() It gets the local port number to which the specified socket
bound.

getLocalSocketAddress() This method gets the address of the endpoint to which th


socket is bound.

getOOBInline() This method tests whether the SO_OOBINLINE option is enable


or not.

getOutputStream() This method returns an output stream for the specified socket.

getPort() This method returns the remote port number to which the socke
is connected.

getReceiveBufferSize() It returns the value of the SO_RCVBUF option for this Socket.

getRemoteSocketAddress() This method either returns the address of the endpoint to whic
this socket is connected or it returns null if the socket
unconnected.

getReuseAddress() It tests whether the SO_REUSEADDR option is enabled or not.

getSendBufferSize() This method gets the value of the SO_SNDBUF option for th
Socket.
getSoLinger() This method returns setting for the SO_LINGER option.

getSoTimeout() It returns the setting for the SO_TIMEOUT option if it is enabled


else it returns 0 if the option is disabled.

getTcpNoDelay() This method tests whether the TCP_NODELAY option is enable


or not.

getTrafficClass() This method returns the traffic class or type-of-service in the I


header for packets sent from this Socket

isBound() It returns the binding state for this socket.

isClosed() This method returns the closed state of this socket.

isConnected() This method returns the connection state of the socket.

isInputShutdown() It returns whether the read-half of the socket connection


closed or not.

isOutputShutdown() It returns whether the write-half of the socket connection


closed or not.

sendUrgentData(int data) This method sends one byte of urgent data on the socket.

setKeepAlive(boolean on) This method enables or disables the SO_KEEPALIVE option fo


this socket.

setOOBInline(boolean on) This method enables or disables the SO_OOBINLINE option fo


this socket.

setReceiveBufferSize(int size) This method returns the SO_RCVBUF option to the specifie
value for this Socket.

setReuseAddress(boolean on) This method enables or disables the SO_REUSEADDR socke


option for this socket.

setSendBufferSize(int size) This method returns the SO_SNDBUF option to the specifie
value for this Socket.

setSoLinger(boolean on, int linger) It enables or disables the SO_LINGER option with the specifie
linger time in seconds.
setSoTimeout(int timeout) This method enables or disables the SO_TIMEOUT option wit
the specified time in milliseconds.

setTcpNoDelay(boolean on) This method enables or disables the TCP_NODELAY option fo


this socket.

setTrafficClass(int tc) It returns the traffic class or type-of-service octet in the IP heade
for packets sent from the Socket.

shutdownInput() This method places the input stream for this socket at the end o
this stream.

shutdownOutput() This method disables the output stream for this socket.

toString() This method converts this socket to a String.

Example 1
1. import java.io.IOException;
2. import java.net.*;
3. public class JavaSocketExample1 {
4. public static void main(String[] args) throws IOException {
5. Socket socket = new Socket();
6. InetAddress inetAddress=InetAddress.getByName("localhost");
7. //the port should be greater or equal to 0, else it will throw an error
8. int port=1085;
9. //calling the constructor of the SocketAddress class
10. SocketAddress socketAddress=new InetSocketAddress(inetAddress, port);
11. //binding the socket with the inetAddress and port number
12. socket.bind(socketAddress);
13. //connect() method connects the specified socket to the server
14. socket.connect(socketAddress);
15. //setSendBufferSize() sets the send buffer size or SO_SNDBUF option with the speci
fied value
16. socket.setSendBufferSize(67);
17. //getSendBufferSize() method returns the buffer size(SO_SNDBUF) used by the plat
form for output
18. System.out.println("Send Buffer size: "+socket.getSendBufferSize());
19. //enabling the boolean value true
20. boolean on=false;
21. //setKeepAlive() method either enables or disables the SO_KEEPALIVE option
22. socket.setKeepAlive(on);
23. //getKeepAlive() returns a boolean indicating whether SO_KEEPALIVE option is ena
bled or not
24. if(socket.getKeepAlive()){
25. System.out.println("SO_KEEPALIVE option is enabled");
26. }
27. else{
28. System.out.println("SO_KEEPALIVE option is disabled");
29. }
30. //getRemoteSocketAddress() returns the address of the endpoint of the specified s
ocket if the socket is connected
31. System.out.println("Remote socket address: "+socket.getRemoteSocketAddress());
32. }
33. }

OUTPUT:--

Send Buffer size: 67

SO_KEEPALIVE option is disabled

Remote socket address: localhost/127.0.0.1:1085

The Callback Sample Application


Throughout this topic, the Callback sample application is used to demonstrate the
development steps. The callback object in the joint client/server application has
a print_converted method, which accepts a string from the Simple object in the BEA WebLogic
Enterprise server application and prints the string in uppercase and lowercase letters.
Figure 3-1 How the Callback Sample Application Works

The source files for the Callback sample application are located in the WLEdir\samples\
corba\callback_java directory of the BEA WebLogic Enterprise software. See "Building and
Running the Callback Sample Application"" for more information.

Java Examples - Multithreaded Server


Multithreaded Server: A server having more than one thread is known as Multithreaded
Server. When a client sends the request, a thread is generated through which a user can
communicate with the server. We need to generate multiple threads to accept multiple requests
from multiple clients at the same time

Advantages of Multithreaded Server:


 Quick and Efficient: Multithreaded server could respond efficiently and
quickly to the increasing client queries quickly.
 Waiting time for users decreases: In a single-threaded server, other users
had to wait until the running process gets completed but in multithreaded
servers, all users can get a response at a single time so no user has to wait
for other processes to finish.
 Threads are independent of each other: There is no relation between any
two threads. When a client is connected a new thread is generated every
time.
 The issue in one thread does not affect other threads: If any error occurs
in any of the threads then no other thread is disturbed, all other processes
keep running normally. In a single-threaded server, every other client had to
wait if any problem occurs in the thread.
Disadvantages of Multithreaded Server:
 Complicated Code: It is difficult to write the code of the multithreaded
server. These programs can not be created easily
 Debugging is difficult: Analyzing the main reason and origin of the error is
difficult.

RMI (Remote Method Invocation)


The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM.

The RMI provides remote communication between the applications using two
objects stub and skeleton.

Understanding stub and skeleton


RMI uses stub and skeleton object for communication with the remote object.

A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:

stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When
the caller invokes method on the stub object, it does the following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does
the following tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

In the Java 2 SDK, an stub protocol was introduced that eliminates the need for
skeletons.
Understanding requirements for the
distributed applications
If any application performs these tasks, it can be distributed application.

.
1. The application need to locate the remote method
2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.

The RMI application have all these features, so it is called the distributed application.

Java RMI Example


The is given the 6 steps to write the RMI program.

1. Create the remote interface


2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using
the rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application

RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application.
The client application need only two files, remote interface and client application. In the
rmi application, both client and server interacts with the remote interface. The client
application invokes methods on the proxy object, RMI sends the request to the remote
JVM. The return value is sent back to the proxy object and then to the client application.
1) create the remote interface
For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface. Here, we are creating a
remote interface that extends the Remote interface. There is only one method named
add() and it declares RemoteException.

1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }

2) Provide the implementation of the remote


interface
Now provide the implementation of the remote interface. For providing the
implementation of the Remote interface, we need to

o Either extend the UnicastRemoteObject class,


o or use the exportObject() method of the UnicastRemoteObject class

how to call native function in java


To declare a native method, precede the method with the native modifier, but do not
define any body for the method. For example:

public native int meth() ;


After you declare a native method, you must write the native method and follow a
rather complex series of steps to link it with your Java code.

Most native methods are written in C. The mechanism used to integrate C code with
a Java program is called the Java Native Interface (JNI). This methodology was
created by Java 1.1 and then expanded and enhanced by Java 2. (Java 1.0 used a
different approach, which is now completely outdated.) A detailed description of the
JNI is beyond the scope of this book, but the following description provides sufficient
information for most applications.

Note: The precise steps that you need to follow will vary between different Java
environments and versions. This also depends on the language that you are using to
implement the native method. The following discussion assumes a Windows
95/98/NT environment. The language used to implement the native method is C.
The easiest way to understand the process is to work through an example. To begin,
enter the following short program, which uses a native method called test( ):

// A simple example that uses a native method.


Notice that the test( ) method is declared as native and has no body. This is the method
that we will implement in C shortly. Also notice the static block. As explained earlier in this
book, a static block is executed only once, when your program begins execution (or,more
precisely, when its class is first loaded). In this case, it is used to load the dynamic link
library that contains the native implementation of test( ). (You will see how to create this
library soon.)

The library is loaded by the loadLibrary( ) method, which is part of the System class. This is
its general form:

static void loadLibrary(String filename)


Here, filename is a string that specifies the name of the file that holds the library. For the
Windows 95/98/NT environment, this file is assumed to have the .DLL extension. After you
enter the program, compile it to produce NativeDemo.class. Next, you must use javah.exe
to produce one file: NativeDemo.h. (javah.exe is included in the JDK.) You will include
NativeDemo.h in your implementation of test( ). To produce NativeDemo.h, use the
following command:

javah -jni NativeDemo


This command produces a header file called NativeDemo.h. This file must be included in the
C file that implements test( ). The output produced by this command is shown here:

Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java

o It provides readymade architecture.


o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating
a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:

No Method Description
.

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean addAll(Collection<? It is used to insert the specified collection elements i


extends E> c) the invoking collection.

3 public boolean remove(Object It is used to delete an element from the collection.


element)
4 public boolean It is used to delete all the elements of the specifie
removeAll(Collection<?> c) collection from the invoking collection.

5 default boolean removeIf(Predicate<? It is used to delete all the elements of the collectio
super E> filter) that satisfy the specified predicate.

6 public boolean retainAll(Collection<? It is used to delete all the elements of invokin


> c) collection except the specified collection.

7 public int size() It returns the total number of elements in th


collection.

8 public void clear() It removes the total number of elements from th


collection.

9 public boolean contains(Object It is used to search an element.


element)

10 public boolean It is used to search the specified collection in th


containsAll(Collection<?> c) collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime typ
of the returned array is that of the specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collectio
as its source.

16 default Stream<E> stream() It returns a sequential Stream with the collection as it


source.

17 default Spliterator<E> spliterator() It generates a Spliterator over the specified element


in the collection.

18 public boolean equals(Object It matches two collections.


element)
19 public int hashCode() It returns the hash code number of the collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No Method Description
.

1 public boolean It returns true if the iterator has more elements otherwise it return
hasNext() false.

2 public Object next() It returns the element and moves the cursor pointer to the nex
element.

3 public void remove() It removes the last elements returned by the iterator. It is less used.

Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection
framework since Java 1.2. It is found in the java.util package and implements
the List interface, so we can use all the methods of List interface here.

It is recommended to use the Vector class in the thread-safe implementation only. If you
don't need to use the thread-safe implementation, you should use the ArrayList, the
ArrayList will perform better in such case.

The Iterators returned by the Vector class are fail-fast. In case of concurrent
modification, it fails and throws the ConcurrentModificationException.
It is similar to the ArrayList, but with two differences-

o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections
framework.

Java Vector class Declaration

1. public class Vector<E>


2. extends Object<E>
3. implements List<E>, Cloneable, Serializable

Java Vector Constructors


Vector class supports four types of constructors. These are given below:

S Constructor Description
N

1) vector() It constructs an empty vector with the default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the specified initia


capacity and with its capacity increment equal to zero.

3) vector(int initialCapacity, int It constructs an empty vector with the specified initia
capacityIncrement) capacity and capacity increment.

4) Vector( Collection<? extends E> It constructs a vector that contains the elements of
c) collection c.

Java Hashtable class


Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.

Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashcode() method. A Hashtable contains
values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.

Hashtable class declaration


Let's see the declaration for java.util.Hashtable class.

1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Clonea


ble, Serializable

Hashtable class Parameters


Let's see the Parameters for java.util.Hashtable class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors of Java Hashtable class

Constructor Description

Hashtable() It creates an empty hashtable having the initial default capacity and loa
factor.

Hashtable(int capacity) It accepts an integer parameter and creates a hash table that contains
specified initial capacity.

Hashtable(int capacity, float It is used to create a hash table having the specified initial capacity an
loadFactor) loadFactor.
Hashtable(Map<? extends K,? It creates a new hash table wiith the same mappings as the given Map.
extends V> t)

Methods of Java Hashtable class

Method Description

void clear() It is used to reset the hash table.

Object clone() It returns a shallow copy of the Hashtable.

V compute(K key, BiFunction<? super K,? It is used to compute a mapping for the specified key an
super V,? extends V> its current mapped value (or null if there is no curren
remappingFunction) mapping).

V computeIfAbsent(K key, Function<? It is used to compute its value using the given mappin
super K,? extends V> mappingFunction) function, if the specified key is not already associated wit
a value (or is mapped to null), and enters it into this ma
unless null.

V computeIfPresent(K key, BiFunction<? It is used to compute a new mapping given the key and it
super K,? super V,? extends V> current mapped value if the value for the specified key
remappingFunction) present and non-null.

Enumeration elements() It returns an enumeration of the values in the hash table.

Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in th


map.

boolean equals(Object o) It is used to compare the specified Object with the Map.

void forEach(BiConsumer<? super K,? It performs the given action for each entry in the map unt
super V> action) all entries have been processed or the action throws a
exception.

V getOrDefault(Object key, V It returns the value to which the specified key is mapped
defaultValue) or defaultValue if the map contains no mapping for th
key.
int hashCode() It returns the hash code value for the Map

Enumeration<K> keys() It returns an enumeration of the keys in the hashtable.

Set<K> keySet() It returns a Set view of the keys contained in the map.

V merge(K key, V value, BiFunction<? If the specified key is not already associated with a valu
super V,? super V,? extends V> or is associated with null, associates it with the given non
remappingFunction) null value.

V put(K key, V value) It inserts the specified value with the specified key in th
hash table.

void putAll(Map<? extends K,? extends It is used to copy all the key-value pair from map t
V> t)) hashtable.

V putIfAbsent(K key, V value) If the specified key is not already associated with a valu
(or is mapped to null) associates it with the given valu
and returns null, else returns the current value.

boolean remove(Object key, Object It removes the specified values with the associate
value) specified keys from the hashtable.

V replace(K key, V value) It replaces the specified value for a specified key.

boolean replace(K key, V oldValue, V It replaces the old value with the new value for a specifie
newValue) key.

void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invokin
super V,? extends V> function) the given function on that entry until all entries have bee
processed or the function throws an exception.

String toString() It returns a string representation of the Hashtable object.

Collection values() It returns a collection view of the values contained in th


map.

boolean contains(Object value) This method returns true if some value equal to the valu
exists within the hash table, else return false.

boolean containsValue(Object value) This method returns true if some value equal to the valu
exists within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key exist
within the hash table, else return false.

boolean isEmpty() This method returns true if the hash table is empt
returns false if it contains at least one key.

protected void rehash() It is used to increase the size of the hash table an
rehashes all of its keys.

V get(Object key) This method returns the object that contains the valu
associated with the key.

V remove(Object key) It is used to remove the key and its value. This metho
returns the value associated with the key.

int size() This method returns the number of entries in the has
table.

Java Stack
The stack is a linear data structure that is used to store the collection of objects. It is
based on Last-In-First-Out (LIFO). Java collection framework provides many interfaces
and classes to store the collection of objects. One of them is the Stack class that
provides different operations such as push, pop, search, etc.

In this section, we will discuss the Java Stack class, its methods, and implement the
stack data structure in a Java program. But before moving to the Java Stack class have a
quick view of how the stack works.

The stack data structure has the two most important operations that are push and pop.
The push operation inserts an element into the stack and pop operation removes an
element from the top of the stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.

Let's remove (pop) 18, 45, and 11 from the stack.


Empty Stack: If the stack has no element is known as an empty stack. When the stack is empty
the value of the top variable is -1.
When we push an element into the stack the top is increased by 1. In the following
figure,

o Push 12, top=0


o Push 6, top=1
o Push 9, top=2

Java Enums
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. It is
available since JDK 1.5.

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


o Enum improves type safety
o Enum can be easily used in switch
o Enum can be traversed
o Enum can have fields, constructors and methods
o Enum may implement many interfaces but cannot extend any class because it
internally extends Enum class
Simple Example of Java Enum
1. class EnumExample1{
2. //defining the enum inside the class
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4. //main method
5. public static void main(String[] args) {
6. //traversing the enum
7. for (Season s : Season.values())
8. System.out.println(s);
9. }}

Output:

Winter

Spring
Summer

Fall

Set in Java
The set is an interface available in the java.util package. The set interface extends the
Collection interface. An unordered collection or list in which duplicates are not allowed
is referred to as a collection interface. The set interface is used to create the
mathematical set. The set interface use collection interface's methods to avoid the
insertion of the same elements. SortedSet and NavigableSet are two interfaces that
extend the set implementation.

In the above diagram, the NavigableSet and SortedSet are both the interfaces.
The NavigableSet extends the SortedSet, so it will not retain the insertion order and store the
data in a sorted way.

SetExample1.java

1. import java.util.*;
2. public class setExample{
3. public static void main(String[] args)
4. {
5. // creating LinkedHashSet using the Set
6. Set<String> data = new LinkedHashSet<String>();
7.
8. data.add("JavaTpoint");
9. data.add("Set");
10. data.add("Example");
11. data.add("Set");
12.
13. System.out.println(data);
14. }
15. }

Output:

Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-
based methods to insert, update, delete and search the elements. It can have the
duplicate elements also. We can also store the null elements in the list.

The List interface is found in the java.util package and inherits the Collection interface. It
is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in
forward and backward directions. The implementation classes of List interface
are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are widely used
in Java programming. The Vector class is deprecated since Java 5.

List Interface declaration

1. public interface List<E> extends Collection<E>

Java List Methods

Method Description

void add(int index, E element) It is used to insert the specified element at the specified position in
a list.

boolean add(E e) It is used to append the specified element at the end of a list.

boolean addAll(Collection<? extends It is used to append all of the elements in the specified collection
E> c) to the end of a list.

boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection,
extends E> c) starting at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

boolean equals(Object o) It is used to compare the specified object with the elements of a
list.

int hashcode() It is used to return the hash code value for a list.

E get(int index) It is used to fetch the element from the particular position of the
list.

boolean isEmpty() It returns true if the list is empty, otherwise false.


int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.

Object[] toArray() It is used to return an array containing all of the elements in this
list in the correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this
list in the correct order.

boolean contains(Object o) It returns true if the list contains the specified element

boolean containsAll(Collection<?> c) It returns true if the list contains all the specified element

int indexOf(Object o) It is used to return the index in this list of the first occurrence of
the specified element, or -1 if the List does not contain this
element.

E remove(int index) It is used to remove the element present at the specified position
in the list.

boolean remove(Object o) It is used to remove the first occurrence of the specified element.

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.

void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the specified
operator) element.

void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the
specified collection.

E set(int index, E element) It is used to replace the specified element in the list, present at the
specified position.

void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of specified
comparator.
Spliterator<E> spliterator() It is used to create spliterator over the elements in a list.

List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the given range.
toIndex)

int size() It is used to return the number of elements present in the list.

Java Map Interface


A map contains values on the basis of key, i.e. key and value pair. Each key and value
pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy


There are two interfaces for implementing Map in java: Map and SortedMap, and three
classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given
below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.

A Map can't be traversed, so you need to convert it into Set


using keySet() or entrySet() method.

Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain any order.

LinkedHashMa LinkedHashMap is the implementation of Map. It inherits HashMap class.


p maintains insertion order.

TreeMap TreeMap is the implementation of Map and SortedMap. It maintains ascendin


order.

Iterator in Java
In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is
practiced in order to iterate over a collection of Java object components entirety one by
one. It is free to use in the Java programming language since the Java 1.2 Collection
framework. It belongs to java.util package.

Though Java Iterator was introduced in Java 1.2, however, it is still not the oldest tool
available to traverse through the elements of the Collection object. The oldest Iterator in
the Java programming language is the Enumerator predated Iterator. Java Iterator
interface succeeds the enumerator iterator that was practiced in the beginning to
traverse over some accessible collections like the ArrayLists.

The Java Iterator is also known as the universal cursor of Java as it is appropriate for all
the classes of the Collection framework. The Java Iterator also helps in the operations
like READ and REMOVE. When we compare the Java Iterator interface with the
enumeration iterator interface, we can say that the names of the methods available in
Java Iterator are more precise and straightforward to use.

Advantages of Java Iterator


Iterator in Java became very prevalent due to its numerous advantages. The advantages
of Java Iterator are given as follows -

o The user can apply these iterators to any of the classes of the Collection
framework.
o In Java Iterator, we can use both of the read and remove operations.
o If a user is working with a for loop, they cannot modernize(add/remove) the
Collection, whereas, if they use the Java Iterator, they can simply update the
Collection.
o The Java Iterator is considered the Universal Cursor for the Collection API.
o The method names in the Java Iterator are very easy and are very simple to use.

Disadvantages of Java Iterator


Despite the numerous advantages, the Java Iterator has various disadvantages also. The
disadvantages of the Java Iterator are given below -

o The Java Iterator only preserves the iteration in the forward direction. In simple
words, the Java Iterator is a uni-directional Iterator.
o The replacement and extension of a new component are not approved by the
Java Iterator.
o In CRUD Operations, the Java Iterator does not hold the various operations like
CREATE and UPDATE.
o In comparison with the Spliterator, Java Iterator does not support traversing
elements in the parallel pattern which implies that Java Iterator supports only
Sequential iteration.
o In comparison with the Spliterator, Java Iterator does not support more reliable
execution to traverse the bulk volume of data.

How to use Java Iterator?


When a user needs to use the Java Iterator, then it's compulsory for them to make an
instance of the Iterator interface from the collection of objects they desire to traverse
over. After that, the received Iterator maintains the trail of the components in the
underlying collection to make sure that the user will traverse over each of the elements
of the collection of objects.

If the user modifies the underlying collection while traversing over an Iterator leading to
that collection, then the Iterator will typically acknowledge it and will throw an exception
in the next time when the user will attempt to get the next component from the Iterator.
Java Iterator Methods
The following figure perfectly displays the class diagram of the Java Iterator interface. It
contains a total of four methods that are:

o hasNext()
o next()
o remove()
o forEachRemaining()

The forEachRemaining() method was added in the Java 8. Let's discuss each method in
detail.

o boolean hasNext(): The method does not accept any parameter. It returns true if
there are more elements left in the iteration. If there are no more elements left,
then it will return false.
If there are no more elements left in the iteration, then there is no need to call
the next() method. In simple words, we can say that the method is used to
determine whether the next() method is to be called or not.
o E next(): It is similar to hasNext() method. It also does not accept any parameter.
It returns E, i.e., the next element in the traversal. If the iteration or collection of
objects has no more elements left to iterate, then it throws the
NoSuchElementException.
o default void remove(): This method also does not require any parameters. There
is no return type of this method. The main function of this method is to remove
the last element returned by the iterator traversing through the underlying
collection. The remove () method can be requested hardly once per the next ()
method call. If the iterator does not support the remove operation, then it throws
the UnSupportedOperationException. It also throws the IllegalStateException if
the next method is not yet called.
o default void forEachRemaining(Consumer action): It is the only method of
Java Iterator that takes a parameter. It accepts action as a parameter. Action is
nothing but that is to be performed. There is no return type of the method. This
method performs the particularized operation on all of the left components of
the collection until all the components are consumed or the action throws an
exception. Exceptions thrown by action are delivered to the caller. If the action is
null, then it throws a NullPointerException.

You might also like