Java Notes
Java Operators:-
Uniary operators:-
++x:Increment first then print
x++:print then increment
x--:print then decrement
--x:decrement then print
ex:-
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
Java Unary Operator Example: ~ and !
~ :- if no. is positive add 1 to no & give minus sign
~:-if no is negative minus 1 from it dont give minus sign
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b= -10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts
from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from
0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to
the left side of a specified number of times.
for ex:-
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right operand.
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Java Shift Operator Example: >> vs >>>
public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first
condition is false. It checks the second condition only if the first one is
true.
ex:-
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}}
Java OR Operator Example: Logical || and Bitwise |:-
The logical || operator doesn't check the second condition if the first
condition is true. It checks the second condition only if the first one is
false.
The bitwise | operator always checks both conditions whether first
condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Java Thread Pool
Java Thread pool represents a group of worker threads that are waiting
for the job and reused many times.
In the case of a thread pool, a group of fixed-size threads is created. A
thread from the thread pool is pulled out and assigned a job by the
service provider. After completion of the job, the thread is contained in
the thread pool again.
Thread Pool Methods
newFixedThreadPool(int s): The method creates a thread pool of the
fixed size s.
newCachedThreadPool(): The method creates a new thread pool that
creates the new threads when needed but will still use the previously
created thread whenever they are available to use.
newSingleThreadExecutor(): The method creates a new thread.
Advantage of Java Thread Pool
Better performance It saves time because there is no need to create a
new thread.
Real time usage
It is used in Servlet and JSP where the container creates a thread pool
to process the request.
Risks involved in Thread Pools
The following are the risk involved in the thread pools.
Deadlock: It is a known fact that deadlock can come in any program
that involves multithreading, and a thread pool introduces another
scenario of deadlock. Consider a scenario where all the threads that are
executing are waiting for the results from the threads that are blocked
and waiting in the queue because of the non-availability of threads for
the execution.
Thread Leakage: Leakage of threads occurs when a thread is being
removed from the pool to execute a task but is not returning to it after
the completion of the task. For example, when a thread throws the
exception and the pool class is not able to catch this exception, then the
thread exits and reduces the thread pool size by 1. If the same thing
repeats a number of times, then there are fair chances that the pool will
become empty, and hence, there are no threads available in the pool
for executing other requests.
Resource Thrashing: A lot of time is wasted in context switching among
threads when the size of the thread pool is very large. Whenever there
are more threads than the optimal number may cause the starvation
problem, and it leads to resource thrashing.
Remaining Topics:-
Thread Group
Shutdownhook
performing multiple task
Java Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the unused
objects.
Advantage of Garbage Collection
· It makes java memory efficient because garbage collector removes
the unreferenced objects from heap memory.
· It is automatically done by the garbage collector(a part of JVM) so
we don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage
collection
3) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as:
protected void finalize(){}
The Garbage collector of JVM collects only those objects that are
created by new keyword. So if you have created any object without
new, you can use finalize method to perform cleanup processing
(destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
public static void gc(){}
Note: Garbage collection is performed by a daemon thread called
Garbage Collector(GC). This thread calls the finalize() method before
object is garbage collected.
Java Runtime class
Java Runtime class is used to interact with java runtime environment.
Java Runtime class provides methods to execute a process, invoke GC,
get total and free memory etc. There is only one instance of
java.lang.Runtime class is available for one java application.
The Runtime.getRuntime() method returns the singleton instance of
Runtime class.
1) public static Runtime getRuntime() returns the instance of
Runtime class.
2) public void exit(int status) terminates the current virtual
machine.
3) public void addShutdownHook(Thread hook) registers new
hook thread.
4) public Process exec(String command)throws IOException
executes given command in a separate process.
5) public int availableProcessors() returns no. of available
processors.
6) public long freeMemory() returns amount of free memory in
JVM.
7) public long totalMemory() returns amount of total memory in
JVM.
Remaining Topics
Java synchronization
Java I/O Tutorial
Java I/O (Input and Output) is used to process the input and produce
the output.
Java uses the concept of a stream to make I/O operation fast. The
java.io package contains all the classes required for input and output
operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes.
It's called a stream because it is like a stream of water that continues to
flow.
In Java, 3 streams are created for us automatically. All these streams are
attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
OutputStream
Java application uses an output stream to write data to a destination; it
may be a file, an array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may
be a file, an array, peripheral device or socket.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts
output bytes and sends them to some sink.
Useful methods of OutputStream
public void write(int)throws IOException is used to write a byte to
the current output stream.
2) public void write(byte[])throws IOException is used to write an
array of byte to the current output stream.
3) public void flush()throws IOException flushes the current output
stream.
4) public void close()throws IOException is used to close the current
output stream.
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.
Useful methods of InputStream
public abstract int read()throws IOException reads the next byte of data
from the input stream. It returns -1 at the end of the file.
2) public int available()throws IOException returns an estimate of the
number of bytes that can be read from the current input stream.
3) public void close()throws IOException is used to close the current
input stream.
InputStream Hierarchy
Java 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.
public class FileOutputStream extends OutputStream
FileOutputStream class methods
protected void finalize() It is used to clean up the connection with
the file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte
array to the file output stream.
void write(byte[] ary, int off, int len) It is used to write len bytes from
the byte array starting at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output
stream.
FileChannel getChannel() It is used to return the file channel object
associated with the file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated
with the stream.
void close() It is used to closes the file output stream.
Java 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.
public class FileInputStream extends InputStream
Java FileInputStream class methods
int available() It is used to return the estimated number of bytes that
can be read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data
from the input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of
data from the input stream.
long skip(long x) It is used to skip over and discards x bytes of data from
the input stream.
FileChannel getChannel() It is used to return the unique FileChannel
object associated with the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is
call when there is no more reference to the file input stream.
void close() It is used to closes the stream.
Java BufferedOutputStream Class
Java BufferedOutputStream class is used for buffering an output stream.
It internally uses buffer to store data. It adds more efficiency than to
write data directly into a stream. So, it makes the performance fast.
For adding the buffer in an OutputStream, use the
BufferedOutputStream class.
OutputStream os= new BufferedOutputStream(new
FileOutputStream("D:\\IO Package\\testout.txt"));
Java BufferedOutputStream class constructors
BufferedOutputStream(OutputStream os) It creates the new buffered
output stream which is used for writing the data to the specified output
stream.
BufferedOutputStream(OutputStream os, int size) It creates the new
buffered output stream which is used for writing the data to the
specified output stream with a specified buffer size.
Java BufferedOutputStream class methods
void write(int b) It writes the specified byte to the buffered output
stream.
void write(byte[] b, int off, int len) It write the bytes from the
specified byte-input stream into a specified byte array, starting with the
given offset
void flush() It flushes the buffered output stream.
Java BufferedInputStream Class
Java BufferedInputStream class is used to read information from
stream. It internally uses buffer mechanism to make the performance
fast.
The important points about BufferedInputStream are:
When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a
time.
When a BufferedInputStream is created, an internal buffer array is
created.
public class BufferedInputStream extends FilterInputStream
BufferedInputStream(InputStream IS) It creates the
BufferedInputStream and saves it argument, the input stream IS, for
later use.
BufferedInputStream(InputStream IS, int size) It creates the
BufferedInputStream with a specified buffer size and saves it argument,
the input stream IS, for later use.
Java BufferedInputStream class methods
int available() It returns an estimate number of bytes that can be
read from the input stream without blocking by the next invocation
method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int ln) It read the bytes from the specified
byte-input stream into a specified byte array, starting with the given
offset.
void close() It closes the input stream and releases any of the
system resources associated with the stream.
void reset() It repositions the stream at a position the mark
method was last called on this input stream.
void mark(int readlimit) It sees the general contract of the mark
method for the input stream.
long skip(long x) It skips over and discards x bytes of data from the input
stream.
remaining topics
sequenceinputstream
bytearrayoutputstream
bytearrayinputstream
Remaining Io packagen startting generics
Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes
the code stable by detecting the bugs at compile time.
Advantage of Java Generics
1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow
to store other objects.
Without Generics, we can store any type of objects.
2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than
runtime.
Generic class
A class that can refer to any type is known as a generic class. Here, we are using the T
type parameter to create the generic class of specific type.
Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating
a group of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
Hierarchy of Collection Framework
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
Methods of Iterator interface
1 public boolean hasNext() It returns true if the iterator has more elements otherwise it returns false.
2 public Object next() It returns the element and moves the cursor pointer to the next element.
3 public void remove() It removes the last elements returned by the iterator. It is less used.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.
It contains only one abstract method. i.e.,
3. Iterator<T> iterator()
It returns the iterator over the elements of type T.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
Methods of Collection interface
1 public boolean add(E e) It is used to insert an element in this collection.
2 public boolean addAll(Collection<? It is used to insert the specified collection elements in the
extends E> c) invoking collection.
3 public boolean remove(Object element) It is used to delete an element from the collection.
4 public boolean removeAll(Collection<?> It is used to delete all the elements of the specified
c) collection from the invoking collection.
5 default boolean removeIf(Predicate<? It is used to delete all the elements of the collection that
super E> filter) satisfy the specified predicate.
6 public boolean retainAll(Collection<?> c) It is used to delete all the elements of invoking collection
except the specified collection.
7 public int size() It returns the total number of elements in the collection.
8 public void clear() It removes the total number of elements from the
collection.
9 public boolean contains(Object element) It is used to search an element.
10 public boolean containsAll(Collection<? It is used to search the specified collection in the
> c) collection.
11 public Iterator iterator() It returns an iterator.
12 public Object[] toArray() It converts collection into array.
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of
the returned array is that of the specified array.
14 public boolean isEmpty() It checks if collection is empty.
15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as
its source.
16 default Stream<E> stream() It returns a sequential Stream with the collection as its
source.
17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in
the collection.
18 public boolean equals(Object element) It matches two collections.
19 public int hashCode() It returns the hash code number of the collection.