Java Assignment-4 UNIT-4 Input/Output Stream
Java Assignment-4 UNIT-4 Input/Output Stream
UNIT-4
INPUT/OUTPUT STREAM
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 characters. Character stream uses Unicode and therefore can be
internationalized.
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
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:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
A list of popular classes of JDBC API are given below:
o DriverManager class
o Blob class
o Clob class
o Types class
We can use JDBC API to handle database using Java program and can perform the
following activities:
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. }
SOCKETS
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 rendezvous 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.
On the client side, if the connection is accepted, a socket is successfully created and
the client can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their
sockets.
Definition:
If you are trying to connect to the Web, the URL class and related classes
(URLConnection, URLEncoder) are 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. See Working with URLs for
information about connecting to the Web via URLs.
How it works?
For each client connection, the server starts a child thread to process
the request independent of any other incoming requests.
Thus, for example, a client seeking product information can query a warehouse object on
the server. It calls a remote method find which has one parameter, the request form object.
The find method returns an object to the client, the product information object. This can be
depicted as follows:
find Warehouse
The purpose behind RMI is to make all the implementation details transparent to the
programmer so that remote objects and methods work just like the local objects and
methods.
Design
In the JNI framework, native functions are implemented in separate .c or .cpp
files. (C++ provides a slightly simpler interface with JNI.) When the JVM
invokes the function, it passes a JNIEnv pointer, a jobject pointer, and
any Java arguments declared by the Java method. For example, the following
converts a Java string to a native string:
extern "C"
JNIEXPORT void JNICALL Java_ClassName_MethodName
(JNIEnv *env, jobject obj, jstring javaString)
{
const char *nativeString = env-
>GetStringUTFChars(javaString, 0);
env->ReleaseStringUTFChars(javaString, nativeString);
}
The steps shown herein are the simplest way to write a JNI app disregarding
standard/good programming technique. Make sure you have a GNU g++ compiler
installed for C/C++, along with latest JDK. Also, make sure you can compile C/C++
source code from a command line/terminal, along with Java. This can be
accomplished by setting up bin folder for both Java and C/C++ compiler in the PATH
environment variable.
1. Write the Java Code
To keep it simple, create a folder and name it, say, JNI_project. We shall use it as a parent folder for
every file we create. Now, create a Java file with the following code:
javac JNITest.java
javah JNITest
#include<stdio.h>
#include<jni.h>
#include "JNITest.h"
JNIEXPORT void JNICALL Java_JNITest_greet
(JNIEnv *env, jobject obj){
printf("\n...Welcome to the world of JNI...\n");
return;
}
For Windows:
Collection Characteristics
VECTORS
Java Vector class comes under the java.util package. The vector class
implements a growable array of objects. Like an array, it contains the
component that can be accessed using an integer index.
Vector is very useful if we don't know the size of an array in advance or we need
one that can change the size over the lifetime of a program.
o Vector is synchronized.
o The vector contains many legacy methods that are not the part of a
collections framework
1. public class Vector<E>
2. extends Object<E>
3. implements List<E>, Cloneable, Serializable
SN Constructor Description
3 vector(int initialCapacity, int It constructs an empty vector with the specified initial
) capacityIncrement) capacity and capacity increment.
STACKS
Hashtable Class
Hashtable()
As Hashtable implements Map interface, so some methods are inherited from Map.
Methods Description
void clear() Removes all the key/value pairs from the Hashtable.
Returns the total number of key-value pairs in a
int size()
Hashtable.
Set<Map.Entry<K,V>>
Returns the Set containing Map.Entry objects.
entrySet()
Java Enumerations
Enumerations was added to Java language in
JDK5. Enumeration means a list of named constant. In Java,
enumeration defines a class type. An Enumeration can have
constructors, methods and instance variables. It is created
using enum keyword. Each enumeration constant
is public, static and final by default. Even though enumeration
defines a class type and have constructors, you do not
instantiate an enum using new. Enumeration variables are
used and declared in much a same way as you do a primitive
variable.
The Collection interface is a general interface that includes sub-interfaces List and Set. If a method
has a parameter of type Collection, such as the addAll(Collection coll) method below, you can
pass it a List or Set and it will work fine. List is an interface, and ArrayList is the typically used class
that implements List. Likewise, Set is an interface, and HashSet is the commonly used class that
implements Set. The Map interface is separate from the Collection interface. The Map interface
defines a key/value lookup dictionary, and HashMap is the most commonly used Map. The sections
below explain all of these classes.
Lists
The List is probably the single most useful and widely used type of Collection. List is a general
interface, and ArrayList and LinkedList are implementing classes. ArrayList is the best general
purpose List, so that's what we'll use here.
A List is a linear structure where each element is known by an index number 0, 1, 2, ... len-1 (like an
array). Lists can only store objects, like String and Integer, but not primitives like int. You cannot
create a List of int, but you can create a list of Integer objects. This is a common feature of all the
Java Collection classes (see boxing below). Another way to say this is that the collection classes can
only store pointers.
Iterator
The foreach syntax -- for (String str: words) ... -- is the easiest way to iterate over a list. "Iterator"
objects provide an alternative and more flexible way to iterate over a list. In fact, behind the scenes,
the foreach syntax just creates an Iterator object to do the iteration.
Iterator objects are generic by the element type, so for a List<String>, you use an Iterator<String>.
Iterators are shown here with lists, but iterators work for all collection types. To use an Iterator, call
the collection's iterator() method which returns an Iterator object, ready to iterate over that
collection:
// Suppose we have a "words" list of strings:
List words = new ArrayList(); // create a list of strings
// Here's how to create an iterator to go through all the words:
Iterator it = words.iterator();
The Iterator object is temporary -- you use it to go through the elements in the list and then discard
it. The Iterator has two main methods:
Each call to next() yields the next element from the list until there are no more elements, at which
point hasNext() returns false. It is an error to call next() when hasNext() is false. During the
hasNext()/next() iteration, it is not valid to modify the underlying list with add/remove operations.
Code that uses iteration must not modify the collection during the iteration.
Iterator Remove
The Iterator has a remove() method that removes the element from the previous call to next(). It is
not valid to modify the list during iteration generally, but iterator remove() is an allowed exception.
It is only valid to call it.remove() once for each call to it.next(). For example, here is code that iterates
over the words list, removing all the words of length 4 or more:
// words is: {"this", "and",
"that"} // Remove words
length 4 or more.
Iterator<String> it =
words.iterator(); while
(it.hasNext()) {
String str = it.next();
if (str.length() >= 4) it.remove();
}
// words is: {"and"}
Using it.remove() during iteration is potentially a very clean and efficient strategy -- it does not have
to search the whole list for the element, since the element to remove is at the current spot of the
iterator. Contrast this to the more expensive list.remove(Object target) above which must
search the whole list for the target and then remove it.
It's possible to have multiple iterators going over a collection at the same time, each proceeding
through all the elements independently. In that case, no add/remove modifications to the collection
are allowed -- it would be too complicated for the multiple iterators to coordinate their changes.
The above code demonstrates the basic Iterator class which works for all collection types, including
lists. There is a more powerful type of iterator, the ListIterator, which works for list types, but not
other collection types. The ListIterator can go forwards and backwards and can insert and delete.
The ListIterator is powerful but more rarely used -- you can get quite far with the plain foreach for
common loops, and the Iterator when you want to delete during iteration. Iterators are not
restricted to the Collection classes -- any class that implements the Iterable interface to provide an
Iterator object with hasNext(), next(), etc. can support iteration just like the collection classes.
Sets
The Java "Set" is a Collection, like the List, but with the added constraint that each element can be in
the Set once, using equals() to test if two elements are the same. If an add() operation tries to add
an element that is already in the set, the add() is silently ignored. This can be useful to store values
where you want this sort of mathematical set behavior. The standard Collection methods --
contains(), addAll(), iterator()... -- work for Sets as they do for any Collection. With Sets, the standard
utility methods addAll(), retainAll(), containsAll() now give you fully functioning mathematical set
operations. To make a set union of x and y, call x.addAll(y). To make the intersection of sets x and y,
call x.retainAll(y). To test if x is a subset of y, call y.containsAll(x). Sets do not impose a 0..size-1
indexing of the elements (that's what Lists do), so List methods like get(int index) are not available
for sets. Sets are potentially more efficient than lists. In particular, the HashSet can find or insert an
element in constant time.
// Create a Set of Integer objects
Set<Integer> nums = new HashSet<Integer>();
// Add the
numbers 1..10 for
(int i=1; i<=10; i++) {
nums.add(i);
}
// Add 1, 4, 9, 16, 25
// Since it's a Set, only the add() of 16 and 25
do anything. for (int i=1; i<=5; i++) {
nums.add(i * i);
}
Map
A Map is very different from List and Set. A Map is a key/value table that can look up any entry by
key very efficiently (know as a "hash table" or "dictionary").
"Map" is a general interface of the basic map features, implemented by two main classes: HashMap
and TreeMap. HashMap is by far the more commonly used one, and that's what we will us here.
A Map stores key/value entries, where each key in the map is associated with a single value. For
example, here is a map where the each key is the string name of a city and the associated value is
the lat/long location of that city (in this case, both key and value are strings):
Most uses of a map involve just two methods put() and get():
put(Object key, Object value) -- puts an entry for the given key into the map with
the given value. If there was an existing value for that key, it is overwritten by this new
value. Object get(Object key) -- gets the value previously stored for this key, or null
if there is no entry for this key in the map.
boolean containsKey(Object key) -- returns true if the map contains an entry for
the given key. int size() -- returns the number of key/value entries in the map
With Java version 5, the Map is most often used with generics to indicate the type of key and
the type of value. Both the key and value must be object types such as String or Integer or List. For
example, below is code that creates a new HashMap where both the key and value are Strings.
"Map" is the general interface for maps, and "HashMap" is the particular type of map created here.
It is standard to declare the variable with the general type, Map, as shown here:
Map<String, String> states = new HashMap<String, String>();
states.put("ca", "California");
states.put("az", "Arizona");
states.put("mn", "Minnesota");
states.put("nj", "New Jersey");
Once a value is put in the map with put(), it can be retrieved with get():
states.get("ca") // returns "California"
states.get("nj") // returns "New Jersey"
states.get("xx") // returns null, there is no entry for "xx"
states.put("nj", "Garden State"); // Put a new entry for "nj", overwriting the old
entry states.get("nj") // returns "Garden State"
For a HashMap, the keys are stored in a seemingly random order. The important feature of get() and
put() is that they are fast. With a HashMap, even if there are a 100,000 entries in the map, get() and
put() can access a particular entry almost instantaneously (constant time). This very fast
performance is a feature of HashMap; the TreeMap is slower. That's why everyone uses HashMap.
For whatever problem you are solving, if there is part of the problem that involves storing
information under some key and retrieving that information later ... use a HashMap. The HashMap is
simple to use, reliable, and fast.