CJ Unit 4
CJ Unit 4
JAVA
MODULE-4: Enumerations, Arrays, Multithreading, Exceptions
and Byte streams
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
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];
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};
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.
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.
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
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 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;
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
…………
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.
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.
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();
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 −
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));
OUTPUT:
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
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
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
//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..."); } }
_________________________________________________________________________________
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...");
}
}
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
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
Question Bank
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
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
11. Which of these is a method to clear all the data present in output buffers?
a) clear()
b) flush()
c) fflush()
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()