Java IO Stream
Java IO 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.
DataOutputStream An output stream that contain method for writing java standard data ty
These classes define several key methods. Two most important are
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.
int read() throws IOException
import java.io.*;
class MyInput
String text;
System.out.println(text);
The basic differences between print() and println() methods are as follows:
Now, let us understand it in a better way with the help of some examples.
1. // Sample program to display numbers from 1-10
using print method
2. class printEg
3. {
4. public static void main(String args[])
5. {
6. int a;
7. for (a=1 ; a<=10 ; a++)
8. {
9.
System.out.print(a);
10. }
11. }
12. }
Output:
Example of println() method:
Let us take the same example above and use println() method in place of print() method.
1. // Sample program to display numbers from 1-10
using println method
2. class printlnEg
3. {
4. public static void main(String args[])
5. {
6. int a;
7. for (a=1 ; a<=10 ; a++)
8. {
9.
System.out.println(a);
10. }
11. }
12. }
Output:
Both these functions work best for output of strings as well. Let us have a look at another
example.
In addition, if you want to display the value of any particular variable used in the program,
then you have to append the variable name along with the string with a plus (+) symbol.
1. // Sample program to display sum of numbers from 1-
10
2. class Eg1
3. {
4. public static void main(String args[])
5. {
6. int a, total = 0;
7. for (a=1 ; a<=10 ; a++)
8. {
9. total = total +
a;
10. }
11.
System.out.println("Sum of first 10 numbers is: " +
total);
12. }
13. }
Output:
The write() method
Alternatively, you can make use of the write() method for directing the output of your
program to the console. The easiest syntax of the write() method is:
class writeEg
{
public static void main(String args[])
{
int a, b;
a = 'Q';
b = 65;
System.out.write(a);
System.out.write('\n');
System.out.write(b);
System.out.write('\n');
}
}
Output:
java.io.serializable
java.io.Externalizable
ObjectInputStream
ObjectOutputStream
java.io.serializable
java.lang.Cloneable
java.rmi.Remote
java.util.RandomAccess
All these interfaces does not have any method and field. They only add special
behavior to the classes implementing them. However marker interfaces have been
deprecated since Java 5, they were replaced by Annotations. Annotations are used
in place of Marker Interface that play the exact same role as marker interfaces did
before.
To implement serialization and deserialization, Java provides two classes
ObjectOutputStream and ObjectInputStream.
while serializing if you do not want any field to be part of object state then declare it
either static or transient based on your need and it will not be included during java
serialization process.
Serialization is the process of writing the state of an object to a byte stream. This is
useful when you want to save the state of your program to a persistent storage area,
such as a file. At a later time, you may restore these objects by using the process of
deserialization. Serialization is also needed to implement Remote Method Invocation
(RMI). RMI allows a Java object on one machine to invoke a method of a Java object
on a different machine. An object may be supplied as an argument to that remote
method. The sending machine serializes the object and transmits it. The receiving
machine deserializes it.
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.
How to Define and Use an Enumeration
1. An enumeration can be defined simply by creating a list of enum variable. Let
us take an example for list of Subject variable, with different subjects in the list.
2. //Enumeration defined
3. enum Subject
4. {
Example of Enumeration
Lets create an example to define an enumeration and access its constant by using
enum reference variable.
enum WeekDays{
class Demo
Today is SUNDAY
enum WeekDays{
class Demo {
System.out.println("It is Weekend");
else
System.out.println("It is weekday:
"+weekDays);
}
It is weekday: WEDNESDAY
enum WeekDays{
class Demo {
WeekDays[] wk = WeekDays.values();
for(WeekDays weekday : wk ){
System.out.println(weekday);
}
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
enum Restaurants {
class Demo {
Restaurants r;
System.out.println(a);
r = Restaurants.valueOf("DOMINOS");
r = Restaurants.valueOf("DOMINOS");
int i= Restaurants.KFC.ordinal();
KFC
PIZZAHUT
PANINOS
BURGERKING
It is DOMINOS
enum ordinal()
Restaurants.DOMINOS.ordinal(); // 0
Autoboxing and Unboxing in Java
Java added concept of autoboxing and unboxing that deal with conversion of
primitive type to object and vice versa.
The term autoboxing refers to the auto conversion of primitive type to its
correspond object type. For example, conversion of int type to Integer object or char
type to Character object. This conversion is done implicitly by the Java compiler
during program execution.
In the same context, when an object coverts to its correspond primitive type then it is
called unboxing. For example, conversion of Integer type to int type or Byte to byte
type etc. Java automatically performs this conversion during program execution.
Example of Autoboxing
In this example, we are assigning an int type value to Integer object and notice
compiler does not report any error because it performs autoboxing here.
class Demo
System.out.println(i);
Character ch = 'a';
System.out.println(ch);
Byte b = 12;
System.out.println(b);
}
100
12
Explanation:
Whenever we use object of Wrapper class in an expression, autoboxing is done by
JVM.
This will happen always, when we will use Wrapper class objects in expressions or
conditions etc.
Example : Unboxing
In this example, we using arraylist to store int type values. Since arraylist stores only
object then it automatically converts int type to Integer and store the elements. If we
fetch the elements of it returns object type and if we store it into primitive int type
then it automatically converts Integer to int type. See the below example.
import java.util.ArrayList;
class Demo
arrayList.add(200);
arrayList.add(300);
for(Integer i : arrayList) {
System.out.println(i);
100
200
300
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally.
String readLine() It is used to read a single line of text from the console.
char[] readPassword() It is used to read password that is not being displayed on the console.
Generics in Java
It would be nice if we could write a single sort method that could sort the elements
in an Integer array, a String array, or an array of any type that supports ordering.
Java Generic methods and generic classes enable programmers to specify, with a
single method declaration, a set of related methods, or with a single class
declaration, a set of related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch
invalid types at compile time.
Using Java Generic concept, we might write a generic method for sorting an array
of objects, then invoke the generic method with Integer arrays, Double arrays,
String arrays and so on, to sort the array elements.
Generic Methods
You can write a single generic method declaration that can be called with
arguments of different types. Based on the types of the arguments passed to the
generic method, the compiler handles each method call appropriately. Following are
the rules to define Generic Methods −
All generic method declarations have a type parameter section delimited by
angle brackets (< and >) that precedes the method's return type ( < E > in
the next example).
Each type parameter section contains one or more type parameters
separated by commas. A type parameter, also known as a type variable, is
an identifier that specifies a generic type name.
The type parameters can be used to declare the return type and act as
placeholders for the types of the arguments passed to the generic method,
which are known as actual type arguments.
A generic method's body is declared like that of any other method. Note that
type parameters can represent only reference types, not primitive types (like
int, double and char).