0% found this document useful (0 votes)
17 views

CJ Unit 4

This document provides an overview of key Java concepts covered in Module 4 including enumerations, arrays, multithreading, exceptions, and byte streams. It describes a compiled e-book on Core Java that covers these topics. The e-book was compiled by Beena Kapadia from Vidyalankar School of Information Technology according to predefined guidelines and includes all elementary learning tools for better understanding relevant concepts.

Uploaded by

Esha Worlikar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

CJ Unit 4

This document provides an overview of key Java concepts covered in Module 4 including enumerations, arrays, multithreading, exceptions, and byte streams. It describes a compiled e-book on Core Java that covers these topics. The e-book was compiled by Beena Kapadia from Vidyalankar School of Information Technology according to predefined guidelines and includes all elementary learning tools for better understanding relevant concepts.

Uploaded by

Esha Worlikar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Core

JAVA
MODULE-4: Enumerations, Arrays, Multithreading, Exceptions
and Byte streams

Vidyalankar School of Compiled by: Beena Kapadia


Information Technology
Wadala (E), Mumbai [email protected]
www.vsit.edu.in
Certificate
This is to certify that the e-book titled “CORE JAVA” comprises all
elementary learning tools for a better understating of the relevant concepts. This e-
book is comprehensively compiled as per the predefined eight parameters and
guidelines.

Signature Date: 19-11-2019


Ms. Beena Kapadia
Assistant Professor
Department of IT

DISCLAIMER: The information contained in this e-book is compiled and distributed for
educational purposes only. This e-book has been designed to help learners understand
relevant concepts with a more dynamic interface. The compiler of this e-book and
Vidyalankar Institute of Technology give full and due credit to the authors of the contents,
developers and all websites from wherever information has been sourced. We acknowledge
our gratitude towards the websites YouTube, Wikipedia, and Google search engine. No
commercial benefits are being drawn from this project.
Unit II Control Flow Statements,Iterations and Classes

Contents :
Enumerations, Arrays: Two Dimensional Arrays, Multi-Dimensional Arrays, Vectors, Adding
Elements To A Vector, Accessing Vector Elements, Searching For Elements In A Vector, Working With
The Size of The Vector.

Multithreading: the thread control methods, thread life cycle, the main thread, creating a thread,
extending the thread class.

Exceptions: Catching Java Exceptions, Catching Run-Time Exceptions, Handling Multiple Exceptions,
The finally Clause, The throws Clause

Byte streams: reading console input, writing console output, reading file, writing file, writing binary
data, reading binary data, getting started with character streams, writing file, reading file
Recommended Books :
Core Java 8 for Beginners, Vaishali Shah, Sharnam Shah, 1st Edition
Java: The Complete Reference , Herbert Schildt ,9th Edition
Murach’s beginning Java with Net Beans, Joel Murach , Michael Urban, 1st Edition
Core Java, Volume I: Fundamentals, Hortsman, 9th Edition
Core Java, Volume II: Advanced Features, Gary Cornell and Hortsman, 8th Edition
Core Java: An Integrated Approach , R. Nageswara Rao , 1st Edition

Prerequisites/linkages
Unit II Pre- Sem. I Sem. II Sem. III Sem. V Sem. VI
requisites
Control Flow -- IP WP, Python Enterprise Project
Statements,Iterati OOPS Java,
ons and Classes AWP
 Arrays
An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and may have one or more dimensions. A specific element in
an array is accessed by its index. Arrays offer a convenient means of grouping related
information.

 One-Dimensional Arrays
A one-dimensional array is a list of like-typed variables.
 Creating an Array
Creation of an array includes three steps:
1. Declare the array
2. Create memory locations
3. Put values into the memory locations.
1. Declaration of arrays
Two forms of declaration
type arrayname[]; Form1

type[ ] arrayname; Form2


Eg:
int number[];
int[] number;
Note:- do not enter the size of the arrays in the declaration

2. Creation of array
After declaring an array we need to allocate a memory using new keyword.
It has the following form:
arrayname = new type[size];

Eg: number=new int[5];


It also possible to combine the first two steps as follows:

int number=new int[5];

3. Initialization of arrays
It has the following form:
arrayname [subscript]=value;

Eg: number[0]=25;
number[1]=35;
……………..
……………..
number[4]=65;
We can also initialize array automatically in the same way as the ordinary variable when they
are declared as follows:
type arrayname[]={list of values} ;

Eg:
int number[]={25,35,45,55,65};

It is possible to assign an array object to another. Example:


int a[ ]= {1,2,3};
int b[ ];
b=a;
both arrays will have the same values.
 Array Length
In java all arrays store the allocated size in a variable named length. We can obtain
the length
Of the array a using a.length. Example:
int size=a.length;
// This program demonstrates the length array member.
class Length
{
public static void main(String args[])
{
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}
OUTPUT:
This program displays the following output:
length of a1 is 10
length of a2 is 8
length of a3 is 4

// This program demonstrates Sorting an array elements in Ascending Order

class NumberSorting {
public static void main(String args[])
{
int number[]={55,40,80,65,71};
int n=number.length;
System.out.print("Given List:");
for(int i=0;i<n;i++)
{
System.out.print(" " +number[i]);
}
System.out.println("");

for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(number[i]>number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}

}
}
System.out.print("Sorted List:");
for(int i=0;i<n;i++)
{
System.out.print(" " +number[i]);

}} }

OUTPUT:

Given List: 55 40 80 65 71
Sorted List: 40 55 65 71 80

 Two-Dimensional Arrays
 Creation of two dimensional array
int myarr[ ][ ];
myarr=new int[3][4];
OR
int myarr [][ ]=new int[3][4];
This creates a table that can store 12 integer values, four across and three down.

 Two dimensional array may be initialized as follows:


int table[ ][ ]={ {0,0,0} {1,1,1}};
Initializes the elements of the first row to zero and the second row to one. The
initialization is done by row by row.

 We can also initialize a two-dimensional array in the form of matrix


int table[ ][ ]={
{0,0,0}
{1,1,1}
};
 To refer to the value stored in two-dimensional array we can use the following
statement
int value=table[1][2];
This retrieves the value stored in the second row and third column of table martix.
// This program demonstrates creation of two-dimesional array.

class twodimarr
{
public static void main(String args[])
{
int i,j;
int table[][]=new int[5][5];
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==j)
table[i][j]=1;
else
table[i][j]=0;
}
}

for(i=0;i<5;i++)
{
System.out.println(" ");
for(j=0;j<5;j++)
{
System.out.print(table[i][j]+" ");

}
}

}
}
OUTPUT:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

Vector
 Vector implements a dynamic array that means it can grow or shrink as required. Like
an array, it contains components that can be accessed using an integer index
 They are very similar to ArrayList but Vector is synchronised and have some legacy
method which collection framework does not contain.
 Constructor:
 Vector():- Creates a default vector of initial capacity is 10.
 Vector(int size):- Creates a vector whose initial capacity is specified by size.
 Vector(int size, int incr):- Creates a vector whose initial capacity is specified by size
and increment is specified by incr. It specifies the number of elements to allocate
each time that a vector is resized upward.
 Vector(Collection c):- Creates a vector that contains the elements of collection c.

 Methods
Sr. Method Description
No.
1 void add(int index, Object element) Inserts the specified element at the specified
position in this Vector.
2 boolean add(Object o) Appends the specified element to the end of this
Vector.
3 boolean addAll(Collection c) Appends all of the elements in the specified
Collection to the end of this Vector, in the order
that they are returned by the specified
Collection's Iterator.
4 boolean addAll(int index, Inserts all of the elements in in the specified
Collection c) Collection into this Vector at the specified
position.
5 void addElement(Object obj) Adds the specified component to the end of this
vector, increasing its size by one.
6 int capacity() Returns the current capacity of this vector.
7 void clear() Removes all of the elements from this vector.
8 void copyInto(Object[] anArray) Copies the components of this vector into the
specified array.
9 Object elementAt(int index) Returns the component at the specified index.
10 void insertElementAt(Object obj, int Inserts the specified object as a component in
index) this vector at the specified index.
11 Object remove(int index) Removes the element at the specified position in
this vector.
12 boolean removeAll(Collection c) Removes from this vector all of its elements that
are contained in the specified Collection.
13 void removeAllElements() Removes all components from this vector and
sets its size to zero.
14 boolean removeElement(Object obj) Removes the first (lowest-indexed) occurrence
of the argument from this vector.
15 void removeElementAt(int index) Removes element at the specified position in
this Vector.

//Demonstrate various Vector operations.


import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " + v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " + v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " + v.capacity());
System.out.println("First element: " + (Integer)v.firstElement());
System.out.println("Last element: " + (Integer)v.lastElement());

if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println(); } }
OUTPUT:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
First element: 1
Last element: 5.45
Vector contains 3. Elements in vector: 1 2 3 4 5.45

Accessing Vector Elements


The get(int index) method is used to return the element at the specified index
position in this Vector.
Example
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
// create an empty Vector vec with an initial capacity of 4
Vector<Integer> vec = new Vector<Integer>(4);

// use add() method to add elements in the vector


vec.add(4); vec.add(3); vec.add(2); vec.add(1);

// let us get the 3rd element of the vector


System.out.println("Third element is :"+vec.get(3));
}}
OUTPUT:
Third element is :1
Searching For Elements In A Vector
1. public int indexOf(Object o):
It returns the index of first occurrence of Object o in Vector.
2. public int indexOf(Object o, int startIndex):
It returns the index of the first occurrence of the Object o in this vector,
searching forwards from startIndex (inclusive).
3. public int lastIndexOf(Object o):
It returns the index of last occurrence of Object o in Vector.
4. public int lastIndexOf(Object o, int startIndex):
It returns the index of the last occurrence of the specified element in this
vector, searching backwards from startIndex(inclusive).

Example
import java.util.Vector;
public class SearchVector {
public static void main(String[] args) {
// Create a Vector object
Vector<String> vector = new Vector<String>();
//Add elements to Vector
vector.add("Kate");
vector.add("Patt");
vector.add("Kluge");
vector.add("Karon");
vector.add("Patt");
vector.add("Monica");
vector.add("Patt");

//This would return the index of first occurrence


int first_index = vector.indexOf("Patt");
System.out.println("First Occurrence of Patt at index: "+first_index);

//This would return the index of last occurrence


int last_index = vector.lastIndexOf("Patt");
System.out.println("Last Occurrence of Patt at index: "+last_index);

//This would start search from index 2(inclusive)


int after_index = vector.indexOf("Patt", 2);
System.out.println("Occurrence after index 2: "+after_index);

//This would search the element backward starting from index 6(inclusive)
int before_index = vector.lastIndexOf("Patt", 6);
System.out.println("Occurrence before index 6: "+before_index);
}}
Output:
First Occurrence of Patt at index: 1
Last Occurrence of Patt at index: 6
Occurrence after index 2: 4
Occurrence before index 6: 6
Working With The Size of The Vector
The int size() method is used to return the number of components in this vector.

import java.util.Vector;

public class VectorDemo {


public static void main(String[] args) {
// create an empty Vector vec with an initial capacity of 4
Vector<Integer> vec = new Vector<Integer>(4);
// use add() method to add elements in the vector
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(1);
// let us print the size of the vector
System.out.println("Size of the vector: "+vec.size());
} }
OUTPUT:
Size of the vector: 4

Multithreading
Benefits of Multithreading
1. Enables programmer to do multiple things at one time.
2. Programmer can divide a long program into threads and execute them in parallel which
eventually increases the speed of the program execution.
3. Improved performance and concurrency
4. Simultaneous access to multiple applications
Thread is Running
Output:
Thread is Running
OUTPUT:
A:1
A:2
A:3
A:4
A:5
Exit from A
C:1
C:2
C:3
C:4
C:5
Exit from C
Exception Handling
Introduction
 An error may produce an incorrect output or may terminate the execution of the program
abruptly or even may cause the system to crash.
 Types of Errors
 Compile-time error
 Run-time error
 All syntax errors will be detected and displayed by the Java compiler and therefore these
errors are known as compile-time errors.
 Whenever the compiler displays an error it will not create the .class file.
 The most common problems are:
 Missing semicolons
 Missing(or mismatch )brackets in classes and methods
 Missing double quotes
 Use of undeclared variables
 Use of = in place of ==operator
 And so on
 Sometimes , a program may compile successfully creating the .class file but may not run
properly. Such programs may produce wrong results due to wrong logic or may terminate
due to errors such as stack overflow.
 The most common run-time errors are:
 Dividing an integer by zero
 Accessing an element that is out of the bounds of an array
 Trying to store the value into an array of an incompatible class or type
 Attempting to use a negative size of an array
 Converting invalid string to a number
 And so on

Exceptions
 An exception is a condition that is caused by a run – time error in the program.
 When the java interpreter encounters an error such as dividing an integer by zero, it creates
an exception object and throws it (i.e. informs us that an error has occured).
 The most general exceptions are subclasses of the standard type RuntimeException. These
exceptions need not be included in any method’s throws list. These are called unchecked
exceptions because the compiler does not check to see if a method handles or throws these
exceptions.
 The unchecked exceptions defined in java.lang are listed in Table 10-1.
 Table 10-2 lists those exceptions defined by java.lang that must be included in a method’s
throws list if that method can generate one of these exceptions and does not handle it itself.
These are called checked exceptions.
Exception handling mechanism

Syntax of exception handling code

…………
try
{
statement; // generates an exception
}
Catch(Exception-type e)
{
statement; //processes the exception
}
…………
…………

Java uses a keword “try” to preface a block of code that is likely to cause an error condition and
“throw” an exception. A catch block defined by “catch” catches an exception thrown by the try
block and handles it appropriately. The catch block is added immediately after try block.
The try block can have one or more statements that could generate an exception. If any one
statement generates an exception, the remaining statements in the block are skipped and execution
jumps to the catch block that is placed next to the try block.

//Program to handle Arithmetic Exception

import java.util.*;

class exception
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x;
try
{

x=a/(b-c);
System.out.println("x="+x);

catch(ArithmeticException e)
{
System.out.println("Division by zero");
}

OUTPUT:

Division by Zero
Multiple Catch Statements

It is possible to have more than one catch statement in the catch block as illustrated below:

…………
try
{
statement; // generates an exception
}
Catch(Exception-type1 e)
{
statement; //processes exception type1
}
Catch(Exception-type2 e)
{
statement; //processes exception type2
}
…………
…………

Catch(Exception-typeN e)
{
statement; //processes exception type N
}
When an exception in a try block is generated, the java treats the multiple catch statements like cases
in a switch statement. The first statement whose parameter matches with the exception object will be
executed, and the remaining statements will be skipped.
We also can have a catch statement with an empty block to avoid program abortion.
Example:
catch(Exception e);

The catch statement simply ends with semicolon, which does nothing.
This statement will catch an exception and then ignore it.

Program to handle multiple catch block

class exception
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=3;
int x;
int arr[]={3,4,5,6};

try
{
x=a/(b-c);
System.out.println("x="+x);
System.out.println("arr[5]="+arr[5]);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException fe)
{
System.out.println("Array index not found");
}
catch(ArrayStoreException ae)
{
System.out.println("Array type not matched");
}}}

OUTPUT:
x=5
Arra index not found
Using finally statement

 Finally statement can be used to handle an exception that is not caught by any of the previous
catch statements.
 Finally blocked can be used to handle any exception generated within a try block .
 It may be added immediately after the try block or after the last catch block shown as
follows:
try
{
-------------
}
finally
{
------------------
}

OR

try
{

--------------
}

catch(…)
{
----------
}

catch(…)
{
-----------
}

finally
{
--------------
}

When finally block is defined, this is guaranteed to be execute, regardless of whether or not
in exception is thrown.
As a result, we can use it to perform certain house-keeping operations such as closing files
and releasing system resources.
Throwing our own exception
 To handle our own exception we use throw keyword.
 Syntax:
throw new Throwable_subclass;
 Example:
throw new ArithmeticException();
throw new IOException();

Program to handle your own exception

class myexception extends Exception


{
int detail;
myexception(int a)
{ detail=a; }
void message()
{ System.out.println("MyException"+detail); }
}

class exceptiondemo
{
static void compute(int a) throws myexception
{
System.out.println("Called compute " +a);
if(a>10)
{ throw new myexception(a); }
System.out.println("Normal exit");
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}

catch(myexception e)
{
System.out.println("Caught "+e);
e.message();
} } }
Output:
Called compute 1
Normal exit
Called compute 20
Caught myexception
MyException20
Source:- https://www.youtube.com/watch?v=LpfHEjEoDCg

Byte Streams
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.


Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are
descended from InputStream and OutputStream.
Reading Console Input
In Java, there are three different ways for reading input from the user in the command line
environment(console).
1. Using Buffered Reader Class
This is the Java classical method to take input, Introduced in JDK1.0. This method is used by
wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped
in a BufferedReader, we can read input from the user in the command line.
Advantages
The input is buffered for efficient reading.
Drawback:
The wrapping code is hard to remember.
Sr.No. Method Description
1 int read() It is used for reading a single character.
2 int read(char[] cbuf, int off, int len) It is used for reading characters into a portion of an
array.
3 String readLine() It is used for reading a line of text.
4 void close() It closes the input stream and releases any of the
system resources associated with the stream.
Example

import java.io.*;
public class Test
{
public static void main(String[] args) throws IOException
{
//Enter data using BufferReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// Reading string data using readLine


System.out.println("Enter your name:-");
String name = br.readLine();

// Reading integer data using readLine


System.out.println("Enter your age:-");
int age = Integer.parseInt(br.readLine());

// Printing the string


System.out.println("Your Name:-"+name);

// Printing the Integer


System.out.println("Your Age:-"+age);
}
}

OUTPUT:

Enter your name:- Bean


Enter your age:- 30
Your Name:- Bean
Your Age:-30

2. Using Scanner Class


This is probably the most preferred method to take input. The main purpose of the
Scanner class is to parse primitive types and strings using regular expressions, however it is
also can be used to read input from the user in the command line.

Advantages:
o Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the
tokenized input.
o Regular expressions can be used to find tokens.
Drawback:
The reading methods are not synchronized
Example

import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
System.out.println("Enter a string:-");
String s = in.nextLine();

System.out.println("Enter an Integer:-");
int a = in.nextInt();

System.out.println("Enter a float:-");
float b = in.nextFloat();

System.out.println(“Entered string:-"+s);
System.out.println("Entered integer:-"+a);
System.out.println("Entered float:-"+b);
}
OUTPUT:

Enter a string:-VSIT
Enter an Integer:-27
Enter a float:-21.45

Entered string:-VSIT
Entered integer:-27
Entered float:-21.45
3. Using Console Class

It has been becoming a preferred way for reading user’s input from the command line. In
addition, it can be used for reading password-like input without echoing the characters entered by the
user; the format string syntax can also be used (like System.out.printf()).
Advantages:
Reading password without echoing the entered characters.
Reading methods are synchronized.
Format string syntax can be used.
Drawback:
Does not work in non-interactive environment (such as in an IDE).

Example
import java.io.Console;
class ReadStringTest
{
public static void main(String args[])
{
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
} }
Output:
Enter your name: java
Welcome java

writing console output


print and println methods in System.out are mostly used for console output.
These methods are defined by the class PrintStream which is the type of object referenced by
System.out. System.out is the byte stream.
PrintStream is the output derived from OutputStream.write() method is also defined in
PrintStream for console output.
void write(int byteval):- This method writes the byte specified by byteval. Although byteval is
declared as an integer, only the low-order eight bits are written.

Example:-
class WriteConsoleOutput
{
public static void main(String args[])
{
int y;
y = 'X';
System.out.write(y);
System.out.write('\n');
} }

Output:-
X
Reading From file
FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data
(streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data.
But, for reading streams of characters, it is recommended to use FileReader class.

Constructor:-
Constructor Description
FileInputStream(File file) This creates a FileInputStream by opening a connection to an
actual file, the file named by the File object file in the file
system.
FileInputStream(String name) This creates a FileInputStream by opening a connection to an
actual file, the file named by the path name name in the file
system.

Method

//Read single character

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[])throws IOException {
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
} }
//Read all Characters

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file.
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.

Constructor:-
Constructor Description
FileOutputStream(File file) This creates a file output stream to write to the file represented
by the specified File object.
FileOutputStream(File file, This creates a file output stream to write to the file represented
boolean append) by the specified File object.
FileOutputStream(String name) This creates an output file stream to write to the file with the
specified name.
FileOutputStream(String name, This creates an output file stream to write to the file with the
boolean append) specified name.

Methods:-
//Write byte

public class FileOutputStreamExample {


public static void main(String args[])throws IOException{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}}

//write string
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[])throws IOException {
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b); fout.close();
System.out.println("success..."); } }
_________________________________________________________________________________

Reading Binary Data


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.
Constructor:-
Constructor Description
DataInputStream(InputStream in) This creates a DataInputStream that uses the specified
underlying InputStream.
Methods
//Reading the data from the file testout.txt file
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
} } }

DataOutputStream Class
Java DataOutputStream class allows an application to write primitive Java data types to the
output 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.

Constructor:-
Constructor Description
DataOutputStream(OutputStream in) This creates a DataOutputStream that uses the specified
underlying OutputStream.
Methods
//Writing the data to a text file testout.txt using DataOutputStream class
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}

Getting Started with 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 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.

1. Reading File
FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class. It is character-oriented class which is used for file handling in
java.

Constructor

Methods

//Reading the data from the file testout.txt file


import java.io.*;
public class FileReaderExample {
public static void main(String[] args) throws IOException {
FileReader f=new FileReader(“testout.txt”);
BufferedReader br=new Buffered(f);
String s=””;
While((s=br.readLine())!=null)
System.out.print(s);
f.close();
} }

2. Writing File

FileWriter Class
Java FileWriter class is used to write character-oriented data to a file. It is character-
oriented class which is used for file handling in java. Unlike FileOutputStream class, you
don't need to convert string into byte array because it provides method to write string
directly.

Constructor
Methods

//Writing the data to the file testout.txt file


import java.io.*;
public class FileWriterExample {
public static void main(String[] args) throws IOException {
FileWriter f=new FileWriter(“testout.txt”);
String s=”Core Java,Pyhton,C++,C,PHP”;
f.write(s);
f.close();
} }
Source:- https://www.youtube.com/watch?v=kD_HqZP8MLY

Question Bank

1. Explain Multidimensional Array with example.


2. What is vector? List and explain any two constructor and three methods of Vector.
3. Write a program that accepts a shopping list of 5 items from the user and stores them in a
vector and perform the following operations:
a. Delete an item
b. To add an item at a specified location
c. To add an item at the end of the list
d. To print the contents of the vector.
4. Explain lifecycle of the thread.
5. What are the different ways of creating a Thread in java? Explain any one with the help of a
program
6. Define thread priority. Explain the method of changing thread priorities with an example
program.
7. Short note on: a. try b. catch c. throw d. throws e. finally
8. ‘Multiple catch can be associated with a single try-block’- Comment and justify the answer.
9. ‘user-defined exception can be created in java’ – explain the concept with an example
program
10. Short note on DataInputStream and DataOutputStream class in java.
11. How to use CharacterStreams for reading from And writing to a file in java.
12. Define FileInputStream and FileOutputStream classes in java. List and explain its
constructors and methods.

Multiple Choice Questions


1. Which one of the following is a valid statement?
a. char []=new char();
b. char[] c = new char[5];
c. char[] c = new char(4);
d. char[] c = new char[];

2. What is the name of data member of class Vector which is used to store number of elements in the
vector?
a. length
b. elements
c. elementCount
d. capacity

3. Which of these methods is used to add elements in vector at specific location?


a. add()
b. set()
c. AddElement()
d. addElement()

4. When you pass an array to a method, the method receives ________ .


a. A copy of the array.
b. A copy of the first element.
c. The reference of the array.
d. The length of the array.

5. Which of these keywords is not a part of exception handling?


a. try
b. finally
c. thrown
d. catch

6. Which exception is thrown when divide by zero statement executes? permit data to be hidden
from other classes
a. NumberFormatException
b. ArithmeticException
c. NullPointerException
d. None of these

7. Which of the following blocks execute compulsorily whether exception is caught or not.
a. finally
b. catch
c. throw
d. throws

8. Which of these exception is thrown in cases when the file specified for writing it not found?
a. IOException
b. FileException
c. FileNotFoundException
d. FileInputException

9. Which of these values is returned by read() method is end of file (EOF) is encountered?
a) 0
b) 1
c) -1
d) Null

10. Which of these class is used to read characters in a file?


a) FileReader
b) FileWriter
c) FileInputStream
d) InputStreamReader

11. Which of these is a method to clear all the data present in output buffers?
a) clear()
b) flush()
c) fflush()
d) close()

12. Which of these methods is used to write() into a file?


a) put()
b) putFile()
c) write()
d) writeFile()

13. Which of the following method(s) not included in InputStream class.


a) available( )
b) reset( )
c) flush( )
d) close( )

14. The ……………………… method of the BufferedReader class is used for reading lines of text
from the console, the file or other input streams.
a) read( )
b) read(byte[]b)
c) readLine( )
d) readByte( )

15. Which of these method of InputStream is used to read integer representation of next available
byte input?
a. scanf()
b. get()
c. read()
d. getInteger()

You might also like