IMPORTANT CONCEPT OF JAVA PART-4
Importants points
------------------------
Character streams:-
Program uses character stream to perform input & output of character data. All character stream classes developed based on Reader & Writer classes
FileReader
------------
-- It is used to read the data from source one item at a time.
---To read the data from source use read() method of FileInputStream class.
public int read() throws java.io.IOException;
read() method returns first character Unicode value in the form of integer value.
FileWriter
---------------
--- It is used to write the data to destination one item at a time.
--- To write the data to destination use write() method of FileOutputStream class.
CharArrayWriter:-
--------------------------
It is used to write the data to multiple files & this call implements Appendable interface.
{
CharArrayWriter ch = new CharArrayWriter();
FileWriter fw1 = new FileWriter("a.txt");
FileWriter fw2 = new FileWriter("b.txt");
FileWriter fw3 = new FileWriter("c.txt");
FileWriter fw4 = new FileWriter("d.txt");
ch.writeTo(fw1);
ch.writeTo(fw2);
ch.writeTo(fw3);
ch.writeTo(fw4);
}
Note:-
-------
In above two streams(byte & character) it is possible to read only one item at time it increases number of read & write operations hence the performance is decreased.
To overcome above limitation to improve performance of the application instead of reading the data item by item, read the data line-by-line format to improve the performance.
BufferedReader
----------------------
--- It is used to read the data from source file in line by line format.
--- To read the data use readLine() method of BufferedReader class .
public java.lang.String readLine() throws java.io.IOException;
The readLine() method returns first line of the text file in the form of String
There are four buffered stream classes.
Buffered byte streams,
1. BufferedInputStream
2. BufferedOutputStream
A program can convert an un buffered stream into buffered streams.
new BufferedInputStream(new FileInputStream("sd.txt"));
new BufferedOutputStream(new FileOutputSream("sd.txt"));
Buffered Character streams,
3. BufferedReader
4. BufferedWriter
A program can convert an un buffered stream into buffered streams.
new BufferedReader(new FileReader("rsa.txt"));
new BufferedWriter(new FileWriter("as.txt"));
What is Exception?
---------------------------
----Dictionary meaning of the exception is abnormal termination.
----An exception is an event that occurs during execution of the program that disturbs normal flow of the program instructions.
-----If the application contains exception then the program terminated abnormally then the rest of the application is not executed.
There are two ways to handle the exceptions in java.
1) By using try-catch block.
2) By using throws keyword.
What is Exception Handling
-------------------------------------
The main objective of exception handling is to get normal termination of the application in order to execute rest of the application code.
Types of Exceptions:-
As per the sun micro systems standards The Exceptions are divided into three types
1) Checked Exception
2) Unchecked Exception
3) Error
Checked Exception:-
----- The Exceptions which are checked by the compiler at the time of compilation are called Checked Exceptions.
Examples:- IOException,SQLException,InterruptedException,ClassNotFoundException ...etc
Unchecked Exception:-
-----------------------------
----The exceptions which are not checked by the compiler at the time of compilation are called unchecked Exception.
ArithmeticException,ArrayIndexOutOfBoundsException,NumberFormatException….etc
What is Error
--------------------
---Error is caused due to lack of system resources.
Example: - StackOverFlowError, OutOfMemoryError, AssertionError…………etc
----It is not possible to handle the errors.
-----Error is an un-checked type exception.
Note:-
------The root class of exception handling is Throwable class
Exception handling by using Try –catch blocks:-
-------------------------------------------------------------
Syntax:-
try
{ exceptional code;
}
catch (ExceptionName reference_variable)
{ Code to run if an exception is raised (alternate code);
}
Whenever the exception is raised in the try block JVM won’t terminate the program immediately it will search corresponding catch block.
a). If the catch block is matched then that block will be executed & rest of the application executed & program is terminated normally.
b.) If the catch block is not matched program is terminated abnormally.
Note:-
----------
------In between try-catch blocks it is not possible to declare any statements, if we are declaring statements compiler will generate error message.
----- In exception handling must declare try with immediate catch block.
-----If the exception raised in try block the remaining code of try block is not executed.
------ Once the control is out of the try block the control never entered into try block once again.
------- Don’t take normal code inside try block because no guarantee all statements in try-block will be executed or not.
----When we declare multiple catch blocks then the catch block order must be child-parent but if we are declaring parent to child compiler will generate error message.
-----By using Exception class catch block it is possible to hold any type of exceptions.
------If there is no exception in try block the corresponding catch blocks are not checked
----Note:-
Finally block code is always executed irrespective of try and catch block code.
try
{
//risky code;
}
catch(Exception e)
{
//code to be run if the exception raised (handling code);
}
finally
{
//Clean-up code;(database connection closing , streams closing……etc)
}
It is not possible to write finally alone.
a. try-catch-finally ---> valid
b. try-catch ---> valid
c. catch-finally ---> invalid
d. try-catch-catch-finally ---> valid
e. try-finally ---> valid
f. catch-catch-finally ---> invalid
g. Try ---> invalid
h. Catch ---> invalid
i. Finally ---> invalid
There are two methods to print Exception information
--- toString()
----getMessage()
Multi Threading
------------------------
What is Thread?
----------------
1) Thread is nothing but separate path of sequential execution.
2) The independent execution technical name is called thread.
3) Whenever different parts of the program executed simultaneously that each and every part is called thread.
4) The thread is light weight process because whenever we are creating thread it is not occupying the separate memory it uses the same memory. Whenever the memory is shared means it is not consuming more memory.
5) Executing more than one thread a time is called multithreading.
main Thread:-
-------------------
1. It is used to create a new Thread(child Thread).
2. It must be the last thread to finish the execution because it perform various actions.
It is possible to get the current thread reference by using currentThread() method it is a static public method present in Thread class.
A thread can be created in two ways:-
-------------------------------------------------
1) By extending Thread class.
2) By implementing java.lang.Runnable interface
First approach to create thread extending Thread class:-
-----------------------------------------------------------------
Step 1:- Our normal java class will become Thread class whenever we are extending predefined Thread class.
class MyThread extends Thread
{
}
Step 2:- override the run() method to write the business logic of the Thread( run() method present in Thread class).
class MyThread extends Thread
{
public void run()
{
System.out.println("business logic of the thread");
System.out.println("body of the thread");
}
}
Step 2:- Create userdefined Thread class object.
MyThread t=new MyThread();
Step 3:- Start the Thread by using start() method of Thread class.
t.start();
Note:-it is not possible to start a thread twice
t.start();
t.start(); invalid
Second approach:-
1) Implementing the Runnable interface does not give developers any control over the thread itself, as it simply defines the unit of work that will be executed in a thread.
2) By implementing the Runnable interface, the class can still extend other base classes if necessary
Difference between t.start() and t.run():-
----------------------------------------------------
-----In the case of t.start(), Thread class start() is executed a new thread will be created that is responsible for the execution of run() method.
------But in the case of t.run() method, no new thread will be created and the run() is executed like a normal method call by the main thread
Arrays
-----------
---Arrays are used to represent group of elements as a single entity but these elements are homogeneous & fixed size.
----The size of Array is fixed it means once we created Array it is not possible to increase and decrease the size.
----- Array in java is index based first element of the array stored at 0 index.
Different ways to declare a Array:-
int[] values;
int []values;
int values[];
declaration & instantiation & initialization :-
Approach 1:- int a[]={10,20,30,40}; //declaring, instantiation, intialization
Approach 2:- int[] a=new int[100]; //declaring, instantiation
a[0]=10; //initialization
Example :- copy the data from one array to another array
class Test
{
public static void main(String[] args)
{
int[] a1={10,20,30,40,50,60,70,80};
int[] a2 = new int[7];
System.arraycopy(a1,1,a2,0,7);
for (int cc:copyto)
{ System.out.println(cc);
}
}
}
Example :- copy the data from one array to another array
class Test
{
public static void main(String[] args)
{
int[] a2={10,20,30,40,50,60,70,80};
int[] newarray=java.util.Arrays.copyOfRange(a2,1,4);
for (int aa:newarray)
{ System.out.println(aa); //20 30 40
}
}
}
Collections
---------------
1.The main objective of collections framework is to represent group of object as a single entity.
2.Collection API contains group of classes and interfaces that makes it easier to handle group of objects.
3.Collections are providing flexibility to store, retrieve, and manipulate data.
4.Collections are used to store both heterogeneous data(different type)& homogeneous data
5.Collections are growable in nature, it means based on our requirement it is possible to increase & decrease the size.
List interface:-
List interface common properties:-
1) All list class allows heterogeneous data.
2) All List interface implementation classes allows null insertion.
3) All classes allows duplicate objects.
implements List
1) ArrayList
collection classes are having 2-formats:-
1) Normal version (no type safety).
2) Generic version. (provide type safety )
The main purpose of the generics is to provide the type safety to avoid type casting problems.
-----Collections are not type safe it means we can’t give guarantee for the type of elements present in collection.
To overcome above problems use generics,
1) To provide type safety.
2) To overcome type casting problems.
in java it is recommended to use generic version of collections to provide the type safety.
Normal version
---------------------
ArrayList al = new ArrayList();
al.add("ras");
al.add("aas");
al.add(12)
Generic version
---------------------
Syntax:-
ArrayList<type-name> al = new ArrayList<>( );
------------
----The ArrayList is able to store only String data if we are trying to add any other data compiler will generate error message.
Example :- ArrayList<String> al = new ArrayList<>();
al.add("rsn");
al.add("ascu");
al.add(new Integer(10)); //compilation error
Iterator
----------
1.Used to retrieve the objects from collection classes
2.It is used to retrieve the data from all collection classes
3.It contains two methods
hasNext(): to check the objects available or not.
Next() : to retrieve the objects
4.Only forward direction.
5.Interface
ListIterator
------------
1.Used to retrieve the data from collection classes.
2.It contains 9 methods
3.Bidirectional cursor direction.
4.Interface
Map interface:-
------------------
HashMap implements Map
HashMap<keytype,valutetype> map=new HashMap<>();
We can also holds hasmap object into Map reference...
Map<String,String> map=new HashMap<>();
Post a Comment