Javafullnotes
Javafullnotes
UNIT I
Overview and characteristics of Java, Java program Compilation and Execution Process Organization of the Java Virtual
Machine, JVM as an interpreter and emulator, Instruction Set, class File Format, Verification, Class Area, Java Stack, Heap,
Garbage Collection. Security Promises of the JVM, Security Architecture and Security Policy. Class loaders and security aspects,
sandbox model [T1,R2][No. of Hrs.: 11]
UNIT II
Java Fundamentals, Data Types & Literals Variables, Wrapper Classes, Arrays, Arithmetic Operators, Logical Operators, Control
of Flow, Classes and Instances, Class Member Modifiers Anonymous Inner Class Interfaces and Abstract Classes, inheritance,
throw and throws clauses, user defined Exceptions, The String Buffer Class, tokenizer, applets, Life cycle of applet and Security
concerns. [T1,T2][No. of Hrs.: 12]
UNIT III
Threads: Creating Threads, Thread Priority, Blocked States, Extending Thread Class, Runnable Interface, Starting Threads,
Thread Synchronization, Synchronize Threads, Sync Code Block, Overriding Synced Methods, Thread Communication, wait,
notify and notify all.AWT Components, Component Class, Container Class, Layout Manager Interface Default Layouts, Insets
and Dimensions, Border Layout, Flow Layout, Grid Layout, Card Layout Grid Bag Layout AWT Events, Event Models,
Listeners, Class Listener, Adapters, Action Event Methods Focus Event Key Event, Mouse Events, Window Event
[T2][No. of Hrs.: 11]
UNIT IV
Input/Output Stream, Stream Filters, Buffered Streams, Data input and Output Stream, Print Stream Random Access File, JDBC
(Database connectivity with MS-Access, Oracle, MS-SQL Server), Object serialization, Sockets, development of client Server
applications, design of multithreaded server. Remote Method invocation, Java Native interfaces, Development of a JNI based
application. Collection API Interfaces, Vector, stack, Hashtable classes, enumerations, set, List, Map, Iterators. [T1][R1][No. of
Hrs.: 10]
Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code understand
the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
These two abstract classes have several concrete classes that handle various devices such as
disk files, network connection etc.
Some important Byte stream classes.
These classes define several key methods. Two most important are
These two abstract classes have several concrete classes that handle unicode character ( The
Unicode standard uses hexadecimal to express a character. For example, the value 0x0041
represents the Latin character A. ).
import java.io.*;
class CopyFile
{
public static void main(String[] args)
{
try
{
FileReader fr=new FileReader("Data.txt");
FileWriter fw=new FileWriter("Copy.txt");
int i=0;
while((i=fr.read())!=-1)
{
fw.write(i);
}
fw.flush();
fw.close();
fr.close();
System.out.println("Copied sucessfully..");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OR
Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns
integer type value has we need to use typecasting to convert it into char type.
import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}
Program to read from a file using BufferedReader class
import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream
in the java.io package supports many data such as primitives, object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
● InPutStream − The InputStream is used to read data from a source.
● OutPutStream − The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an
input file into an output file −
Example
import java.io.*;
public class CopyFile {
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file
and do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here the major difference is that FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −
Example
import java.io.*;
public class CopyFile {
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file
and do the following −
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. If you are aware
of C or C++ programming languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similarly, Java provides the following three standard streams −
● Standard Input − This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
● Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented as
System.out.
● Standard Error − This is used to output the error data produced by the user's program and
usually a computer screen is used for standard error stream and represented as
System.err.
Following is a simple program, which creates InputStreamReader to read standard input stream
until the user types a "q" −
Example
import java.io.*;
public class ReadConsole {
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown in
the following program. This program continues to read and output the same character until we
press 'q' −
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword
new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file
−
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
This method closes the file output stream. Releases any system
resources associated with the file. Throws an IOException.
This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.
This method reads the specified byte of data from the InputStream.
Returns an int. Returns the next byte of data and -1 will be returned if it's
the end of the file.
4
public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array.
Returns the total number of bytes read. If it is the end of the file, -1 will
be returned.
5
public int available() throws IOException{}
Gives the number of bytes that can be read from this file input stream.
Returns an int.
There are other important input streams available, for more detail you can refer to the following
links −
● ByteArrayInputStream
● DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a
file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.
This method closes the file output stream. Releases any system
resources associated with the file. Throws an IOException.
This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.
3
public void write(int w)throws IOException{}
There are other important output streams available, for more detail you can refer to the following
links −
● ByteArrayOutputStream
● DataOutputStream
Example
Following is the example to demonstrate InputStream and OutputStream −
import java.io.*;
public class fileStreamTest {
try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();
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.
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.
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");
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.
Method Description
IOException stream.
IOException
IOException
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream
of bytes.
Method Description
1) public abstract int reads the next byte of data from the input stream. It
IOException
IOException
InputStream Hierarchy
If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutputStream.
protected void finalize() It is used to clean up the connection with the file output
stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the
void write(byte[] ary, It is used to write len bytes from the byte array starting at
int off, int len) offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel It is used to return the file channel object associated with the
FileDescriptor getFD() It is used to return the file descriptor associated with the
stream.
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
Output:
Success...
The content of a text file testout.txt is set with the data Welcome to javaTpoint.
testout.txt
Welcome to javaTpoint.
int available() It is used to return the estimated number of bytes that can be read
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.
int read(byte[] b, It is used to read up to len bytes of data from the input stream.
long skip(long x) It is used to skip over and discards x bytes of data from the input
stream.
FileChannel It is used to return the unique FileChannel object associated with
getFD()
protected void It is used to ensure that the close method is call when there is no
Note: Before running the code, a text file named as "testout.txt" is required to be created. In this
file, we are having following content:
Welcome to javatpoint.
After executing the above program, you will get a single character from the file which is 87 (in byte
form). To see the text, you need to convert it into character.
Output:
W
Java FileInputStream example 2: read all characters
1. package com.javatpoint;
2.
3. import java.io.FileInputStream;
4. public class DataStreamExample {
5. public static void main(String args[]){
6. try{
7. FileInputStream fin=new FileInputStream("D:\\testout.txt");
8. int i=0;
9. while((i=fin.read())!=-1){
10. System.out.print((char)i);
11. }
12. fin.close();
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
Output:
Welcome to javaTpoint
For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax
for adding the buffer in an OutputStream:
BufferedOutputStream(O It creates the new buffered output stream which is used for
BufferedOutputStream(O It creates the new buffered output stream which is used for
utputStream os, int size) writing the data to the specified output stream with a
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, It write the bytes from the specified byte-input stream into a
int off, int len) specified byte array, starting with the given offset
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
Welcome to javaTpoint.
● When the bytes from the stream are skipped or read, the internal buffer automatically refilled
from the contained input stream, many bytes at a time.
putStream IS, int size) and saves it argument, the input stream IS, for later use.
int available() It returns an estimate number of bytes that can be read from the input
stream without blocking by the next invocation method for the input
stream.
int read() It read the next byte of data from the input stream.
int It read the bytes from the specified byte-input stream into a specified
void reset() It repositions the stream at a position the mark method was last called
void mark(int It sees the general contract of the mark method for the input stream.
readlimit)
long skip(long It skips over and discards x bytes of data from the input stream.
x)
boolean It tests for the input stream to support the mark and reset methods.
markSupporte
d()
1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedInputStreamExample{
4. public static void main(String args[]){
5. try{
6. FileInputStream fin=new FileInputStream("D:\\testout.txt");
7. BufferedInputStream bin=new BufferedInputStream(fin);
8. int i;
9. while((i=bin.read())!=-1){
10. System.out.print((char)i);
11. }
12. bin.close();
13. fin.close();
14. }catch(Exception e){System.out.println(e);}
15. }
16. }
Here, we are assuming that you have following data in "testout.txt" file:
javaTpoint
Output:
javaTpoint
Java FilterOutputStream Class
Java FilterOutputStream class implements the OutputStream class. It provides different
sub classes such as BufferedOutputStream and DataOutputStream to provide
additional functionality.
Java application generally uses the data output stream to write data that can later be read
int size() It is used to return the number of bytes written to the data
output stream.
void write(int b) It is used to write the specified byte to the underlying output
stream.
void write(byte[] b, It is used to write len bytes of data to the output stream.
writeBoolean(boolea value.
n v)
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
writeChars(String s) characters.
value.
writeBytes(String s) bytes.
v)
v)
v)
void writeUTF(String It is used to write a string to the output stream using UTF-8
DataOutputStream class.
1. package com.javatpoint;
2.
3. import java.io.*;
4. public class OutputExample {
5. public static void main(String[] args) throws IOException {
6. FileOutputStream file = new FileOutputStream(D:\\testout.txt);
7. DataOutputStream data = new DataOutputStream(file);
8. data.writeInt(65);
9. data.flush();
10. data.close();
11. System.out.println("Succcess...");
12. }
13. }
Output:
Succcess...
testout.txt:
Ex-2 : DataOutputStreamEx.java
import java.io.*;
class DataOutputStreamEx
dos.writeInt(10);
dos.writeChar('A');
dos.writeDouble(23.33);
dos.close();
}
Java DataInputStream Class
Java DataInputStream class allows an application to read primitive data from the input stream in a
machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a data
input stream.
int read(byte[] b) It is used to read the number of bytes from the input
stream.
int read(byte[] b, int off, It is used to read len bytes of data from the input stream.
int len)
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double
value.
boolean readBoolean() It is used to read one input byte and return true if byte is
String readUTF() It is used to read a string that has been encoded using the
UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and store
void readFully(byte[] b, It is used to read len bytes from the input stream.
Ex-1:
import java.io.*;
class DataInputStreamEx
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream(new FileInputStream("xyz.text"));
int a=dis.readInt();
char ch=dis.readChar();
double d=dis.readDouble();
System.out.println(a+" "+ch+ " "+d);
dis.close();
}
}
In this example, we are reading the data from the file testout.txt file.
1. package com.javatpoint;
2. import java.io.*;
3. public class DataStreamExample {
4. public static void main(String[] args) throws IOException {
5. InputStream input = new FileInputStream("D:\\testout.txt");
6. DataInputStream inst = new DataInputStream(input);
7. int count = input.available();
8. byte[] ary = new byte[count];
9. inst.read(ary);
10. for (byte bt : ary) {
11. char k = (char) bt;
12. System.out.print(k+"-");
13. }
14. }
15. }
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A
java.io.PrintStream class
The PrintStream class provides methods to write data to another stream. The PrintStream class
automatically flushes the data so there is no need to call flush() method. Moreover, its methods don't
throw IOException.
PrintStream class:
● public void print(char[] c): it prints the specified character array values.
● public void println(boolean b): it prints the specified boolean value and
terminates the line.
● public void println(char c): it prints the specified char value and terminates the
line.
● public void println(char[] c): it prints the specified character array values and
terminates the line.
● public void println(int i): it prints the specified int value and terminates the line.
● public void println(long l): it prints the specified long value and terminates the
line.
● public void println(float f): it prints the specified float value and terminates the
line.
● public void println(double d): it prints the specified double value and
terminates the line.
● public void println(String s): it prints the specified string value and terminates
the line./li>
● public void println(Object obj): it prints the specified object value and
terminates the line.
1. import java.io.*;
2. class PrintStreamTest{
3. public static void main(String args[])throws Exception{
4. FileOutputStream fout=new FileOutputStream("mfile.txt");
5. PrintStream pout=new PrintStream(fout);
6. pout.println(1900f);
7. pout.println(‘A’);
8. pout.println("Hello Java");
9. pout.println("Welcome to Java");
10. pout.close();
11. fout.close();
12. }
13. }
Construct Description
or
FileReader(S It gets filename in string. It opens the given file in read mode. If file
FileReader(F It gets filename in file instance. It opens the given file in read mode. If file
Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of
file.
1. package com.javatpoint;
2.
3. import java.io.FileReader;
4. public class FileReaderExample {
5. public static void main(String args[])throws Exception{
6. FileReader fr=new FileReader("D:\\testout.txt");
7. int i;
8. while((i=fr.read())!=-1)
9. System.out.print((char)i);
10. fr.close();
11. }
12. }
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
Unlike FileOutputStream class, you don't need to convert string into byte array because it provides
method to write string directly.
Constructor Description
FileWriter(File file) Creates a new file. It gets file name in File object.
Method Description
1. package com.javatpoint;
2. import java.io.FileWriter;
3. public class FileWriterExample {
4. public static void main(String args[]){
5. try{
6. FileWriter fw=new FileWriter("D:\\testout.txt");
7. fw.write("Welcome to javaTpoint.");
8. fw.close();
9. }catch(Exception e){System.out.println(e);}
10. System.out.println("Success...");
11. }
12. }
Output:
Success...
testout.txt:
Welcome to javaTpoint.
Class declaration
Let's see the declaration for Java.io.PrintWriter class:
Method Description
void println(boolean x) It is used to print the boolean value.
writer.
boolean checkError() It is used to flushes the stream and check its error
state.
1. package com.javatpoint;
2.
3. import java.io.File;
4. import java.io.PrintWriter;
5. public class PrintWriterExample {
6. public static void main(String[] args) throws Exception {
7. //Data to write on Console using PrintWriter
8. PrintWriter writer = new PrintWriter(System.out);
9. writer.write("Javatpoint provides tutorials of all technology.");
10. writer.flush();
11. writer.close();
12. //Data to write in File using PrintWriter
13. PrintWriter writer1 =null;
14. writer1 = new PrintWriter(new File("D:\\testout.txt"));
15. writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");
16. writer1.flush();
17. writer1.close();
18. }
19. }
Outpt
Method Description
void write(int b) It is used to write the specified byte to the output stream.
void write(byte[] ary) It is used to write ary.length byte to the output stream.
void write(byte[] b, int off, It is used to write len bytes from the offset off to the
Output:
Success...
testout.txt
Welcome to javaTpoint.
Method Description
int available() It is used to return an estimate number of bytes that can be read
int read() It is used to read the next byte of data from the input stream.
int read(byte[] b) It is used to read up to byte.length bytes of data from the input
stream.
long skip(long n) It is used to skip over and discards n bytes of data from the input
stream.
boolean It is used to test if the input stream support mark and reset
markSupported() method.
void mark(int It is used to mark the current position in the input stream.
readlimit)
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javatpoint
Output:
Welcome to javatpoint
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.
5. File mode specifies whether the file has to be opened in the read
mode (“r”) or read-write mode(“rw”).
Constructor
Constructor Description
file, String mode) optionally to write to, the file specified by the File argument.
g name, String mode) optionally to write to, a file with the specified name.
Method
the stream.
or write occurs.
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)));
The myFile.TXT contains text "This class is used for reading and writing to random access file."
Output:
On file: This class is used for reading I love my country and my peoplele.
Java JDBC Tutorial
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with
the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect
with the database. There are four types of JDBC drivers:
● Native Driver,
● Thin Driver
We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC
API, we can save, update, delete and fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on
the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC
API. A list of popular interfaces of JDBC API are given below:
● Driver interface
● Connection interface
● Statement interface
● PreparedStatement interface
● CallableStatement interface
● ResultSet interface
● ResultSetMetaData interface
● DatabaseMetaData interface
● RowSet interface
A list of popular classes of JDBC API are given below:
● DriverManager class
● Blob class
● Clob class
● Types class
We can use JDBC API to handle database using Java program and can perform the following activities:
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database.
There are 4 types of JDBC drivers:
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
This is now discouraged because of thin driver. (Vendor based database libraries means
you need to use libraries provided by vendors to connect to database. For example You
need to use ojdbc10.jar for Oracle , postgresql-9.4.1207.jar for postgresql etc.)
Advantages:
● easy to use.
● can be easily connected to any database.
Disadvantages:
● Performance degraded because JDBC method call is converted into the ODBC function calls.
● The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls (In rough terms, a "native function call" means
calling a function that is implemented by, and specific to, the operating system (or
family of operating systems). The functions in the win32 API could be described by
windows programmers as native functions.) of the database API. It is not written
entirely in java.
Advantage:
Disadvantage:
Advantage:
● No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
Advantage:
Disadvantage:
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in
the classpath, and then JDBC driver manager can detect and load the driver automatically.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
throws SQLException
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
statement. The object of statement is responsible to execute queries with the database.
database. This method returns the object of ResultSet that can be used to get all the
records of a table.
Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties that
enable you to send SQL or PL/SQL commands and receive data from your database.
They also define methods that help bridge data type differences between Java and SQL data
types used in a database.
The following table provides a summary of each interface's purpose to decide on the interface to
use.
PreparedStatement Use this when you plan to use the SQL statements many
times. The PreparedStatement interface accepts input
parameters at runtime.
CallableStatement Use this when you want to access the database stored
procedures. The CallableStatement interface can also
accept runtime input parameters.
JDBC API provides 3 different interfaces to execute the different types of SQL queries. They are,
1) Statement – Used to execute normal SQL queries.
These three interfaces look very similar but they differ significantly from one another in the
functionalities they provide and the performance they give. In this post, we will discuss about the
differences between Statement, PreparedStatement and CallableStatement in detail.
1) Statement
Statement interface is used to execute normal SQL queries. You can’t pass the parameters to
SQL query at run time using this interface. This interface is preferred over other two interfaces if
you are executing a particular SQL query only once. The performance of this interface is also very
less compared to other two interfaces. In most of time, Statement interface is used for DDL
statements like CREATE, ALTER, DROP etc. For example,
1
//Creating The Statement Object
2
3
4 Statement stmt = con.createStatement();
5
6
//Executing The Statement
7
2) PreparedStatement
PreparedStatement is used to execute dynamic or parameterized SQL queries.
PreparedStatement extends Statement interface. You can pass the parameters to SQL query at
run time using this interface. It is recommended to use PreparedStatement if you are executing a
particular SQL query multiple times. It gives better performance than Statement interface.
Because, PreparedStatement are precompiled and the query plan is created only once
irrespective of how many times you are executing that query. This will save lots of time.
1
//Creating PreparedStatement object
2
3
4 PreparedStatement pstmt = con.prepareStatement("update
STUDENT set NAME = ?, where ID = ?");
5
6
7 //Setting values to place holders using setter methods of
8 PreparedStatement object
9
10
pstmt.setString(1, "MyName"); //Assigns "MyName" to first
11 place holder
12
13
pstmt.setInt(2, 111); //Assigns "111" to second place
holder
//Executing PreparedStatement
pstmt.executeUpdate();
Java Database Connectivity with Oracle
To connect java application with the oracle database, we need to follow 5 following steps.
In this example, we are using Oracle 10g as the database. So we need to know following
2. Connection URL: T
he connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is
running, we may also use IP address, 1521 is the port number and XE is the
Oracle service name. You may get all these information from the tnsnames.ora file.
4. Password: It is the password given by the user at the time of installing the oracle
database.
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Two ways to load the jar file:
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
● temporary
● permanent
Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
4. Password: It is the password given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create database
first.
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/dbase","root","root");
8. //here dbase is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }
The above example will fetch all the records of emp table.
To connect java application with the mysql database, mysqlconnector.jar file is required to be
loaded.
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath:
There are two ways to set the classpath:
● temporary
● permanent
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
Java JDBC Example Connect to Microsoft Access
Database
This JDBC tutorial guides you how to develop a Java program that connects to a Microsoft Access Database. In
the early days of JDBC, you can connect to an Access database via JDBC ODBC driver provided by JDK.
However JDBC ODBC driver is no longer supported so you need to use a third-party JDBC driver for Microsoft
Access. And your Java code still uses JDBC API as normal.
Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only for
knowledge.
DSN: It is the name that applications use to request a connection to an ODBC Data Source. In other
words, it is a symbolic name that represents the ODBC connection. It stores the connection details like
database name, directory, database driver, UserID, password, etc. when making a connection to the
ODBC.
1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String database="student.mdb";//Here database exists in the current directory
6.
7. String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
8. DBQ=" + database + ";DriverID=22;READONLY=true";
9.
10. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11. Connection c=DriverManager.getConnection(url);
12. Statement st=c.createStatement();
13. ResultSet rs=st.executeQuery("select * from login");
14.
15. while(rs.next()){
16. System.out.println(rs.getString(1) );
17. }
18.
19. }catch(Exception ee){System.out.println(ee);}
20.
21. }}
1. import java.sql.*;
2. class Test{
3. public static void main(String ar[]){
4. try{
5. String url="jdbc:odbc:mydsn";
6. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
7. Connection c=DriverManager.getConnection(url);
8. Statement st=c.createStatement();
9. ResultSet rs=st.executeQuery("select * from login");
10.
11. while(rs.next()){
12. System.out.println(rs.getString(1) );
13. }
14.
15. }catch(Exception ee){System.out.println(ee);}
16.
17. }}
Steps to ADD DSN:
what happens if you want to call that class without re-creating the object? In those cases,
what you do is use the serialization concept by converting data into a byte stream.
object serialization is a process used to convert the state of an object into a byte stream,
which can be persisted into disk/file or sent over the network to any other running java
virtual machine. The reverse process of creating an object from the byte stream is called
deserialization . The byte stream created is platform independent. so, the object
serialized on one platform can be deserialized on a different platform.
Java provides a mechanism, called object serialization where an object can be
represented as a sequence of bytes that includes the object's data as well as information
about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its data
can be used to recreate the object in memory.
Most impressive is that the entire process is JVM independent, meaning an object can be
serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the
methods for serializing and deserializing an object.
The ObjectOutputStream class contains many write methods for writing various data types, but
one method in particular stands out −
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the
ObjectInputStream class contains the following method for deserializing an object −
public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is
Object, so you will need to cast it to its appropriate data type.
Emp.java
import java.io.Serializable;
}
SerialDemo.java
import java.io.*;
try {
FileOutputStream fileOut =new FileOutputStream("Employee.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in Employee.txt");
} catch (IOException i) {
i.printStackTrace();
}
}
}
Contents Of Employee.txt:
import java.io.*;
public class DeserialDemo {
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
}
}
Output:
Deserialized Employee...
Name: Vaishali
Address: ADGITM
Notice that for a class to be serialized successfully, two conditions must be met −
● The class must implement the java.io.Serializable interface.
● All of the fields in the class must be serializable. If a field is not serializable, it must be
marked transient.
The transient keyword in Java is used to avoid serialization. If any object of a data
structure is defined as a transient, then it will not be serialized.
SOCKET
What Is a Socket?
Normally, a server runs on a specific computer and has a socket that is bound to a
specific port number. The server just waits, listening to the socket for a client to
make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is
running and the port number on which the server is listening. To make a connection
request, the client tries to connect with the server on the server's machine and port. The
client also needs to identify itself to the server so it binds to a local port number that it will
use during this connection. This is usually assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the
server gets a new socket bound to the same local port and also has its remote
endpoint set to the address and port of the client. It needs a new socket so that it
can continue to listen to the original socket for connection requests while tending to
the needs of the connected client.
The client and server can now communicate by writing to or reading from their
sockets.
Definition:
The java.net package in the Java platform provides a class, Socket, that implements
one side of a two-way connection between your Java program and another program on the
network. The Socket class sits on top of a platform-dependent implementation, hiding the
details of any particular system from your Java program. By using the java.net.Socket
class instead of relying on native code, your Java programs can communicate over the
network in a platform-independent fashion.
If you are trying to connect to the Web, the URL class and related classes
(URLConnection, URLEncoder) a re probably more appropriate than the socket classes.
In fact, URLs are a relatively high-level connection to the Web and use sockets as part of
the underlying implementation.
Socket programming in Java is used for communication between the applications that
are running on different JRE. It can be either connection-oriented or connectionless. On the
whole, a socket is a way to establish a connection between a client and a server.
Socket programming is a way of connecting two nodes on a network to communicate with each
other. One socket ( node) listens on a particular port at an IP, while other socket r eaches out to the
other in order to form a connection.
The server forms the listener socket while the client reaches out to the server. Socket and Server
Socket classes are used for connection-oriented socket programming.
In order to initiate a clients request, you need to follow the below-mentioned steps:
1. Establish a Connection
The very first step is to establish a socket connection. A socket connection implies that the
two machines have information about each other’s network location (IP Address) and TCP
port. You can create a Socket with the help of a below statement:
Or
2. Communication
In order to communicate over a socket connection, streams are used for both input and output the
data. After establishing a connection and sending the requests, you need to close the connection.
The socket connection is closed explicitly once the message to the server is sent.
Now let’s see how to write a Java program to implement socket connection at client side.
1
2 // A Java program for a ClientSide
3
import java.net.*;
4
5 import java.io.*;
6
7 public class ClientProgram
8
9 {
10
11 // initialize socket and input output streams
12 private Socket socket = null;
13
14 private DataInputStream input = null;
15
16 private DataOutputStream out = null;
17
18 // constructor to put ip address and port
19
public Client(String address, int port)
20
21 {
22
23 // establish a connection
24
25 try
26
{
27
28 socket = new Socket(address, port);
29
30 System.out.println("Connected");
31
32 // takes input from terminal
33
input = new DataInputStream(System.in);
34
35 // sends output to the socket
36
37 out = new DataOutputStream(socket.getOutputStream());
38
39 }
40
41 catch(UnknownHostException u)
42
{
43
44
45
46 System.out.println(u);
47
}
48
49 catch(IOException i)
50
51 {
52
53 System.out.println(i);
54
55 }// string to read message from input
56 String line = "";
57
58 // keep reading until "Over" is input
59
60 while (!line.equals("Over"))
try
line = input.readLine();
out.writeUTF(line);
catch(IOException i)
System.out.println(i);
try
input.close();
out.close();
socket.close();
catch(IOException i)
System.out.println(i);
}
Now, let’s implement server-side programming and then arrive at the output.
In order to code the server-side application, you need two sockets and they are as follows:
● A ServerSocket which waits for the client requests (when a client makes a new Socket())
● A plain old socket for communication with the client.
Communication
It is important to close the connection by closing the socket as well as input/output streams once
everything is done.
Now let’s see how to write a Java program to implement socket connection at server side.
1
2 // A Java program for a Serverside
3
import java.net.*;
4
5 import java.io.*;
6
7 public class Server
8
9 {//initialize socket and input stream
10
11 private Socket socket = null;
12 private ServerSocket server = null;
13
14 private DataInputStream in = null;
15
16 // constructor with port
17
18 public Server(int port)
19
{
20
21 // starts server and waits for a connection
22
23 try{
24
25 server = new ServerSocket(port);//create a socket object
26
System.out.println("Server started");
27
28 System.out.println("Waiting for a client ...");
29
30 socket = server.accept();
31
32 System.out.println("Client accepted");
33
// takes input from the client socket
34
35 in = new DataInputStream(new
36 BufferedInputStream(socket.getInputStream()));
37
38 String line = "";
39
40 // reads message from client until "Over" is sent
41
42 while (!line.equals("Over"))
43
{
44
45
46 try
47
{
48
49 line = in.readUTF();
50
51 System.out.println(line);
52
}
catch(IOException i)
System.out.println(i);
}}
System.out.println("Closing connection");
// close connection
socket.close();
in.close();
catch(IOException i){
System.out.println(i);
}}
}}
After configuring both client and server end, you can execute the server side program first. After
that, you need to run client side program and send the request. As soon as the request is sent
from the client end, server will respond back. Below snapshot represents the same.
1. When you run the server side script, it will start and wait for the client to get started.
2. Next, the client will get connected and inputs the request in the form of a string.
3. When the client sends the request, the server will respond back.
One-way Communication
ClientSide:
package socketdemo;
import java.io.*;
import java.net.*;
String str="Vaishali";
OutputStreamWriter os= new OutputStreamWriter(s.getOutputStream());
PrintWriter out=new PrintWriter(os);
out.write(str);
os.flush();
s.close();
}
}
Serverside:
package socketdemo;
import java.io.*;
import java.net.*;
System.out.println("Client Connected");
Output:
Serverside:
Server is started
Server is waiting for client request
ClientSide:
Server is started
Server is waiting for client request
Client Connected
Client data: Vaishali
Two_way Communication:
ServerSide:
package socketdemo;
import java.io.*;
import java.net.*;
Client side:
package socketdemo;
import java.io.*;
import java.net.*;
public class ClientTwoWaySocket {
String str="Vaishali";
s.close();
}
}
Differences between HTTP and Socket?
HTTP is an application protocol. It basically means that HTTP itself can't be used to transport
information to/from a remote end point. Instead it relies on an underlying protocol which in HTTP's
case is TCP.
Sockets on the other hand are an API that most operating systems provide to be able to talk with the
network. The socket API supports different protocols from the transport layer and down.
That means that if you would like to use TCP you use sockets. But you can also use sockets to
communicate using HTTP, but then you have to decode/encode messages according to the HTTP
specification (RFC2616). Since that can be a huge task for most developers we also got ready clients
ebClient or the H
in our developer frameworks (like .NET), for instance the W ttpWebRequest classes.
Java Native Interface (JNI) is used to support native codes. (Native codes are non java
codes i.e C or C++ )
JNI is like a bridge between byte code running in JVM and native code.
Components needed for JNI application:
JNI Overview
● An interface that allows Java to interact with code written in another language
● Motivation for JNI
○ Code reusability
■ Reuse existing/legacy code with Java (mostly C/C++)
○ Performance
■ Native code used to be up to 20 times faster than Java, when running in interpreted
mode
■ Modern JIT compilers (HotSpot) make this a moot point
○ Allow Java to tap into low level O/S, H/W routines
● JNI code is not portable!
Note
JNI can also be used to invoke Java code from within
natively-written applications - such as those written in C/C++.
● javah - JDK tool that builds C-style header files from a given Java class that includes native methods
○ Adapts Java method signatures to native function prototypes
● jni.h - C/C++ header file included with the JDK that maps Java types to their native counterparts
○ javah automatically includes this file in the application header files
● Create a Java class with native method(s): public native void sayHi(String who, int
times);
● Load the library which implements the method: System.loadLibrary("HelloImpl");
● Invoke the native method from Java
static { System.loadLibrary("HelloImpl"); } //
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, P
riorityQueue, HashSet,
LinkedHashSet, TreeSet).
Or
● It is optional.
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:
N Method Description
o.
E> c)
element)
4 public boolean It is used to delete all the elements of the specified collection
5 default boolean It is used to delete all the elements of the collection that
E> filter)
7 public int size() It returns the total number of elements in the collection.
8 public void clear() It removes the total number of elements from the collection.
element)
containsAll(Collection<?> c)
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of
15 default Stream<E> It returns a possibly parallel Stream with the collection as its
parallelStream() source.
16 default Stream<E> stream() It returns a sequential Stream with the collection as its
source.
spliterator() 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.
No Method Description
.
1 public boolean It returns true if the iterator has more elements otherwise it returns
hasNext() false.
2 public Object next() It returns the element and moves the cursor pointer to the next
element.
3 public void remove() It removes the last elements returned by the iterator. It is less
used.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection interface extends
the Iterable interface and therefore all the subclasses of Collection interface also implement the
Iterable interface.
1. Iterator<T> iterator()
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection
c), void clear(), etc. which are implemented by all the subclasses of Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in which
we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
There are various methods in List interface that can be used to insert, delete, and access the elements
from the list. The classes that implement the List interface are given below.
1. ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate
element of different data types. The ArrayList class maintains the insertion order and is
non-synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider the
following example.
Ex-1
import java.util.*;
list.add("Hey");
list.add("Namastey");
list.add(9);
System.out.println(list);
Output:
Ex-2
1. import java.util.*;
2. public class TestJavaCollection1{
3. public static void main(String args[]){
4. Collection list=new ArrayList();//Creating arraylist
5. list.add("Hello");//Adding object in arraylist
6. list.add("Hey");
7. list.add("Namastey");
8. list.add("Hi");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. } }
Output:
Hello
Hey
Namastey
Hi
Ex-3
import java.util.*;
public class TestJavaCollection1{
public static void main(String args[]){
List list=new ArrayList();//Creating arraylist
//Adding object in arraylist
list.add(4); //Integer v=new Integer(4), this is an object of Integer
list.add(6);
list.add(9);
list.add(2,2);
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
4
6
2
9
Ex-4
import java.util.*;
public class TestJavaCollection1{
public static void main(String args[]){
List list=new ArrayList();//Creating arraylist
list.add(4);//Adding object in arraylist
list.add(6);
list.add(9);
list.add(2,2);
//Traversing list through for loop
Ex-5
import java.util.*;
public class TestJavaCollection1{
list.add(6);
list.add(9);
list.add(2,2);
System.out.println(o);
}
Output:
4
6
2
9
Concept of Generics:
List <E>list=new ArrayList<E>();
Ex
import java.util.*;
public class TestJavaCollection1{
public static void main(String args[]){
ArrayList <Integer> list=new ArrayList<Integer>();//Creating arraylist
list.add(4);//Adding object in arraylist
list.add(6);
list.add(9);
list.add(2,2);
//Traversing list through for loop
for(Integer o: list)
{
System.out.println(o);
}
}
}
Output:
4
6
2
9
Sorting in List:
Collections.sort(list);
Ex:
import java.util.*;
public class TestJavaCollection1{
public static void main(String args[]){
ArrayList <Integer> list=new ArrayList<Integer>();//Creating arraylist
list.add(4);//Adding object in arraylist
list.add(6);
list.add(2);
list.add(9);
Collections.sort(list);
import java.util.*;
public class TestJavaCollection1{
list.add(6);
list.add(2);
list.add(9);
Collections.sort(list);
Collections.reverse(list);
for(Integer o: list)
{
System.out.println(o);
}
}
Output:
9
4
2
Note: Original list is changed, so we can say that list is mutable.
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is fast because no shifting is required.
Ex-1
import java.util.*;
//add
ll.add("Test");
ll.add("java");
ll.add("Link");
ll.add("list");
Output:
content of linkedlist[Test, java, Link, list]
Ex-3
import java.util.*;
public class LinkedListDemo{
ll.add("Test");
ll.add("java");
ll.add("Link");
ll.add("list");
//print
System.out.println("content of linkedlist" + ll);
//add first
ll.addFirst("hey");
//add Last
ll.addLast("end");
}
Output:
Ex-4
import java.util.*;
public class LinkedListDemo{
public static void main(String args[]){
LinkedList<String> ll = new LinkedList<String>();
//add
ll.add("Test");
ll.add("java");
ll.add("Link");
ll.add("list");
//print
System.out.println("content of linkedlist" + ll);
//add first
ll.addFirst("hey");
//add Last
ll.addLast("end");
System.out.println("content of linkedlist" + ll);
//get
System.out.println(ll.get(0));
ll.set(0,"hello");
System.out.println(ll.get(0));
}
}
Output:
content of linkedlist[Test, java, Link, list]
content of linkedlist[hey, Test, java, Link, list, end]
hey
hello
Ex-5
import java.util.*;
public class LinkedListDemo{
public static void main(String args[]){
LinkedList<String> ll = new LinkedList<String>();
//add
ll.add("Test");
ll.add("java");
ll.add("Link");
ll.add("list");
//print
System.out.println("content of linkedlist" + ll);
//add first
ll.addFirst("hey");
//add Last
ll.addLast("end");
System.out.println("content of linkedlist" + ll);
//get
System.out.println(ll.get(0));
ll.set(0,"hello");
System.out.println(ll.get(0));
//remove first and last element
ll.removeFirst();
ll.removeLast();
System.out.println("content of linkedlist" + ll);
ll.remove(2);
System.out.println("content of linkedlist" + ll);
}
}
Output:
content of linkedlist[Test, java, Link, list]
content of linkedlist[hey, Test, java, Link, list, end]
hey
hello
content of linkedlist[Test, java, Link, list]
content of linkedlist[Test, java, list]
Ex-6
import java.util.*;
public class LinkedListDemo{
public static void main(String args[]){
LinkedList<String> ll = new LinkedList<String>();
//add
ll.add("Test");
ll.add("java");
ll.add("Link");
ll.add("list");
//print
System.out.println("content of linkedlist" + ll);
//add first
ll.addFirst("hey");
ll.add(2,"exampple");
//add Last
ll.addLast("end");
System.out.println("content of linkedlist" + ll);
//loop
System.out.println("***For Loop***");
for(int n=0;n<ll.size();n++)
{
System.out.println(ll.get(n));
}
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are not the part of Collection framework.
1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ayush
Amit
Ashish
Garima
Ex-2
import java.util.*;
public class TestJavaCollection1{
myVector.add(4);
myVector.add(12);
myVector.add(8);
myVector.add(5);
System.out.println(myVector);
System.out.println(myVector.get(2));
myVector.remove(3);
System.out.println(myVector);
yourVector.add(10);
yourVector.add(14);
myVector.addAll(yourVector);
System.out.println(myVector);
}
Output:
[10, 4, 12, 8, 5]
12
[10, 4, 12, 5]
[10, 4, 12, 5, 10, 14]
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The
stack contains all of the methods of Vector class and also provides its methods like boolean push(),
boolean peek(), boolean push(object o), which defines its properties.
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. I t can be defined as an ordered list that is
used to hold the elements which are about to be processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
There are various classes that implement the Queue interface, some of them are given below.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to
be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.
1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Ex-2
import java.util.*;
public class TestJavaCollection5{
public static void main(String args[]){
LinkedList<Integer> queue=new LinkedList<Integer>();
queue.add(10);
queue.add(7);
queue.add(2);
queue.add(5);
System.out.println(queue);
System.out.println("head:"+queue.peek());
queue.poll();
System.out.println(queue);
}
}
Output:
[10, 7, 2, 5]
head:10
[7, 2, 5]
[2, 5, 7, 10]
head:5
[5, 10, 7]
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from
both the side. Deque stands for a double-ended queue which enables us to perform the operations at
both the ends.
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we
can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }
Output:
Gautam
Karan
Ajay
Ex-2:
import java.util.*;
Ex-3
import java.util.*;
// Using remove()
String element = animals.remove();
System.out.println("Removed Element: " + element);
// Using removeLast()
String lastElement = animals.removeLast();
System.out.println("Removed Last Element: " + lastElement);
System.out.println("New ArrayDeque: " + animals);
}
}
Output:
ArrayDeque: [Dog, Cat, Cow, Horse]
Removed Element: Dog
New ArrayDeque: [Cat, Cow, Horse]
Removed First Element: Cat
New ArrayDeque: [Cow, Horse]
Removed Last Element: Horse
New ArrayDeque: [Cow]
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents
the unordered set of elements which doesn't allow us to store the duplicate items. We can store at
most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Set Operations
The Java Set interface allows us to perform basic mathematical set operations like
union, intersection, and subset.
● Union - to get the union of two sets x and y, we can use x.addAll(y)
● Intersection - to get the intersection of two sets x and y, we can use
x.retainAll(y)
Ex-1
import java.util.*;
set.add(4);
set.add(8);
set.add(9);
set.add(2);
//Traversing elements
Iterator<Integer> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
Output:
2
4
8
9
Ex-2
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<Integer> set=new HashSet<Integer>();
set.add(4);
set.add(8);
set.add(9);
set.add(2);
set.add(9); //adding redundant data
//Traversing elements
Iterator<Integer> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
2
4
8
9
//But only one 9 has been added in the output.
Ex-3 //TreeSet
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
TreeSet<Integer> set=new TreeSet<Integer>();
set.add(4);
set.add(8);
set.add(9);
set.add(2);
set.add(9);
//Traversing elements
Iterator<Integer> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
2
4
8
9
Ex-
import java.util.*;
public class TestJavaCollection7{
set.add(4);
set.add(8);
set.add(9);
set.add(8);
set.add(2);
System.out.println(set);
//Traversing elements
Iterator<Integer> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
tset.add(4);
tset.add(8);
tset.add(9);
tset.add(8);
tset.add(2);
System.out.println(tset);
//Traversing elements
Iterator<Integer> itr1=set.iterator();
while(itr1.hasNext()){
System.out.println(itr1.next());
}
}
}
Output:
[2, 4, 8, 9]
2
4
9
[2, 4, 8, 9]
4
8
import java.util.Set;
import java.util.HashSet;
set1.add(2);
set1.add(3);
set2.add(6);
set2.add(2);
System.out.println("Set2: " + set2);
set2.addAll(set1);
Output:
Set1: [2, 3, 10]
Set2: [1, 2, 6]
import java.util.HashSet;
primeNumbers.add(3);
evenNumbers.add(4);
evenNumbers.retainAll(primeNumbers);
System.out.println("Intersection is: " + evenNumbers);
}
Output:
HashSet1: [2, 3]
HashSet2: [2, 4]
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet
class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the
insertion order and permits null elements.
1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements
of the SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the
additional methods that inhibit the natural ordering of the elements.
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet
also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.
1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ajay
Ravi
Vijay
import java.util.HashSet;
class Main {
public static void main(String[] args) {
HashSet<Integer> primeNumbers = new HashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
System.out.println("HashSet1: " + primeNumbers);
A Map is useful if you have to search, update or delete elements on the basis of a
key. A map cannot contain duplicate keys. And, each key is associated with a single
value.
We can access and modify values using the keys associated with them.
In Java, we must import the java.util.Map package in order to use Map. Once we import the
In the above code, we have created a Map named numbers. We have used the HashMap class to
Here,
Map Properties:
Method Description
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry<K,V>> It returns the Set view containing all the keys and values.
entrySet()
V compute(K key, BiFunction<? It is used to compute a mapping for the specified key and its
super K,? super V,? extends V> current mapped value (or null if there is no current mapping).
remappingFunction)
V computeIfAbsent(K key, It is used to compute its value using the given mapping function,
Function<? super K,? extends if the specified key is not already associated with a value (or is
V> mappingFunction) mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, It is used to compute a new mapping given the key and its
BiFunction<? super K,? super current mapped value if the value for the specified key is present
remappingFunction)
boolean containsValue(Object This method returns true if some value equal to the value exists
boolean containsKey(Object This method returns true if some key equal to the key exists
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? It performs the given action for each entry in the map until all
super K,? super V> action) entries have been processed or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated
V getOrDefault(Object key, V It returns the value to which the specified key is mapped, or
int hashCode() It returns the hash code value for the Map
boolean isEmpty() This method returns true if the map is empty; returns false if it
V merge(K key, V value, If the specified key is not already associated with a value or is
BiFunction<? super V,? super associated with null, associates it with the given non-null value.
remappingFunction)
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V It replaces the old value with the new value for a specified key.
oldValue, V newValue)
void replaceAll(BiFunction<? It replaces each entry's value with the result of invoking the
super K,? super V,? extends V> given function on that entry until all entries have been processed
Collection values() It returns a collection view of the values contained in the map.
int size() This method returns the number of entries in the map.
Java HashMap
Java HashMap class implements the Map interface which allows us to store key and
value pair, where keys should be unique. If you try to insert the duplicate key, it will
replace the element of the corresponding key. It is easy to perform operations using
the key index like updation, deletion, etc. HashMap class is found in the java.util
package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It
allows us to store the null elements as well, but there should be only one null key.
Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for
value. It inherits the AbstractMap class and implements the Map interface.
Points to remember
● Java HashMap may have one null key and multiple null values.
● Java HashMap is non synchronized.
Map Interface
Ex-1: //old style
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
Map<String, String> map=new HashMap<>();
map.put("name","vaishali");
map.put("college","adgitm");
map.put("subject","java");
System.out.println(map);
Ex-3:
import java.util.Map;
import java.util.HashMap;
import java.util.HashMap;
import java.util.Map.Entry;
// create a hashmap
HashMap<String, Integer> numbers = new HashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("HashMap: " + numbers);
Output:
HashMap: {One=1, Two=2, Three=3}
The key for value 3 is Three
In the above example, we have created a hashmap named numbers. Here, we want to get the
Here, the entrySet() method returns a set view of all the entries.
Inside the if statement we check if the value from the entry is the same as the given value. And,
for matching value, we get the corresponding key.
Set doesn’t allow duplicates. Set and all of the classes which implements Set interface
should have unique elements.
Map stored the elements as key & value pair. Map doesn’t allow duplicate keys while it
allows duplicate values.
Map can have single null key at most and any number of null values.
3) Order: List and all of its implementation classes maintains the insertion order.
Set doesn’t maintain any order; still few of its classes sort the elements in an order such as
LinkedHashSet maintains the elements in insertion order.
Similar to Set, Map also doesn’t stores the elements in an order, however few of its
classes does the same. For e.g. TreeMap sorts the map in the ascending order of keys
and LinkedHashMap sorts the elements in the insertion order, the order in which the
elements got added to the LinkedHashMap.
2) If there is a need of frequent search operations based on the index values then List
(ArrayList) is a better choice.
3) If there is a need of maintaining the insertion order then also the List is a preferred
collection interface.
4) If the requirement is to have the key & value mappings in the database then Map is your
best bet.
Java RMI - Introduction
RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in
one system (JVM) to access/invoke an object running on another JVM.
RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.
● Inside the server program, a remote object is created and reference of that object is made
available for the client (using the registry).
● The client program requests the remote objects on the server and tries to invoke its
methods.
● Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.
● Stub − A stub is a representation (proxy) of the remote object at client. It resides in the
client system; it acts as a gateway for the client program.
● Skeleton − This is the object which resides on the server side. stub communicates with this
skeleton to pass request to the remote object.
● RRL(Remote Reference Layer) − It is the layer which manages the references made by the
client to the remote object.
At the server side, the packed parameters are unbundled and then the required method is
invoked. This process is known as unmarshalling.
RMI Registry
RMI registry is a namespace on which all server objects are placed. Each time the server creates
an object, it registers this object with the RMIregistry (using bind() or reBind() methods). These
are registered using a unique name known as bind name.
To invoke a remote object, the client needs a reference of that object. At that time, the client
fetches the object from the registry using its bind name (using lookup() method).
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
The library contains components for managing input, database programming, and much
much more. The complete list can be found at Oracles website:
https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either import a
single class (along with its methods and attributes), or a whole package that contain all
the classes that belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
ackage.name.
import p Class; // Import a single class
import p ackage.name. *; // Import the whole package
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get
user input, write the following code:
Example
import java.util.Scanner;
To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use the
nextLine() method, which is used to read a complete line:
Example
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");
Import a Package
There are many packages to choose from. In the previous example, we used the
Scanner class from the java.util package. This package also contains date and time
facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the java.util package:
Example
import java.util.*;
User-defined Packages
To create your own package, you need to understand that Java uses a file system
directory to store them. Just like folders on your computer:
Example
└── root
└── mypack
└── MyPackageClass.java
MyPackageClass.java
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Save the file as MyPackageClass.java, and compile it:
Note: The package name should be written in lower case to avoid conflict with class names.
When we compiled the package in the example above, a new folder was created, called
"mypack".
This is my package!
Miscellaneous (Extra)
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
platform-independent.
3) AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
4) AWT provides less components than Swing. Swing provides more powerful components
tabbedpane etc.
view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of
desktop applications.
JFrame – A frame is an instance of JFrame. Frame is a window that can have title, border,
menu, buttons, text fields and several other components. A Swing application must have a
frame to have the components added to it.
JPanel – A panel is an instance of JPanel. A frame can have more than one panels and
each panel can have several components. You can also call them parts of Frame. Panels
are useful for grouping components and placing them to appropriate locations in a frame.
JLabel – A label is an instance of JLabel class. A label is unselectable text and images. If
you want to display a string or an image on a frame, you can do so by using labels. In the
above example we wanted to display texts “User” & “Password” just before the text fields ,
we did this by creating and adding labels to the appropriate positions.
JTextField – Used for capturing user inputs, these are the text boxes where user enters
the data.
JPasswordField – Similar to text fields but the entered data gets hidden and displayed as
dots on GUI.
Java vs Javax:
Originally, everything that was part of the standard API was part of the java package, whereas
everything that was not part of the standard API was released under the package name j avax. Hence,
packages essential to the API was java, while javax contained the extensions to the API. It can even be
said that javax, is just java with an x
, which stands for extension.
Java Swing Examples
There are two ways to create a frame:
We can write the code of swing inside the main(), constructor or any other method.
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,1
00,1
00, 4
0);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.
File: Simple.java
1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. b.setBounds(130,1
00,1
00, 4
0);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the
position of the button.
File: Simple2.java
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,1
00,1
00, 4
0);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
Programming Interface (API) is the area of Java development kit (JDK). An API
includes classes, interfaces, packages and also their methods, fields, and constructors.
All these built-in classes give benefits to the programmer. Only programmers
understand how to apply that class. A user interface offers the basic user interaction
among user and computer, in the same manner, the API works as an application
program interface which gives connection amongst the software as well as the
consumer. API includes classes and packages which usually assist a programmer to
per below:
1. Java compiler
● The Java API added to the JDK, explains the function of every element. In Java
● Hence, the programmer can make use of a prewritten program with the Java API.
After mentioning the obtainable API classes as well as, packages, the
programmer quickly creates the required program classes and packages to get
executed.
● The Java API is a vital element of the JDK and identifies features of every
done it. Through Java, API coder can simply make use of the pre-written
program.
● The programmers initially declare the classes and packages, then this coder can
simply use the application program of classes and packages to get executed.