Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
203 views

Java CoreJava

This document provides an overview of core Java concepts including: - Arrays and common array operations like sorting and copying. It also discusses the difference between arrays and collections like ArrayList. - Key interfaces like Comparable and Comparator that are used to compare objects. It also covers exceptions and how they are handled in Java. - Commonly used data structures like HashMap, HashSet, TreeMap and how they work. - Other core concepts like generics, iterators, serialization and final keywords. The document serves as a reference for basic but important Java concepts that form the foundation of any Java program.

Uploaded by

Dipen Dahal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views

Java CoreJava

This document provides an overview of core Java concepts including: - Arrays and common array operations like sorting and copying. It also discusses the difference between arrays and collections like ArrayList. - Key interfaces like Comparable and Comparator that are used to compare objects. It also covers exceptions and how they are handled in Java. - Commonly used data structures like HashMap, HashSet, TreeMap and how they work. - Other core concepts like generics, iterators, serialization and final keywords. The document serves as a reference for basic but important Java concepts that form the foundation of any Java program.

Uploaded by

Dipen Dahal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 75

CORE JAVA

Contents
CORE JAVA...................................................................................................................................................6
128 == 128 returns false?........................................................................................................................6
Array........................................................................................................................................................7
ArrayIndexOutOfBoundsException? When it occurs?.........................................................................7
Copying an array into another array....................................................................................................7
Drawbacks of the arrays?....................................................................................................................7
Equality of two arrays OR Compare the two arrays.............................................................................7
jagged arrays in java? Give example?..................................................................................................8
Obtain an array from an ArrayList class...............................................................................................8
Sort the array elements?.....................................................................................................................8
Array and ArrayList..................................................................................................................................9
ArrayList vs LinkedList..............................................................................................................................9
ArrayList and Vector..............................................................................................................................10
Collection and Collections.....................................................................................................................11
Comparator interface? When to use?...................................................................................................11
Comparable interface? When to use?...................................................................................................12
Comparator vs Comparable...................................................................................................................13
Copy.......................................................................................................................................................13
Deep copy and Shallow copy.............................................................................................................13
Implementing Deep Cloning..............................................................................................................14
Implementing Shallow Cloning..........................................................................................................15
Covariant return type? Example............................................................................................................17
Data types and their default values?.....................................................................................................17
Dictionary class......................................................................................................................................19
Enumeration vs Iterator........................................................................................................................19
Error vs Exception..................................................................................................................................19
Equals method.......................................................................................................................................20
Equals Method and == Operator...........................................................................................................21
Exception...............................................................................................................................................21
Checked Exceptions...........................................................................................................................21
ClassNotFoundException vs NoClassDefFoundError..........................................................................22

1
CORE JAVA

How JAVA exception handlings work?...............................................................................................22


java.lang.Throwable..........................................................................................................................22
OutOfMemoryError in Java................................................................................................................22
throw, throws and Throwable...........................................................................................................23
Unchecked Exceptions.......................................................................................................................23
Externalizable interface.........................................................................................................................24
Fail Fast vs Fail Safe Iterators.................................................................................................................25
File name - Is Empty .java a valid source file name?..............................................................................25
Final keyword........................................................................................................................................25
Final Variable.....................................................................................................................................25
Final Method.....................................................................................................................................25
Final Class..........................................................................................................................................25
Blank or uninitialized final variable....................................................................................................26
Static Blank final variable...................................................................................................................26
Final, finally and finalize keywords........................................................................................................26
final....................................................................................................................................................26
finally.................................................................................................................................................26
finalize...............................................................................................................................................26
Garbage collection.................................................................................................................................27
Generic collection..................................................................................................................................27
hashCode() method?.............................................................................................................................27
Hash collision in Hashtable and how it is handled?...............................................................................28
HashMap vs HashTable..........................................................................................................................29
HashMap vs HashSet.............................................................................................................................30
HashMap vs TreeMap............................................................................................................................31
HashSet..................................................................................................................................................31
HashSet vs TreeSet................................................................................................................................31
Iterator..................................................................................................................................................33
Iterator and ListIterator.........................................................................................................................33
Iterator and Enumeration......................................................................................................................33
IntegerCache Class.................................................................................................................................34
J2EE and JEE are same?.........................................................................................................................34
J2SE and J2EE Differences......................................................................................................................34

2
CORE JAVA

jar vs war vs ear.....................................................................................................................................34


Java 8 Features......................................................................................................................................34
1. forEach() method in Iterable interface......................................................................................35
2. default and static methods in Interfaces...................................................................................35
3. Functional Interfaces and Lambda Expressions.........................................................................36
4. Java Stream API for Bulk Data Operations on Collections..........................................................36
5. Java Time API.............................................................................................................................37
6. Collection API improvements.....................................................................................................37
7. Concurrency API improvements................................................................................................38
8. Java IO improvements...............................................................................................................38
9. Miscellaneous Core API improvements.....................................................................................38
java vs javaw vs javaws..........................................................................................................................39
JDK.........................................................................................................................................................39
JRE.........................................................................................................................................................40
JVM........................................................................................................................................................40
LinkedList...............................................................................................................................................41
List and Set............................................................................................................................................41
Literals?.................................................................................................................................................42
Main method.........................................................................................................................................42
Change the name of main method? if yes explain how? if no then  why?.........................................42
final: declare main method as final?..................................................................................................42
Overload main() method?.................................................................................................................43
private: declare main method private?.............................................................................................43
public: why main method is public?..................................................................................................43
strictfp: declare main method as strictfp?.........................................................................................44
synchronized: declare main method as synchronized?.....................................................................44
Marker interface..? When to use?.........................................................................................................44
Memory.................................................................................................................................................45
Stack and Heap Memory...................................................................................................................45
Stack vs Heap?...................................................................................................................................45
Modifier.................................................................................................................................................45
Access Modifiers................................................................................................................................46
Access Modifiers.............................................................................................................................46

3
CORE JAVA

Non-Access Modifiers........................................................................................................................46
MultiMap...............................................................................................................................................47
Overloading and Overriding..................................................................................................................48
Pass by Value and Pass by reference?...................................................................................................49
Pool.......................................................................................................................................................50
Properties file........................................................................................................................................50
Serialization? When to use?  Advantage?..............................................................................................50
Serializable vs Externalizable.................................................................................................................50
Set vs Map.............................................................................................................................................51
Statement vs PreparedStatement vs CallableStatement.......................................................................51
ExecuteQuery, executeUpdate and Execute......................................................................................52
String.....................................................................................................................................................54
Immutable String in JAVA..................................................................................................................54
Is String a data Type?.........................................................................................................................54
Is String final?....................................................................................................................................55
Is String thread safe?.........................................................................................................................55
String.................................................................................................................................................55
StringBuffer........................................................................................................................................55
StringBuilder......................................................................................................................................56
String pool?........................................................................................................................................57
String vs StringBuffer vs StringBuilder?..............................................................................................57
Synchronize List, Set and Map elements...............................................................................................57
Thread...................................................................................................................................................57
Advantages of Thread?......................................................................................................................58
Create Thread in Java?.......................................................................................................................58
Deadlock............................................................................................................................................59
Extends Thread vs Implements Runnable..........................................................................................59
Extends Thread is better than implement Runnable.........................................................................60
Thread pool.......................................................................................................................................60
Thread  safety?..................................................................................................................................60
Thread states.....................................................................................................................................60
Life cycle of thread............................................................................................................................60
Monitor/manage thread....................................................................................................................61

4
CORE JAVA

Notify vs notifyall?.............................................................................................................................63
Methods............................................................................................................................................63
Priority...............................................................................................................................................64
Process vs Thread..............................................................................................................................65
Semaphore........................................................................................................................................65
States of Thread?...............................................................................................................................65
Thread safety and synchronization....................................................................................................67
User Threads Vs Daemon Threads.....................................................................................................67
wait() and notify()..............................................................................................................................67
wait  vs  sleep?...................................................................................................................................68
wait() and sleep() methods................................................................................................................68
Yield vs sleep?....................................................................................................................................69
TreeSet..................................................................................................................................................69
Type.......................................................................................................................................................69
Synchronization.....................................................................................................................................69
Variable.................................................................................................................................................70
Default value of the local variables?..................................................................................................70
Transient vs volatile variable /ˈvɒl ə tl...............................................................................................70
Web app vs enterprise app....................................................................................................................70
Web server vs application server...........................................................................................................71

5
CORE JAVA

CORE JAVA

Some other resources:

1
2 public class MainClass
{
3 public static void main(String[] args)
4 {
5 Integer i1 = 128;
6
7 Integer i2 = 128;
8
9 System.out.println(i1 == i2);
}
10 }
11

OUTPUT: false

Whenever you are creating Integer objects using auto-boxing, compiler rewrites that statement
with Integer.valueOf(int i) method. For example, the statement “Integer i1 = 127” will be rewritten by the
compiler as below.

1 Integer i1 = Integer.valueOf(127);

Integer.ValueOf() method creates the java.lang.Integer object by passing the specified ‘int‘ value. Actually, it


doesn’t create the new objects for all the values you pass. This method is implemented such that the
frequently used values are cached. I.e. internally it maintains an array of Integer objects where Integer
objects for frequently requested values are created and stored at the time of VM initialization itself. By
default, these values will be from -128 to 127. So, for any number you pass between -128 and 127 (inclusive),
it doesn’t create the new Integer object. Instead it returns already cached object from the array. If you pass
the number beyond this range, then only it creates a new Integer object. 

Below is the source code of Integer.valueOf() method.

1 public static Integer valueOf(int i) {


2         if (i >= IntegerCache.low && i <= IntegerCache.high)
3             return IntegerCache.cache[i + (-IntegerCache.low)];
4         return new Integer(i);
5     }

6
CORE JAVA

From the above code, it is clear that Integer.valueOf() method doesn’t create new Integer objects for the
values between IntegerCache.low and IntegerCache.high. Instead it returns the already cached object
representing that value fromIntegerCache.cache array. By default, IntegerCache.low =
-128and  IntegerCache.high = 127.  If you pass the values beyond this range, then only it creates new Integer
object.

Array
ArrayIndexOutOfBoundsException? When it occurs?

ArrayIndexOutOfBoundsException is a run time exception which occurs when your program tries to access
invalid index of an array i.e negative index or index higher than the size of the array.

Copying an array into another array

There are four methods available in java to copy an array.

1) Using for loop

2) Using Arrays.copyOf() method

3) Using System.arraycopy() method

4) Using clone() method of an array instance.////////

Drawbacks of the arrays?

The main drawback of the arrays is that arrays are of fixed size. You can’t change the size of the array once
you create it. Therefore, you must know how many elements you want in an array before creating it. You
can’t insert or delete the elements once you create an array. Only you can do is change the value of the
elements.

Equality of two arrays OR Compare the two arrays

You can use Arrays.equals() method to compare one dimensional arrays and to compare multidimensional
arrays, use Arrays.deepEquals() method.

7
CORE JAVA

jagged arrays in java? Give example?

Jagged arrays in java are the arrays containing arrays of different length. Jagged arrays are also
multidimensional arrays. They are also called as ragged arrays.

Obtain an array from an ArrayList class

You can convert from ArrayList to traditional arrays using “toArray()” method

Sort the array elements?

8
CORE JAVA

You can sort the array elements using Arrays.sort() method. This method internally uses quick sort
algorithm to sort the array elements.

Array and ArrayList


Array ArrayList

Arrays are of fixed length. ArrayList is of variable length.

You can’t change the size of the array once you create Size of the ArrayList grows and shrinks as you add or

it. remove the elements.

Array does not support generics. ArrayList supports generics.

You can use arrays to store both primitive types as well

as reference types. You can store only reference types in an ArrayList.

ArrayList vs LinkedList

Although both ArrayList and LinkedList implement List interface, they have some differences between them.


The performance and internal working nature of both varies significantly. 

LinkedList

ArrayList

Elements in the LinkedList are called as nodes,

where each node consists of three things –

ArrayList is an index based data structure where Reference to previous element, Actual value of the

Structure each element is associated with an index. element and Reference to next element.

Insertion and Insertions and Removals in the middle of the Insertions and Removals from any position in the

Removal ArrayList are very slow. Because after each LinkedList are faster than the ArrayList. Because

insertion and removal, elements need to be there is no need to shift the elements after every

9
CORE JAVA

insertion and removal. Only references of previous

shifted. and next elements are to be changed.

Insertion and removal operations in ArrayList Insertion and removal in LinkedList are of order

are of order O(n). O(1).

Retrieval of elements in LinkedList is very slow

compared to ArrayList. Because to retrieve an

Retrieval of elements in the ArrayList is faster element, you have to traverse from beginning or

than the LinkedList . Because all elements in end (Whichever is closer to that element) to reach
Retrieval
ArrayList are index based. that element.
(Searching or

getting an Retrieval operation in ArrayList is of order of

element) O(1). Retrieval operation in LinkedList is of order of O(n).

LinkedList is not of type Random Access. i.e

elements cannot be accessed randomly. you have

ArrayList is of type Random Access. i.e elements to traverse from beginning or end to reach a

Random Access can be accessed randomly. particular element.

LinkedList, once defined, can be used as ArrayList,

Stack, Queue, Singly Linked List and Doubly Linked

Usage ArrayList cannot be used as a Stack or Queue. List.

ArrayList requires less memory compared to LinkedList requires more memory compared to

Memory LinkedList. Because ArrayList holds only actual ArrayList. Because, each node in LinkedList holds

Occupation data and its index. data and reference to next and previous elements.

If your application does more retrieval than the If your application does more insertions and

When to Use insertions and deletions, then use ArrayList. deletions than the retrieval, then use LinkedList.

10
CORE JAVA

ArrayList and Vector


1) Synchronization: ArrayList is non-synchronized which means multiple threads can work on ArrayList
at the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be
another thread performing remove operation on ArrayList at the same time in a multithreaded
environment

while Vector is synchronized. This means if one thread is working on Vector, no other thread can get a
hold of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.

2) Resize: Both ArrayList and Vector can grow and shrink dynamically to maintain the optimal use of
storage, however the way they resized is different. ArrayList grow by half of its size when resized while
Vector doubles the size of itself by default when grows.

3) Performance: ArrayList gives better performance as it is non-synchronized. Vector operations gives


poor performance as they are thread-safe, the thread which works on Vector gets a lock on it which
makes other thread wait till the lock is released.

Both are part of java collection framework, but both serve different purpose. Collection is a top-level
interface of java collection framework whereas  Collections is a utility class

Collection is a root level interface of the Java Collection Framework. Most of the classes in Java
Collection Framework inherit from this interface. List, Set and Queue are main sub interfaces of this
interface. JDK doesn’t provide any direct implementations of this interface. But, JDK provides direct
implementations of its sub interfaces. 

ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue are some indirect implementations of


Collection interface. Map interface, which is also a part of java collection framework, doesn’t inherit
from Collection interface. Collection interface is a member of java.util package.

Collections is an utility class in java.util package. It consists of only static methods which are used to
operate on objects of type Collection. For example, it has the method to find the maximum element in a
collection, it has the method to sort the collection, it has the method to search for a particular element
in a collection.

Comparator interface? When to use?


The class whose objects to be sorted do not need to implement this interface. Some third
class can implement this interface to sort. E.g., CountrySortByIdComparator class can
implement Comparator interface to sort collection of country object by id. For example:

Hide   Copy Code

public class CountrySortByIdComparator implements Comparator<Country>{

@Override

11
CORE JAVA

public int compare(Country country1, Country country2) {

return (country1.getCountryId() < country2.getCountryId() ) ? -1:


(country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
}
}

Using Comparator interface, we can write different sorting based on different attributes of


objects to be sorted. You can use anonymous comparator to compare at particular line of
code. For example:

Hide   Copy Code

Country indiaCountry=new Country(1, "India");


Country chinaCountry=new Country(4, "China");
Country nepalCountry=new Country(3, "Nepal");
Country bhutanCountry=new Country(2, "Bhutan");

List<Country> listOfCountries = new ArrayList<Country>();


listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);

//Sort by countryName

Collections.sort(listOfCountries,new Comparator<Country>() {

@Override
public int compare(Country o1, Country o2) {

return o1.getCountryName().compareTo(o2.getCountryName());
}
});

Comparable interface? When to use?

Class whose objects to be sorted must implement this interface. In this, we have to implement
compareTo(Object) method. For example:

public class Country implements Comparable<Country>{


@Override
public int compareTo(Country country) {
return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId
) ? 1:0 ;
}}

12
CORE JAVA

If any class implements comparable interface then collection of that object can be sorted automatically
using Collections.sort() or Arrays.sort(). Object will be sort on the basis
of compareTo method in that class. Objects which implement Comparable in Java can be used as keys
in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other
interface.

Comparator vs Comparable

Parameter Comparable Comparator

Package Java.lang.Comparable Java.util.Comparator 

Sorting logic is in separate class. Hence, we


Sorting logic must be in same class
can write different sorting based on different
Sorting logic whose objects are being sorted. Hence
attributes of objects to be sorted. E.g. Sorting
this is called natural ordering of objects
using id, name etc.

Class whose objects to be sorted do not need


Class whose objects to be sorted must
to implement this interface. Some other class
implement this interface.
can implement this interface. E.g.-
Implementation e.g Country class needs to implement
CountrySortByIdComparator class can
comparable to collection of country
implementComparator interface to sort
object by id
collection of country object by id

int compareTo(Object o1)


This method compares this object int compare(Object o1,Object o2)
with o1 object and returns a integer. Its
value has following meaning This method compares o1 and o2 objects.
Sorting method and returns an integer. Its value has following
1. positive – this object is greater meaning.
than o1 1. positive – o1 is greater than o2
2. zero – this object equals to o1 2. zero – o1 equals to o2
3. negative – this object is less 3. negative – o1 is less than o1 
than o1
Collections.sort(List) Collections.sort(List, Comparator)
Calling method Here objects will be sorted based Here objects will be sorted based on
on CompareTo method Compare method in Comparator

13
CORE JAVA

Copy
Deep copy and Shallow copy
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection
structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all the elements in
the original collection duplicated.

Below is the list of differences between shallow copy and deep copy in java.

Shallow Copy Deep Copy

Cloned Object and original object are not 100% Cloned Object and original object are 100%
disjoint. disjoint.

Any changes made to cloned object will be reflected in Any changes made to cloned object will not be
original object or vice versa. reflected in original object or vice versa.

Default version of clone method creates the shallow To create the deep copy of an object, you must
copy of an object. override clone method.

Shallow copy is preferred if an object has only primitive Deep copy is preferred if an object has
fields. references to other objects as fields.

Shallow copy is fast and less expensive. Deep copy is slow and very expensive.

Implementing Deep Cloning


Deep cloning can be done by two ways:
** All objects implement a clone method
Every object is responsible for cloning itself via its clone() method. So, when the parent is called it makes
calls to all the referenced objects inside the class and calls its clone method.

14
CORE JAVA

public class Person{

String s;
Date d;
...

public Person clone(){


Person p = new Person();
p.s = this.s.clone();
p.d = this.d.clone();
...
return p;
}
}
In your executing code:
ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
clone.add(p.clone());

** Serialization
This is the best way to deep cloning and not to mention best answer in interview of how to implement
deep cloning. There are three steps to do deep cloning using serialization:
- Ensure that all classes in the object are serializable
- Create output stream for writing the new object and input stream for reading the same.
- Pass the object you want to copy to the output stream.
- And finally read the object using the input stream

Your object you wish to deep copy will need to implement serializable. If the class isn't final or can't be
modified, extend the class and implement serializable.

Convert your class to a stream of bytes:


ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
oos.close();
bos.close();
byte[] byteData = bos.toByteArray();

Restore your class from a stream of bytes:

ByteArrayInputStream bais = new ByteArrayInputStream(byteData);


(Object) object = (Object) new ObjectInputStream(bais).readObject();

Implementing Shallow Cloning


To implement shallow cloning, we need to implement cloneable interface and override the clone
method with implementation.

15
CORE JAVA

class Course
{
    String subject1;
 
    String subject2;
 
    String subject3;
 
    public Course(String sub1, String sub2, String sub3)
    {
        this.subject1 = sub1;
 
        this.subject2 = sub2;
 
        this.subject3 = sub3;
    }
}
 
class Student implements Cloneable
{
    int id;
 
    String name;
 
    Course course;
 
    public Student(int id, String name, Course course)
    {
        this.id = id;
 
        this.name = name;
 
        this.course = course;
    }
 
    //Default version of clone() method. It creates shallow copy of an object.
 
    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}
 
public class ShallowCopyInJava
{
    public static void main(String[] args)
    {
        Course science = new Course("Physics", "Chemistry", "Biology");
 
        Student student1 = new Student(111, "John", science);
 
        Student student2 = null;
 
        try
        {
            //Creating a clone of student1 and assigning it to student2
 
            student2 = (Student) student1.clone();
        }
        catch (CloneNotSupportedException e)

16
CORE JAVA

        {
            e.printStackTrace();
        }
 
        //Printing the subject3 of 'student1'
 
        System.out.println(student1.course.subject3);         //Output : Biology
 
        //Changing the subject3 of 'student2'
 
        student2.course.subject3 = "Maths";
 
        //This change will be reflected in original student 'student1'
 
        System.out.println(student1.course.subject3);       //Output : Maths
    }
}

Covariant return type? Example


The covariant return type specifies that the return type may vary in the same direction as the subclass.

Before Java5, it was not possible to override any method by changing the return type. But now, since
Java5, it is possible to override method by changing the return type if subclass overrides any method
whose return type is Non-Primitive but it changes its return type to subclass type

class A{  

A get(){return this;}  

}  

  

class B1 extends A{  

B1 get(){return this;}  

void message(){

System.out.println("welcome to covariant return type");

}  

public static void main(String args[]){  

new B1().get().message();  

}  

Output: welcome to covariant return type

As you can see in the above example, the return type of the get() method of A class is A but the
return type of the get() method of B class is B. Both methods have different return type but it is
method overriding. This is known as covariant return type.

17
CORE JAVA

Data types and their default values?


In java, there are two types of data types

 primitive data types

 non-primitive data types

Data Type Default Value Default size

Boolean False 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

18
CORE JAVA

Long 0L 8 byte

Float 0.0f 4 byte

Double 0.0d 8 byte

Dictionary class
Dictionary is an abstract class that represents a key/value storage repository and operates much like
Map.

Given a key and value, you can store the value in a Dictionary object. Once the value is stored, you can
retrieve it by using its key. Thus, like a map, a dictionary can be thought of as a list of key/value pairs.

Get(key), keys(), elements(key, value), are abstract methods for it.

Enumeration Iterator

Using Enumeration, you can only traverse the collection.

You can’t do any modifications to collection while Using Iterator, you can remove an element of the

traversing it. collection while traversing it.

Enumeration is introduced in JDK 1.0 Iterator is introduced from JDK 1.2

Iterator is used to iterate most of the classes in the

Enumeration is used to traverse the legacy classes collection framework

like Vector, Stack and HashTable. like ArrayList, HashSet, HashMap, LinkedList etc.

Methods: hasMoreElements() and nextElement() Methods: hasNext(), next() and remove()

Enumeration is fail-safe in nature. Iterator is fail-fast in nature.

Enumeration is not safe and secured due to its fail-safe

nature. Iterator  is safer and secured than Enumeration.

19
CORE JAVA

Both java.lang.Error and java.lang.Exception classes are sub classes of java.lang.Throwable class, but


there exist some significant differences between them.  java.lang.Error class represents the errors which
are mainly caused by the environment in which application is running. For example,
OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs when stack
overflows.

Whereas java.lang.Exception class represents the exceptions which are mainly caused by the application


itself. For example, NullPointerException occurs when an application tries to access null object
or ClassCastException occurs when an application tries to cast incompatible class types.

The differences between Error and Exception in Java:

Errors Exceptions

Errors in Java are of type java.lang.Error. Exceptions in Java are of type java.lang.Exception.

Exceptions include both checked as well as unchecked


All errors in java are unchecked type. type.

Checked exceptions are known to compiler whereas


Errors happen at run time. They will not be known unchecked exceptions are not known to compiler
to compiler. because they occur at run time.

You can recover from exceptions by handling them


It is impossible to recover from errors. through try-catch blocks.

Errors are mostly caused by the environment in


which application is running. Exceptions are mainly caused by the application itself.

Examples :
Checked Exceptions : SQLException, IOException
Examples : Unchecked Exceptions :
java.lang.StackOverflowError, ArrayIndexOutOfBoundException, ClassCastException,
java.lang.OutOfMemoryError NullPointerException

Equals method
Why we override equals() method?

Default implementation of equals() class provided by java.lang.Object compares memory location and


only return true if two reference variable are pointing to same memory location i.e. essentially they are
same object.

20
CORE JAVA

Java recommends to override equals and hashCode method if equality is going to be define by logical
way or via some business logic: example: many classes in Java standard library does override it e.g.
String overrides equals, whose implementation of equals() method return true if content of two String
objects are exactly same

public class Employee {

...

public boolean equals(Object o){

if(o == null) return false;

if(!(o instanceof) Employee) return false;

Employee other = (Employee) o;

if(this.employeeId != other.employeeId) return false;

if(! this.firstName.equals(other.firstName)) return false;

if(! this.lastName.equals(other.lastName)) return false;

return true;

Equals Method and


You can check the equality of objects in two ways. One is based on their location in the memory and
second one is based on their contents (i.e state of the objects). Both equals() method and “==” operator
are used to check the equality of two objects in the memory.  “==” operator compares the objects based
on their location in the memory. The default version of  equals() method also does the same thing as
“==” operator. But, equals() method is meant to be used for comparison of two objects based on their
contents. 

“==” operator is a binary operator in java which compares the two objects based on their location in the
memory.

equals() method is a public member of java.lang.Object class. As all classes in java extend Object class by
default, this method is available in all classes you create in java. The default version of equals() method
does the same thing as “==” operator i.e comparing the two objects based on their location in the
memory.

21
CORE JAVA

Exception
An exception is an abnormal condition that arises in a code sequence at run time.

Checked Exceptions

Checked exceptions are known to compiler i.e they are the exceptions that are checked at compile time.
Checked exceptions are also called compile time exceptions, because they can be known during compile
time.

In Java, both ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found


at run time. But, they occur at different scenarios. ClassNotFoundException is an exception which occurs
when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes
are not found in the classpath. On the other hand, NoClassDefFoundError is an error which occurs when a
particular class is present at compile time but it was missing at run time.

How JAVA exception handlings work?


Basically, there are four important keywords which form the main pillars of exception handling: try,
catch, throw and finally. Code which you want to monitor for exception is contained in the try block. If
any exception occurs in the try block its sent to the catch block which can handle this error in a more
rational manner. To throw an exception manually you need to call use the throw keyword. If you want
to put any clean up code use the finally block. The finally block is executed irrespective if there is an
error or not.

java.lang.Throwable

java.lang.Throwable is the super class of all errors and exceptions in java. Throwable class extends
java.lang.Object class. The only argument of catch block must be its type or it’s sub class type.

It has two sub classes.

1)java.lang.Error: java.lang.Error is the super class for all types of errors in java.

2)java.lang.Exception: java.lang.Exception is the super class for all types of Exceptions in java.

OutOfMemoryError in Java
1) Java.lang.OutOfMemoryError: Java heap space

- out of memory in heap

- create an object and there is not enough space in heap to allocate that object

22
CORE JAVA

Default 512MB

2) Java.lang.OutOfMemoryError: PermGen space

- is memory leak through Classloaders and it’s very often surfaced in WebServer and application
server like tomcat, webshere, glassfish or WebLogic

Since in most of J_V_M default size of Perm Space is around "64MB"

specify size of permanent generation using J_V_M options "-XX:PermSize" and "-XX:MaxPermSize"

--> while undeploying if container somehow keeps reference of any class loaded by application class
loader than that class and all other related class will not be garbage collected and can quickly fill the
PermGen space if you deploy and undeploy your application many times.

--> tomcat > 6.0 onward tomcat provides memory leak detection feature which can detect many
common memory leaks on web-app perspective e.g ThreadLocal memory leaks, _JDBC driver registration,
RMI targes, LogFactory and Thread spawned by web-apps.

throw is a keyword in java which is used to throw an exception manually. Using throw keyword, you can
throw an exception from any method or block. But, that exception must be of type java.lang.Throwable class
or it’s sub classes.

throws is also a keyword in java which is used in the method signature to indicate that this method may
throw mentioned exceptions. The caller to such methods must handle the mentioned exceptions either using
try-catch blocks or using throws keyword. 

Throwable is a super class for all types of errors and exceptions in java. This class is a member
of java.lang package. Only instances of this class or it’s sub classes are thrown by the java virtual machine or
by the throw statement. The only argument of catch block must be of this type or it’s sub classes. If you want
to create your own customized exceptions, then your class must extend this class.

Unchecked Exceptions

Unchecked exceptions are not known to compiler.  They are the exceptions that are not checked at compile
time, because they occur only at run time. That’s why these exceptions are also called run time exceptions.

Below are uncheckedExceptions:

Error and its subclasses

RuntimeException and its subclasses

23
CORE JAVA

Externalizable interface
What's the use of Externalizable interface?
When performance becomes an important criteria, then you can serialize using the
java.io.Externalizable interface instead of the Serializable interface. Externalizable requires that you
write the details of reading and writing the object's state to the byte stream. The ObjectOutputStream

24
CORE JAVA

class no longer simplifies this process. You must use the methods readExternal and writeExternal
method to write the object in to stream and read from stream.

Fail Fast vs Fail Safe Iterators


Fail-Fast Iterators Fail-Safe Iterators

Fail-Fast iterators doesn’t allow modifications of a Fail-Safe iterators allow modifications of a collection

collection while iterating over it. while iterating over it.

These iterators throw

ConcurrentModificationException if a collection is These iterators don’t throw any exceptions if a

modified while iterating over it. collection is modified while iterating over it.

They use original collection to traverse over the They use copy of the original collection to traverse

elements of the collection. over the elements of the collection.

These iterators require extra memory to clone the

These iterators don’t require extra memory. collection.

Ex: Iterators returned by ArrayList, Vector, HashMap. Ex: Iterator returned by ConcurrentHashMap.

File name - Is Empty .java a valid source file name?


Yes. We can create empty .java source file name and its valid source file and will be converted *.class
file.

Final keyword
Final Variable
If you make any variable as final, you cannot change the value of final variable (It will be constant).

Final Method
If you make any method as final, you cannot override it.

Final Class

25
CORE JAVA

If you make any class as final, you cannot extend it.

Blank or uninitialized final variable


A final variable that is not initialized at the time of declaration is known as blank final variable. It can be
initialized only in constructor.

Static Blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.

class A{  

static final int data;//static blank final variable  

   static{ data=50;}  

   public static void main(String args[]){  

     System.out.println(A.data);  

  }  

Final, finally and finalize keywords


final
final is a keyword. The variable declared as final should be initialized only once and cannot be changed.
Java classes declared as final cannot be extended. Methods declared as final cannot be overridden. 

finally
finally is a block. The finally block always executes when the try block exits. This ensures that the finally
block is executed even if an unexpected exception occurs. But finally is useful for more than just
exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a
return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when
no exceptions are anticipated. 

finalize
finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method.
You can write system resources release code in finalize() method before getting garbage collected.

26
CORE JAVA

For loops
The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state
incrementing/decrementing counter (There are exceptions, but this is the classic)

For that,
for (int i=0;i<myString.length;i++) {
System.out.println(myString[i]);
}

For Java 5 an alternative was proposed. Anything that implements iterable can be supported. This is
particularly nice in Collections. For example you can iterate the list like this
List<String> list = ....load up with stuff

for (String string : list) {


System.out.println(string);
}

For Java 5 an alternative was proposed. Anything that implements iterable can be supported. This is
particularly nice in Collections. For example, you can iterate the list like this
List<String> list = ....load up with stuff

for (String string : list) {


System.out.println(string);
}

Garbage collection
What is garbage collection? Can we enforce garbage collection to perform?
"Garbage collection is a feature of JAVA that is called automatic memory management as JVM
automatically removes the unused variables/objects (value is null) from the memory.

GC cannot be forced to perform."

Generic
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.

Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the
java programmer to store specific type of objects.

Generics also provide compile-time type safety that allows programmers to catch invalid types at
compile time.

27
CORE JAVA

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 collection
Advantage of generic collection?

After Generics, we don't need to typecast the object.

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety: We can hold only a single type of objects in generics. It doesn’t allow to store other
objects.

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.


List list = new ArrayList();  
list.add("hello");  
String s = (String) list.get(0);//typecasting  

After Generics, we don't need to typecast the object.


List<String> list = new ArrayList<String>();  
list.add("hello");  
String s = list.get(0);  

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.
List<String> list = new ArrayList<String>();  
list.add("hello");  
list.add(32);//Compile Time Error  

Generic Type Parameters


The type parameters naming conventions are important to learn generics thoroughly. The commonly
type parameters are as follows:

T - Type

E - Element

K - Key

N - Number

28
CORE JAVA

V - Value

hashCode() method?
The hashCode() method of objects is used when you insert them into
a HashTable, HashMap or HashSet. When inserting an object into a hastable you use a key. The
hash code of this key is calculated, and used to determine where to store the object internally

public int hashCode(){

return (int) employeeId *

firstName.hashCode() *

lastName.hashCode();

Hash collision in Hashtable and how it is handled?


When we try to restrict the hashing function’s output within the allocated address spectrue limit, there
is a possibility of a collision. For two different keys k1 and k2, if we have h(k1) = h(k2), then this is called
collision in hashtable. What does this mean, our hashing function directs us store two different values
(keys are also different) in the same location.

When we have a collision, there are multiple methodologies available to resolve it. To name a few
hashtable collision resolution technique, ‘separate chaining’ and ‘open addressing’.

Java uses separate chaining for collision resolution. Recall a point that Hashtable stores elements in
buckets. In separate chaining, every bucket will store a reference to a linked list. Now assume that you
have stored an element in bucket 1. That means, in bucket 1 you will have a reference to a linked list
and in that linked list you will have two cells. In those two cells you will have key and its corresponding
value.

29
CORE JAVA

Why do you want to store the key? Because when there is a collision i.e., when two keys results in same
hashcode and directs to the same bucket (assume bucket 1) you want to store the second element also
in the same bucket. You add this second element to the already created linked list as the adjacent
element.

Now when you retrieve a value it will compute the hash code and direct you to a bucket which has two
elements. You scan those two elements alone sequentially and compare the keys using their equals()
method. When the key matches, you get the respective value. Hope you have got the reason behind the
condition that your object must have hashCode() and equals() method.

HashMap vs HashTable
DIFFERENCES:

HashMap HashTable

HashMap is not synchronized and therefore it is not HashTable is internally synchronized and therefore it is

thread safe. thread safe.

HashMap allows maximum one null key and any number

of null values. HashTable doesn’t allow null keys and null values.

Enumeration returned by the HashTable are fail-safe in

Iterators returned by the HashMap are fail-fast in nature. nature.

HashMap extends AbstractMap class. HashTable extends Dictionary class.

HashTable returns both Iterator as well as Enumeration

HashMap returns only iterators to traverse. for traversal.

HashMap is fast. HashTable is slow.

HashMap is not a legacy class.v HashTable is a legacy class.

HashMap is preferred in single threaded applications. If Although HashTable is there to use in multi-threaded

you want to use HashMap in multi-threaded application, applications, nowadays it is not at all preferred. Because,

30
CORE JAVA

wrap it using Collections.synchronizedMap() method. ConcurrentHashMap is better option than HashTable.

31
CORE JAVA

SIMILARITIES BETWEEN HASHMAP AND HASHTABLE

1) Both store the data in the form of key-value pairs.

2) Both use Hashing technique to store the key-value pairs.

3) Both implement Map interface.

4) Both doesn’t maintain any order for elements.

5) Both give constant time performance for insertion and retrieval operations.

HashMap vs HashSet
HashSet HashMap

HashSet implements Set interface. HashMap implements Map interface.

HashSet stores the data as objects. HashMap stores the data as key-value pairs.

HashSet internally uses HashMap. HashMap internally uses an array of Entry<K, V> objects.

HashMap doesn’t allow duplicate keys, but allows duplicate

HashSet doesn’t allow duplicate elements. values.

HashSet allows only one null element. HashMap allows one null key and multiple null values.

Insertion operation requires only one object. Insertion operation requires two objects, key and value.

HashSet is slightly slower than HashMap. HashMap is slightly faster than HashSet.

32
CORE JAVA

HashMap vs TreeMap

HashMap TreeMap

Ordering No Yes

Implementation Hashing Red-Black Tree

Null Keys and Null values One null key, any null values Not permit null key, but any null values

Performance O(1) log(n)

Speed Fast Slow in comparison

HashSet
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash
table for storage. Hash table stores information by using a mechanism called hashing. Information of the
key is used to determine a unique value termed hashcode. This hash code is then used as an index for
data associated with the key is stored. This happens automatically and you will never need to know the
hash code value. Also, your code can't directly index the hash table.

The biggest advantage of hashing is that execution time of add( ), contains( ), remove( ), and size( ) to
remain same even when the collection are large in size. Hash set does not guarantee sorting.

HashSet vs TreeSet

1. Ordering: HashSet stores the object in random order. There is no guarantee that the element
we inserted first in the HashSet will be printed first in the output. For example   

import java.util.HashSet;

public class HashSetExample {

public static void main(String[] args) {

HashSet<String> obj1= new HashSet<String>();

obj1.add("Alive");

obj1.add("is");

obj1.add("Awesome");

33
CORE JAVA

System.out.println(obj1);

OUTPUT : [is, Awesome, Alive]

Elements are sorted according to the natural ordering of its elements in TreeSet. If the objects cannot 
be sorted in natural order than use  of TreeSet object .

import java.util.TreeSet;

public class TreeSetExample {

public static void main(String[] args) {

TreeSet<String> obj1= new TreeSet<String>();

obj1.add("Alive");

obj1.add("is");

obj1.add("Awesome");

System.out.println(obj1);

 OUTPUT: [Alive, Awesome, is]

2. Null value:   HashSet can store null object while TreeSet does not allow null object. If one try to store
null object in TreeSet object, it will throw NullPointerException.

3. Performance: HashSet take constant time performance for the basic operations like add, remove
contains and size. While TreeSet guarantees log(n) time cost for the basic operations (add, remove,
contains).

4. Speed: HashSet is much faster than TreeSet, as performance time of HashSet is constant against the
log time of TreeSet for most operations (add, remove, contains and size). Iteration performance of
HashSet mainly depends on the load factor and initial capacity parameters. 

5. Internal implementation :  HashSet are internally backed by Hashmap. While TreeSet is backed by
a Navigable TreeMap. 

6. Functionality: TreeSet is rich in functionality as compare to HashSet. Functions like pollFirst(),


pollLast(), first(), last(), ceiling(), lower() etc. makes TreeSet easier to use than HashSet. 

7. Comparision: HashSet uses equals() method for comparison in java while TreeSet uses compareTo()
method for maintaining ordering .

34
CORE JAVA

Iterator
What is Iterator?

The Iterator interface is used to step through the elements of a Collection.

How to use it?

To use an iterator to traverse through the contents of a collection, follow these steps:
• Obtain an iterator to the start of the collection by calling the collection's iterator() method.
• Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
• Within the loop, obtain each element by calling next().

When you use For loop, when you use Iterator?

Iterator have remove() method to remove element from the collection whereas For loop only support to
iterate the collection.

Iterator and ListIterator


Iterator and ListIterator are two interfaces in Java collection framework which are used to traverse the
collections. Although ListIterator extends Iterator, there are some differences in the way they traverse the
collections.

1) Using Iterator, you can traverse List, Set and Queue type of objects. But using ListIterator, you can
traverse only List objects. In Set and Queue types, there is no method to get the ListIterator object. But, In
List types, there is a method called listIterator() which returns ListIterator object.

2) Using Iterator, we can traverse the elements only in forward direction. But, using ListIterator you can
traverse the elements in both the directions – forward and backward. ListIterator has those methods to
support the traversing of elements in both directions.

3) Using ListIterator, you can obtain index of next and previous elements. But, it is not possible with Iterator
interface.

4) Using ListIterator, you can perform modifications (insert, replace, remove) on the list. But, using Iterator
you can only remove the elements from the collection.

5) Using ListIterator, you can iterate a list from the specified index. It is not possible with Iterator.

Iterator and Enumeration


You can get remove() from Iterator to remove an element, while Enumeration does not have remove()
method. Using Enumeration you can only traverse and fetch the objects, whereas using Iterator we can
also add and remove the objects

35
CORE JAVA

IntegerCache Class
IntegerCache is the private static inner class of java.lang.Integer class. This is the class which handles the
caching of all frequently requested values.
In IntegerCache, you can notice that low is always set to -128. high gets the value from the property set in
sun.misc.VM class (VM argument -XX:AutoBoxCacheMax=size). That means you can change the upper limit of
the range. If it is not set it gets the default value 127.

J2EE and JEE are same?


yes, J2EE refers to the first version of Java Enterprise Edition. j2ee is the old naming of the java enterprise
edition, in the early history java was called simply java afterward sun created a new version of java called java
2 subsequent updates followed the theme OJ java 2 1.3 java 2 1.4 java 2 1.5 
sun realized that this naming is making confusion to people so it dropped the 2 so j2ee became jee :) 

J2SE and J2EE Differences


J2SE is a collection of basic Java classes and APIs. It focuses on new specifications and APIs including XML,
Web Services, JDBC version 4.0, programming based on Annotations, API’s for Java compiler and Application
client GUI. This was on top of already existing features like Annotations, Generics and Autoboxing.

J2EE provides a server programming platform in Java. It includes JDBC (Java Database Connectivity), RMI
(Remote Method Invocation), JMS (Java Message Service), web services and XML are some of the
specifications offered by Java EE. Furthermore, specifications unique to Java EE such as Enterprise JavaBeans
(EJB), Connecters, Servlets, portlets, Java Server Pages (JSP) are also offered.

jar vs war vs ear

JAR:
EJB modules which contains enterprise java beans class files and EJB deployment descriptor are packed as
JAR files with .jar extension

WAR:
Web modules which contains Servlet class files, JSP FIles, supporting files, GIF and HTML files are packaged as
JAR file with .war (web archive) extension

EAR:
All above files (.jar and .war) are packaged as JAR file with .ear (enterprise archive) extension and deployed
into Application Server.

Java 8 Features
1. forEach() method in Iterable interface
2. default and static methods in Interfaces
3. Functional Interfaces and Lambda Expressions
4. s

36
CORE JAVA

5. Java Time API


6. Collection API improvements
7. Concurrency API improvements
8. Java IO improvements
9. Miscellaneous Core API improvements

1. forEach() method in Iterable interface


Whenever we need to traverse through a Collection, we need to create an Iterator whose whole purpose is
to iterate over and then we have business logic in a loop for each of the elements in the Collection. We
might get ConcurrentModificationException if iterator is not used properly.

Java 8 has introduced forEach method in java.lang.Iterable interface so that while writing code we focus on
business logic only. forEach method takes java.util.function.Consumer object as argument, so it helps in
having our business logic at a separate location that we can reuse.

//traversing using Iterator

Iterator<Integer> it = myList.iterator();

while(it.hasNext()){

Integer i = it.next();

System.out.println("Iterator Value::"+i);

//traversing through forEach method of Iterable with anonymous class

myList.forEach(new Consumer<Integer>() {

public void accept(Integer t) {

System.out.println("forEach anonymous class Value::"+t);

});

2. default and static methods in Interfaces


From Java 8, interfaces are enhanced to have method with implementation. We can use default and static
keyword to create interfaces with method implementation.

We know that Java doesn’t provide multiple inheritance in Classes because it leads to Diamond Problem. So
how it will be handled with interfaces now, since interfaces are now similar to abstract classes. The solution

37
CORE JAVA

is that compiler will throw exception in this scenario and we will have to provide implementation logic in the
class implementing the interfaces.

3. Functional Interfaces and Lambda Expressions


@FunctionalInterface annotation. Functional interfaces are new concept introduced in Java 8. An interface
with exactly one abstract method becomes Functional Interface. We don’t need to use @FunctionalInterface
annotation to mark an interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid
accidental addition of abstract methods in the functional interfaces. You can think of it like @Override
annotation and it’s best practice to use it. java.lang.Runnable with single abstract method run() is a great
example of functional interface.

One of the major benefits of functional interface is the possibility to use lambda expressions to instantiate
them. We can instantiate an interface with anonymous class but the code looks bulky

Runnable r = new Runnable(){

@Override

public void run() {

System.out.println("My Runnable");

}};

//use lamda

Runnable r1 = () -> {

System.out.println("My Runnable");

};

//single statement  we don’t need curly braces

Interface1 i1 = (s) -> System.out.println(s);

i1.method1("abc");

4. Java Stream API for Bulk Data Operations on Collections


A new java.util.stream has been added in Java 8 to perform filter/map/reduce like operations with the
collection. Stream API will allow sequential as well as parallel execution.

Collection interface has been extended with stream() and parallelStream() default methods to get the Stream
for sequential and parallel execution.

38
CORE JAVA

Notice that parallel processing values are not in order, so parallel processing will be very helpful while
working with huge collections.

List<Integer> myList = new ArrayList<>();

for(int i=0; i<100; i++) myList.add(i);

//sequential stream

Stream<Integer> sequentialStream = myList.stream();

//parallel stream

Stream<Integer> parallelStream = myList.parallelStream();

//using lambda with Stream API, filter example

Stream<Integer> highNums = parallelStream.filter(p -> p > 90);

//using lambda in forEach

highNums.forEach(p -> System.out.println("High Nums parallel="+p));

Stream<Integer> highNumsSeq = sequentialStream.filter(p -> p > 90);

highNumsSeq.forEach(p -> System.out.println("High Nums sequential="+p));

5. Java Time API


One of the nice addition in Java 8 is the java.time package that will streamline the process of working with
time in java.

Just by looking at Java Time API packages, I can sense that it will be very easy to use. It has some sub-
packages java.time.format that provides classes to print and parse dates and times and java.time.zone
provides support for time-zones and their rules.

The new Time API prefers enums over integer constants for months and days of the week. One of the useful
class is DateTimeFormatter for converting datetime objects to strings.

6. Collection API improvements


Some new methods added in Collection API are:

forEach()

Iterator default method forEachRemaining(Consumer action) to perform the given action for each remaining
element until all elements have been processed or the action throws an exception.

39
CORE JAVA

Collection default method removeIf(Predicate filter) to remove all of the elements of this collection that
satisfy the given predicate.

Collection spliterator() method returning Spliterator instance that can be used to traverse elements
sequentially or parallel.

Map replaceAll(), compute(), merge() methods.

Performance Improvement for HashMap class with Key Collisions

7. Concurrency API improvements


Some important concurrent API enhancements are:

ConcurrentHashMap compute(), forEach(), forEachEntry(), forEachKey(), forEachValue(), merge(), reduce()


and search() methods.

CompletableFuture that may be explicitly completed (setting its value and status).

Executors newWorkStealingPool() method to create a work-stealing thread pool using all available
processors as its target parallelism level.

8. Java IO improvements
Files.list(Path dir) that returns a lazily populated Stream, the elements of which are the entries in the
directory.

Files.lines(Path path) that reads all lines from a file as a Stream.

Files.find() that returns a Stream that is lazily populated with Path by searching for files in a file tree rooted at
a given starting file.

BufferedReader.lines() that return a Stream, the elements of which are lines read from this BufferedReader.

9. Miscellaneous Core API improvements


Some misc API improvements that might come handy are:

ThreadLocal static method withInitial(Supplier supplier) to create instance easily.

Comparator interface has been extended with a lot of default and static methods for natural ordering,
reverse order etc.

min(), max() and sum() methods in Integer, Long and Double wrapper classes.

logicalAnd(), logicalOr() and logicalXor() methods in Boolean class.

ZipFile.stream() method to get an ordered Stream over the ZIP file entries. Entries appear in the Stream in
the order they appear in the central directory of the ZIP file.

Several utility methods in Math class.

40
CORE JAVA

jjs command is added to invoke Nashorn Engine.

jdeps command is added to analyze class files

JDBC-ODBC Bridge has been removed.

PermGen memory space has been removed

java vs javaw vs javaws


java.exe is a Win32 console application. This is provided as a helper so that, instead of using jvm.dll we can
execute java classes

javaw.exe is very similar to java.exe. It can be considered as a parallel twin. It is a Win32 GUI application. This
is provided as a helper so that application launches its own GUI window and will not launch a console.

javaws.exe is used to launch a java application that is distributed through web. 

JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.

41
CORE JAVA

JRE
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It is the
implementation of JVM. It physically exists. It contains set of libraries + other files that JVM uses at runtime.

Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.

The JVM performs following main tasks:

 Loads code

 Verifies code

 Executes code

 Provides runtime environment

42
CORE JAVA

LinkedList

It provides link-list data structure.

We can add elements to the beginning or the end of the list using the below code snippet:
void addFirst(Object objlst)
void addLast(Object objlst)

objlst is the element added to the list.

In order to get the first and the last element of the linked list we can use the getFirst() and getLast()
methods respectively.

In order to delete the first and the last element of the list we can use the removeFirst() and
removeLast() methods, respectively.

List and Set


List, Set and Map are interfaces in Java and there are many concrete implementation of them are
available in Collection API. ArrayList and LinkedList are two most popular used List implementation while
LinkedHashSet, TreeSet and HashSet are frequently used Set implementation

List (Interface)

 List is an ordered collection which allows duplicate elements

 We can iterate the values by calling iterator() method

List li = new ArrayList();


Iterator iter = li.iterator();

Set (Interface)

 Set is an un-ordered collection which doesn’t allows duplicate (no-duplicate) elements

 We can iterate the values by calling iterator() method

Set s = new HashSet();


Iterator iter = s.iterator();

How to check duplicated elements in the Set?

To check duplicated elements in the Set, you have to override the equals() and hashcode() method.

43
CORE JAVA

Literals?
Literals in Java are a sequence of characters (digits, letters, and other characters) that
represent constant values to be stored in variables. 

Integer literals

Floating literals

Character literals

String literals

Boolean literals

examples:

char a = '\u0001';

String a = "\u0001";

byte a = 68;
char a = 'A' etc

Main method
Change the name of main method? if yes explain how? if no then  why?
I think we cannot change the name of main method

Execute a program without main() method?

Ans) Yes, one of the way is static block but in previous version of JDK NOT in JDK 1.7 and Java 8

class A3{  

static{  

   System.out.println("static block is invoked");  

   System.exit(0);  

   }  

final: declare main method as final?


Yes, main can be declared as final. Final means the method or variable cannot be modified in sub-class It
does not have any impact on main because Static function is not a part of object instance.

44
CORE JAVA

Overload main() method?


Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:

class Overloading1{  

   public static void main(int a){  

   System.out.println(a);  

   }  

    

   public static void main(String args[]){  

   System.out.println("main() method invoked");  

   main(10);  

   }  

private: declare main method private?


Yes, we can declare main method as private. It compiles without any errors, but in runtime, it says main
method is not public. - See more at: http://www.java2novice.com/java_interview_questions/private-
main-method/#sthash.IfdxhSBS.dpuf

public: why main method is public?


 says nothing about the type of the class which contains the main method. However, main
method must be public. (See section 12.1 from the specification.)

Java specifies several access modifiers e.g. private, protected and public. Any method or variable which
is declared public in Java can be accessible from outside of that class. Since the main method is public in

Java, JVM can easily access and execute it.

Static: Why main method is static?

Because object is not required to call static method if it were non-static method, jvm create object first
then call main() method that will lead the problem of extra memory allocation.

1. Since the main method is static Java virtual Machine can call it without creating any instance of a class
which contains the main method.

2. Since C and C++ also have similar main method which serves as entry point for program execution,
following that convention will only help Java.

45
CORE JAVA

3. If main method were not declared static than JVM has to create instance of main Class and since
constructor can be overloaded and can have arguments there would not be any certain and consistent
way for JVM to find main method in Java.

4. Anything which is declared in class in Java comes under reference type and requires object to be
created before using them but static method and static data are loaded into separate memory inside
JVM called context which is created when a class is loaded. If main method is static than it will be loaded
in JVM context and are available to execution.

Read more: http://javarevisited.blogspot.com/2011/12/main-public-static-java-void-method-


why.html#ixzz4Z0cp51IT

strictfp: declare main method as strictfp?


can we change the order of public static void main to static public void main?

can  we  change the name of argument passed in main method?

how many  ways do we  have to declare the argument in main method?

public static synchronized strictfp void main(String args) will it  work  ?

System.out.printIn("subash"); What is System? what is out and its type? what is println  ?

synchronized: declare main method as synchronized?


A Java synchronized block marks a method or a block of code as synchronized. Java synchronized blocks
can be used to avoid . since main method is static we can use synchronized for main method.

Marker interface..? When to use?


In earlier versions of Java, Marker Interfaces were the only way to declare metadata about a class. For
example, the Serializable Marker Interface lets the author of a class say that their class will behave correctly
when serialized and deserialized.

In modern Java, marker interfaces have no place. They can be completely replaced by Annotations.

Java Marker Interface Examples

 java.lang.Cloneable

 java.io.Serializable

 java.util.EventListener

46
CORE JAVA

Memory
Stack and Heap Memory
Stack memory stores primitive types and the addresses of objects. The object values are stored in heap
memory. An object reference on the stack is only an address that refers to the place in heap memory where
that object is kept.

Stack vs Heap?

1) The main difference between heap and stack is that stack memory is used to store local variables and
function call while heap memory is used to store objects in Java. No matter, where the object is created in
code e.g. as a member variable, local variable or class variable, they are always created inside heap space in
Java.

2) Each Thread in Java has their own stack which can be specified using -Xss JVM parameter, similarly, you
can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of the
heap and -Xmx is a maximum size of java heap. to learn more about JVM options see my post 10 JVM option
Java programmer should know.

3) If there is no memory left in the stack for storing function call or local variable, JVM will throw
java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw
java.lang.OutOfMemoryError: Java Heap Space.

4) If you are using Recursion, on which method calls itself, You can quickly fill up stack memory. Another
difference between stack and heap is that size of stack memory is a lot lesser than the size of heap memory
in Java.

5) Variables stored in stacks are only visible to the owner Thread while objects created in the heap are
visible to all thread. In other words, stack memory is kind of private memory of Java Threads while heap
memory is shared among all threads.

Modifier
Access Modifiers Non-Access Modifiers
private static
final
default or No Modifier
abstract
protected synchronized
transient
public volatile
strictfp

Access Modifiers

47
CORE JAVA

As already said, access modifiers are used to control the visibility of a class or a method or a variable or a
constructor. There are 4 different access modifiers are available in java. They are – private, default (or no
access modifier), public and protected.

Same Class Same Package Subclass Other packages


Access Modifiers
public Y Y Y Y
protected Y Y Y N
no access modifier Y Y N N
private Y N N N

private : private members of a class, whether it is a field or a method or a constructor, can not be accessed
outside the class in which they are defined. private members are also not inherited to sub class.

default : default members or members with no access modifier are visible within the package. And they are
inherited to only sub classes which reside in the same package. That means they are not inherited and visible
outside the package.

public : public members are visible everywhere and they are inherited to any sub class.

protected : protected members have half the characteristics of public members and half the characteristics
of default members. i. e protected members are visible within package like default members and they can be
inherited to any sub class just like public members.

Non-Access Modifiers

Java provides some other modifiers to provide the functionalities other than the visibility. These modifiers
are called Non-Access Modifiers. There are many non-access modifiers available in java. Each modifier have
their own functionality. Some of the most used non-access modifiers are listed below.
abstract 

This modifier can be used either with a class or with a method. You cannot apply this modifier to variable and
constructor. A method which is declared as abstract must be modified in the sub class. You can’t instantiate
a class which is declared as abstract. See  post for more info on abstraction in java.
final 

This modifier is used to restrict the further modification of a variable or a method or a class. The value of a
variable which is declared as final can’t be modified once it gets a value. A final method can not be

48
CORE JAVA

overridden in the sub class and you cannot create a sub class to a final class. See post for more info on final
keyword in java.
static

The members which are declared as static are common to all instances of a class. Static members are class
level members which are stored in the class memory. Click  for more info on static members.
strictfp 

This modifier is used for floating-point calculations. This keyword ensures that you will get same floating
point presentation on every platform. This modifier makes floating point variable more consistent across
multiple platforms.
synchronized

This modifier is used to control the access of a particular method or a block by multiple threads. Only one
thread can enter into a method or a block which is declared as synchronized. Click  for more info on
synchronization in java.
transient 

This modifier is used in serialization process. A variable which is declared as transient will not be serialized
during object serialization.
volatile 

Volatile modifier is used in multi threaded programming. If you declare a field as volatile it will be signal to
the threads that it’s value must be read from the main memory rather then their own stack. Because volatile
field is common to all threads and it will be updated frequently by multiple threads.

MultiMap
A multimap is like a Map but it can map each key to multiple values.
The Java Collections Framework doesn't include an interface for multimaps,
but there's Guava framework that provide MultiMap interface like:
Multimap<String, String> myMultimap = ArrayListMultimap.create();

// Adding some key/value


myMultimap.put("Fruits", "Bannana");
myMultimap.put("Fruits", "Apple");
myMultimap.put("Fruits", "Pear");
myMultimap.put("Vegetables", "Carrot");

49
CORE JAVA

Method Overloading Method Overriding

When a class has more than one method with When a super class method is modified

same name but with different arguments, then in the sub class, then we call this as

Definition we call it as method overloading. method overriding.

Overloaded methods must have different Overridden methods must have same

method signatures.  That means they should method signature. I.e. you must not

differ at least in any one of these three things – change the method name, types of

Number of arguments, Types of arguments and arguments, number of arguments and

order of arguments. But, they must have same order of arguments while overriding a

Method Signature name. super class method.

The return type of the overridden

method must be compatible with that of

super class method. That means if super

class method has primitive type as its

return type, then it must be overridden

with same return type. If super class

method has derived type as its return

Overloaded methods can have same or different type then it must be overridden with

Return Types return types. same type or its sub class type.

While overriding a super class method

Visibility(private, either you can keep the same visibility or

public, protected Overloaded methods can have same visibility or you can increase the visibility. But you

and default) different visibility. can’t reduce it.

Static Context Overloaded methods can be static or not static. It You can’t override a static method.

50
CORE JAVA

does not affect the method overloading.

Binding between method call and method Binding between method call and

definition happens at compile time (Static method definition happens at run time

Binding Binding). (Dynamic Binding).

Polymorphism It shows static polymorphism. It shows dynamic polymorphism.

Private methods Private methods can be overloaded. Private methods can’t be overridden.

Final Methods Final methods can be overloaded. Final methods can’t be overridden.

For method overriding, two classes are

For method overloading, only one class is required – super class and sub class.

required. I.e. Method overloading happens That means method overriding happens

Class Requirement within a class. between two classes.

Pass by Value and Pass by reference?


Does JAVA support both of them?

"** In Pass by Value the function or subroutine receives a copy of variable. The function or the method
cannot change variable values.

** In pass By ref the function or subroutine receives a pointer of the variable. And any changes to
variable value are also visible outside the function or subroutine.

JAVA is strictly Pass by Value. So if it’s either primitive data type or an object JAVA always passes by
value”. Even when we have changed the object reference it still reflects the old object value. In short
object references are passed by value. So in JAVA everything is “Pass By Value”.

Pool
How many pools are there in Java?

- Thread pool
- String pool
- Object pool
- Connection pool

51
CORE JAVA

Properties file
Advantage: Java Properties files are amazing resources to add information in Java. Generally, these files
are used to store static information in key and value pair. Things that you do not want to hard code in
your Java code goes into properties files.

There are two ways of loading properties files in Java.


1. Using ClassLoader.getResourceAsStream()
2. Using Class.getResourceAsStream()

For full detail: see below:

Reflection – Access Private Fields and Methods


Accessing Private Fields

To access a private field you will need to call the Class.getDeclaredField(String


name) or Class.getDeclaredFields() method. The
methods Class.getField(String name) and Class.getFields()methods only
return public fields, so they won't work. Here is a simple example of a class with a
private field, and below that the code to access that field via Java Reflection:

public class PrivateObject {

private String privateString = null;

public PrivateObject(String privateString) {


this.privateString = privateString;
}
}
PrivateObject privateObject = new PrivateObject("The Private Value");

Field privateStringField = PrivateObject.class.


getDeclaredField("privateString");

privateStringField.setAccessible(true);

String fieldValue = (String) privateStringField.get(privateObject);


System.out.println("fieldValue = " + fieldValue);

This code example will print out the text "fieldValue = The Private Value", which is the value of the
private field privateString of the PrivateObject instance created at the beginning of the code
sample.

Notice the use of the


method PrivateObject.class.getDeclaredField("privateString"). It is this method call
that returns the private field. This method only returns fields declared in that particular class, not fields
declared in any superclasses.

52
CORE JAVA

Notice the line in bold too. By calling  Field.setAcessible(true) you turn off the access checks
for this particular Field instance, for reflection only. Now you can access it even if it is private,
protected or package scope, even if the caller is not part of those scopes. You still can't access the field
using normal code. The compiler won't allow it.

Accessing Private Methods

To access a private method you will need to call the  Class.getDeclaredMethod(String name,
Class[] parameterTypes) or Class.getDeclaredMethods() method. The
methods Class.getMethod(String name, Class[]
parameterTypes) and Class.getMethods() methods only return public methods, so they won't
work. Here is a simple example of a class with a private method, and below that the code to access that
method via Java Reflection:

public class PrivateObject {

private String privateString = null;

public PrivateObject(String privateString) {


this.privateString = privateString;
}

private String getPrivateString(){


return this.privateString;
}
}
PrivateObject privateObject = new PrivateObject("The Private Value");

Method privateStringMethod = PrivateObject.class.


getDeclaredMethod("getPrivateString", null);

privateStringMethod.setAccessible(true);

String returnValue = (String)


privateStringMethod.invoke(privateObject, null);

System.out.println("returnValue = " + returnValue);

This code example will print out the text "returnValue = The Private Value", which is the value returned
by the method getPrivateString() when invoked on the PrivateObject instance created at
the beginning of the code sample.

Notice the use of the


method PrivateObject.class.getDeclaredMethod("privateString"). It is this method
call that returns the private method. This method only returns methods declared in that particular class,
not methods declared in any superclasses.

Notice the line in bold too. By calling  Method.setAcessible(true) you turn off the access checks
for this particular Method instance, for reflection only. Now you can access it even if it is private,

53
CORE JAVA

protected or package scope, even if the caller is not part of those scopes. You still can't access the
method using normal code. The compiler won't allow it.

Serialization? When to use?  Advantage?


Serialization in java is a mechanism of writing the state of an object into a byte stream.

It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.

The reverse operation of serialization is called deserialization.

The String class and all the wrapper classes implements java.io.Serializable interface by default.

Advantage

It is mainly used to travel object's state on the network (known as marshaling).

Implementation

In order to implement serialization, we need to use two classes from java.io package: ObjectOutputStream
and ObjectInputStream. ObjectOutputStream has a method called writeObject, while ObjectInputStream has
a method called readObject. Using writeobject we can write and readObject can be used to read the object
from the stream.

Serializable vs Externalizable
1) One of the obvious difference between Serializable and Externalizable is that Serializable is a  i.e. does not
contain any method but Externalizable interface contains two methods writeExternal() and readExternal().

2) Second difference between Serializable vs Externalizable is responsibility of Serialization. When a class


implements Serializable interface, default Serialization process gets kicked off and that takes responsibility of
serializing super class state. When any  implement java.io.Externalizable than its your responsibility to
implement Serialization process i.e. preserving all important information.

3) This difference between Serializable and Externalizable is performance. You cannot do much to improve
performance of default serialization process except reducing number of fields to be serialized by
using and  but with Externalizable interface you have full control over Serialization process.

4) Another important difference between Serializable and Externalizable is maintenance. When your Java
class implements Serializable interface its tied with default representation which is fragile and easily
breakable if structure of class changes e.g. adding or removing field. By using java.io.Externalizable interface
you can create your own custom binary format for your object.

Read more: http://java67.blogspot.com/2012/10/difference-between-serializable-vs-externalizable-
interface.html#ixzz3wlsaXHb1

54
CORE JAVA

Set vs Map
A map has a pair for example (key, object).  With key, you can get the object 

A set is just the object (object) just one.

Map (Interface)

 In Map, we used to store the data in key and value pairs, we may have duplicate values but no
duplicate keys

 In Map we don’t have iterator() method, but we can get the keys by calling the method keySet()
Map m; // insert values

Set s = m.keySet();

// Get Map keys into the Set and then iterate this Set object normally

// m.keySet() returns Set object with Map keys

Iterator iter = s.iterator();

Statement vs PreparedStatement vs CallableStatement


Statement PreparedStatement CallableStatement

It is used to execute normal SQL It is used to execute parameterized or It is used to call the stored

queries. dynamic SQL queries. procedures.

It is preferred when a particular SQL It is preferred when a particular query It is preferred when the stored

query is to be executed only once. is to be executed multiple times. procedures are to be executed.

You can pass 3 types of parameters

You cannot pass the parameters to You can pass the parameters to SQL using this interface. They are – IN,

SQL query using this interface. query at run time using this interface. OUT and IN OUT.

This interface is mainly used for It is used for any kind of SQL

DDL statements like CREATE, ALTER, queries which are to be executed It is used to execute stored

DROP etc. multiple times. procedures and functions.

The performance of this interface is The performance of this interface is The performance of this interface is

55
CORE JAVA

better than the Statement interface

(when used for multiple execution of

very low. same query). high.

ExecuteQuery, executeUpdate and Execute

56
CORE JAVA

String
Immutable String in JAVA
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

Once string object is created its data or state can't be changed but a new string object is created.

Let's try to understand the immutability concept by the example given below:

class Testimmutablestring{  

 public static void main(String args[]){  

    String s="Sachin";  

    s.concat(" Tendulkar"); //concat() method appends the string at the end  

    System.out.println(s); //will print Sachin because strings are immutable objects  

  }  

}  

Output: Sachin

But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object. For
example:

class Testimmutablestring1{  

 public static void main(String args[]){  

    String s="Sachin";  

    s=s.concat(" Tendulkar");  

    System.out.println(s);  

  }  

}  

Output: Sachin Tendulkar

Is String a data Type?


String isn't a primitive datatype - it's a class, a reference type

57
CORE JAVA

Is String final?
yes, String is final to make it immutable. One advantage of immutable objects is that

You can share duplicates by pointing them to a single instance.

Is String thread safe?


Is String thread safe?  Yes

String
String is immutable (once created cannot be changed) object. The object created as a String is stored in
the Constant String Pool. 

Every immutable object in Java is thread safe, that implies String is also thread safe. String cannot be
used by two threads simultaneously.

String once assigned cannot be changed.

String  demo = " hello " ;

// The above object is stored in constant string pool and its value cannot be modified.

demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable        

 // "hello" string still exists in string constant pool and its value is not overridden but we lost reference to
the  "hello" string  

StringBuffer

StringBuffer is mutable means one can change the value of the object. The object created through
StringBuffer is stored in the heap. StringBuffer has the same methods as the StringBuilder, but each
method in StringBuffer is synchronized that is StringBuffer is thread safe. 

Due to this it does not allow two threads to simultaneously access the same method. Each method can
be accessed by one thread at a time.

58
CORE JAVA

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread
safe property. Thus, StringBuilder is faster than the StringBuffer when calling the same methods of each
class.

StringBuffer value can be changed, it means it can be assigned to the new value. Nowadays it’s a most
common interview question, the differences between the above classes.

String Buffer can be converted to the string by using toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;

// The above object stored in heap and its value can be changed.

demo1=new StringBuffer("Bye");

// Above statement is right as it modifies the value which is allowed in the


StringBuffer

StringBuilder

StringBuilder is same as the StringBuffer, that is it stores the object in heap and it can also be modified.
The main difference between the StringBuffer and StringBuilder is that StringBuilder is not thread safe. 

StringBuilder is fast as it is not thread safe.  


StringBuilder demo2= new StringBuilder("Hello");

// The above object too is stored in the heap and its value can be modified

demo2=new StringBuilder("Bye"); 

// Above statement is right as it modifies the value which is allowed in the


StringBuilder

----------------------------------------------------------------------------------

                                    String                    StringBuffer         StringBuilder

----------------------------------------------------------------------------------                 

Storage Area | Constant String Pool           Heap                       Heap 

Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )

Thread Safe   |           Yes                                  Yes                              No

 Performance |         Fast                                Very slow                    Fast

59
CORE JAVA

String pool?
As the name suggests, String Pool is a pool of Strings stored in Java heap memory. We know that String
is special class in java and we can create String object using new operator as well as providing values in
double quotes.

String vs StringBuffer vs StringBuilder?


Mutability Difference:

String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and
StringBuilder are mutable so they can change their values.

Thread-Safety Difference:

The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So, when the
application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more
efficient than StringBuffer.

Situations:

If your string is not going to change, use a String class because a String object is immutable.

If your string can change (example: lots of logic and operations in the construction of the string) and will only
be accessed from a single thread, use a StringBuilder is good enough.

If your string can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer
is synchronous so you have thread-safety.

Surrogate Pair (Low and High Surrogate)

Synchronize List, Set and Map elements


In Java framework, public class Collections which exends Ojbect consists of static methods that work on
and return collections. To make List, Set or Map elements synchronized this class provides below three
methods:

 synchronizedList(List list): Returns synchronized which is thread safe list and backed by specified
list.

 synchronizedMap(Map<K,V> m): Returns synchronized which is thread safe map backed by


specified map.

 synchronizedSet(Set s): Returns synchronized which is thread safe set backed by specified set.

60
CORE JAVA

Thread
A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.

Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It
shares a common memory area.

Advantages of Thread?
1) It doesn't block the user because threads are independent and you can perform multiple operations
at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Create Thread in Java?


1) By extending Thread class:
class Multi extends Thread{  

public void run(){  

System.out.println("thread is running...");  

}  

public static void main(String args[]){  

Multi t1=new Multi();  

t1.start();  

 }  

2) By implementing the Runnable interface:


class Multi3 implements Runnable{  

public void run(){  

System.out.println("thread is running...");  

}  

  

public static void main(String args[]){  

Multi3 m1=new Multi3();  

Thread t1 =new Thread(m1);  

t1.start();  

61
CORE JAVA

}  

}  

If you are not extending the Thread class, your class object would not be treated as a thread object. So
you need to explicitly create Thread class object. We are passing the object of your class that
implements Runnable so that your class run() method may execute.

Deadlock
A lock occurs when multiple processes try to access the same resource at the same time.

One process loses out and must wait for the other to finish.

A deadlock occurs when the waiting process is still holding on to another resource that the first needs
before it can finish.

So, an example: Resource A and resource B are used by process X and process Y

X starts to use A.

X and Y try to start using B. Y 'wins' and gets B first

now Y needs to use A

A is locked by X, which is waiting for Y

The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to
lock anything as much as you can.

In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and
switch to optimistic/dirty/nolock reads as much as possible.

Extends Thread vs Implements Runnable

Implements Runnable Extends Thread

You can extend any other class. You can’t extend any other class.

No overhead of additional methods. Overhead of additional methods from Thread class.

Separates the task from the runner. Doesn’t separate the task from the runner.

Best object oriented programming practice. Not a good object oriented programming practice.

Loosely coupled. Tightly coupled.

Improves the reusability of the code. Doesn’t improve the reusability of the code.

More generalized task. Thread specific task.

62
CORE JAVA

Maintenance of the code will be easy. Maintenance of the code will be time consuming.

Extends Thread is better than implement Runnable


Performance.

There is overhead of memory if we use interface, because for interface there will be runtime overhead
which takes time to load. So, in performance critical code we had to avoid interface unless and until it is
required. Whereas extending thread makes the compiler at the runtime itself to bind the class. But, the
code will work same in both ways except the performance.

Thread pool
- A thread pool manages a group of threads. It contains a queue that keeps jobs waiting to get
executed.

- Java 5 (java.util.concurrent)

ExecutorService implements Executors interface

ExecutorService executor = Executors.newFixedThreadPool(5);

Thread  safety?
A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees
safe execution by multiple threads at the same time. 

Thread states
- NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING (Life time thread remains on various)

NEW: means thread is just created but not yet started

RUNNABLE: means thread is started but waiting for CPU to be assigned by thread scheduler

BLOCKED, WAITING and TIMED_WAITING: means thread is not doing anything instead it’s been
blocked and waiting for IO to finished, class or object lock, or any other thread etc.

Life cycle of thread


The java thread states are as follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)

63
CORE JAVA

5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

Monitor/manage thread
How to monitor/manage threads?

64
CORE JAVA

How to monitor JVM performance? JVM tuning?

I use Jconsole and VisualVM to monitor application threads. I prefer VisualVM because of much more
information.

VisualVM displays real-time, high-level data on thread activity in the Threads tab.

The information displayed in the Threads tab is based on Java Management Extensions (JMX). The
Threads tab is visible if VisualVM can make a JMX technology-based connection (JMX connection) with
the target application and retrieve JMX instrumentation from the JVM software.

JConsole: To invoke jconsole, just execute the following command. Example shown below is for
Windows.

JDK_HOME/bin/jconsole.exe <PROCESS ID OF YOUR JAVA APPLICATION>

65
CORE JAVA

VisualVM: Start visualvm by running the command

JDK_HOME/bin/jvisualvm.exe

Notify vs notifyall?
notify method wakes up only one thread waiting on the object and that thread starts execution. So if
there are multiple threads waiting for an object, this method will wake up only one of them. The choice
of the thread to wake depends on the OS implementation of thread management.

notifyAll method wakes up all the threads waiting on the object, although which one will process first
depends on the OS implementation.

Methods
- Thread.sleep():

+ method is used to pause thread for specified duration.

+ You can put a Thread on sleep, where it does not do anything and release the CPU for
specified duration.

66
CORE JAVA

- Thread.join()

+ is used to wait for thread to complete its task before running

- Thread.yield()

+ method is used to release CPU so that other thread can acquire it.

- t.wait() and notify()

+ methods are used to communicate between two threads i.e. for inter thread communication
in Java

- wait(): tells the calling thread to give up the monitor and go to sleep until some other thread enters
the same monitor and calls notify( )

- notify(): wakes up the first thread that called wait() on the same object.

- notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread
will run first.

- t.interrupt():

+ Is a way to cancel tasks.

+ it will help breaks out the sleeping or waiting thread by throwing InterruptedException.

(If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal
behavior and doesn't interrupt the thread but sets the interrupt flag to true)

Priority
Let say we have 2 threads: A and B. Is there any way to be sure that thread A will execute before the
thread B?

You have a setPriority() method in the Thread class. So you can use this method to set priorty of the
thread A higher than thread B. But this way does not guarantee that thread A will go first.

67
CORE JAVA

Process vs Thread

Process Thread

Processes are heavy weight operations. Threads are light weight operations.

Every process has its own memory space. Threads use the memory of the process they belong to.

Inter thread communication is fast as threads of the

Inter process communication is slow as processes same process share the same memory address of the

have different memory address. process they belong to.

Context switching between the process is more Context switching between threads of the same process

expensive. is less expensive.

Processes don’t share the memory with other Threads share the memory with other threads of the

processes. same process.

Semaphore
Semaphore is an object which helps two threads to communicate with one another in order to
synchronize their operation.

States of Thread?
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

1. New

2. Runnable

3. Running

4. Non-Runnable (Blocked)

5. Terminated

68
CORE JAVA

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

69
CORE JAVA

Thread safety and synchronization


Thread safe is used to describe a method that can run safely in multithreaded environments allowing
accessing to data in a safe and efficient way. Thread safety is achieved by synchronization.

Synchronization assures that the object data is not accessed by multiple threads at the same time.

User Threads Vs Daemon Threads

Below is the quick recap of the above points.

User Threads Daemon Threads

JVM waits for user threads to finish their work. It will JVM will not wait for daemon threads to finish their work. It

not exit until all user threads finish their work. will exit as soon as all user threads finish their work.

User threads are foreground threads. Daemon threads are background threads.

User threads are high priority threads. Daemon threads are low priority threads.

User threads are created by the application. Daemon threads, in most of time, are created by the JVM.

User threads are mainly designed to do some specific

task. Daemon threads are designed to support the user threads.

JVM will not force the user threads to terminate. It JVM will force the daemon threads to terminate if all user

will wait for user threads to terminate themselves. threads have finished their work.

wait() and notify()


By using wait() and notify(), a thread can give up its hold on a lock at an arbitrary point, and then wait
for another thread to give it back before continuing.

70
CORE JAVA

By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
Later, when the necessary event happens, the thread that is running it calls notify() from a block
synchronized on the same object. Now the first thread wakes up and begins trying to acquire the lock
again.

wait  vs  sleep?


Object wait methods has three variances, one which waits indefinitely for any other thread to call notify
or notifyAll method on the object to wake up the current thread. Other two variances puts the current
thread in wait for specific amount of time before they wake up.

wait() and sleep() methods

wait() sleep()

The thread which calls wait() method releases the lock it The thread which calls sleep() method doesn’t release the

holds. lock it holds.

The thread regains the lock after other threads call either No question of regaining the lock as thread doesn’t

notify() or notifyAll() methods on the same lock. release the lock.

wait() method must be called within the synchronized sleep() method can be called within or outside the

block. synchronized block.

wait() method is a member of java.lang.Object class. sleep() method is a member of java.lang.Thread class.

wait() method is always called on objects. sleep() method is always called on threads.

wait() is a non-static method of Object class. sleep() is a static method of Thread class.

Waiting threads can be woken up by other threads by Sleeping threads cannot be woken up by other threads. If

calling notify() or notifyAll() methods. done so, thread will throw InterruptedException.

 To call sleep() method, thread need not to have object

 To call wait() method, thread must have object lock. lock.

71
CORE JAVA

72
CORE JAVA

Yield vs sleep?
yield(): 

Causes the currently executing thread object to temporarily pause and allow other threads to execute. 

sleep(long millis) or sleep(long millis, int nanos)

Causes the currently executing thread to sleep (stop execution) for the specified number of milliseconds
plus the specified number of nanoseconds.

TreeSet

TreeSet creates a collection that uses a tree for storage. Items in collection are stored in ascending
order. TreeSet are good choice for storing large amount of data.

Type
Could you describe about "Strong typed"?
Strong type is checking the types of variables at compile time.

Weak typing is checking the types of the system at run-time.

Synchronization

Synchronization in java is the capability to control the access of multiple threads to any shared resource.

There are two types of synchronization

Process Synchronization

Thread Synchronization
synchronized void printTable(int n){//synchronized method  

void printTable(int n){//method not synchronized  

73
CORE JAVA

Variable
Default value of the local variables?
The local variables will not have any default values. They must be explicitly provided with some value.
Accessing an uninitialized local variable will result in a compile-time error.

Transient vs volatile variable /ˈvɒl ə tl/


1) transient keyword is used along with instance variables to exclude them from serialization process. if
a field is transient its value will not be persisted.
volatile keyword can also be used in variables to indicate compiler and JVM that always read its value
from main memory and follow happens-before relationship on visibility of volatile variable among
multiple thread.

2) transient keyword cannot be used along with static keyword but volatile can be used along with
static.

Volatile is a keyword in Java. You cannot use this as a variable or method name. We typically use volatile
keyword when we share variables with more than one thread in a multi-threaded environment, and we
want to avoid any memory inconsistency errors due to the caching of these variables in the CPU cache

Web app vs enterprise app


Web application is deployed in Web server which has web container. Web application - JSP, Servlet,
Java. Web application are programs which created to run in a web browser.

Enterprise Application is deployed in Application server which has Web container, EJB container, set up
for messaging services etc. Enterprise application. - JSP, Servlet, Java, EJB, Web Services, JMS. Enterprise
application is an integrated program which usually used in a large companies

Think of three tiers:

1) the client tier; this tier runs a browser or some other client Java code.

2) the web tier; this tier runs your web server or Servlet container that sends pages of html or other data
to the first tier.

3) the business logic tier: this tier runs your enterprise Java beans, your database connectivity code etc.
This tier communicates with the second tier.

All together these tiers make up an 'enterprise application'; when you leave out the third tier you have a
'web based' application. The first tier by itself is just a desktop application if more than a browser is
used.

74
CORE JAVA

Web server vs application server

Application Server Web Server

A server that exposes business logic to


What is it? client applications through various A server that handles HTTP protocol.
protocols including HTTP.

Application server is used to serve web


based applications and enterprise based
Web server is used to serve web based
Job applications (i.e servlets, jsps and ejbs...).
applications. (i.e servlets and jsps)
Application servers may contain a web
server internally.

Keeping HTML, PHP, , etc files available


To deliver various applications to another
for the web browsers to view when a user
Functions device, it allows everyone in the network
accesses the site on the web, handles
to run software off the same machine.
HTTP requests from clients.

Supports distributed transaction and EJB's Servlets and JSP

JBOSS AS7

IBM WebSphere Tomcat

Example Oracle/BEA WebLogic Jetty

TomEE Sun Java System Web Server

Glassfish

75

You might also like