Java CoreJava
Java CoreJava
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
2
CORE JAVA
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
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);
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.
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.
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 are the arrays containing arrays of different length. Jagged arrays are also
multidimensional arrays. They are also called as ragged arrays.
You can convert from ArrayList to traditional arrays using “toArray()” method
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.
You can’t change the size of the array once you create Size of the ArrayList grows and shrinks as you add or
ArrayList vs LinkedList
LinkedList
ArrayList
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 operations in ArrayList Insertion and removal in LinkedList are of order
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
ArrayList is of type Random Access. i.e elements to traverse from beginning or end to reach a
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
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.
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.
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.
Hide Copy Code
@Override
11
CORE JAVA
Hide Copy Code
//Sort by countryName
Collections.sort(listOfCountries,new Comparator<Country>() {
@Override
public int compare(Country o1, Country o2) {
return o1.getCountryName().compareTo(o2.getCountryName());
}
});
Class whose objects to be sorted must implement this interface. In this, we have to implement
compareTo(Object) method. For example:
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
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.
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.
14
CORE JAVA
String s;
Date d;
...
** 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.
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
}
}
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();
}
}
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
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
18
CORE JAVA
Long 0L 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.
Enumeration Iterator
You can’t do any modifications to collection while Using Iterator, you can remove an element of the
19
CORE JAVA
Errors Exceptions
Errors in Java are of type java.lang.Error. Exceptions in Java are of type java.lang.Exception.
Examples :
Checked Exceptions : SQLException, IOException
Examples : Unchecked Exceptions :
java.lang.StackOverflowError, ArrayIndexOutOfBoundException, ClassCastException,
java.lang.OutOfMemoryError NullPointerException
Equals method
Why we override equals() method?
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
...
return true;
“==” 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.
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.
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
- create an object and there is not enough space in heap to allocate that object
22
CORE JAVA
Default 512MB
- is memory leak through Classloaders and it’s very often surfaced in WebServer and application
server like tomcat, webshere, glassfish or WebLogic
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.
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 iterators doesn’t allow modifications of a Fail-Safe iterators allow modifications of a collection
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
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
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
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 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
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.
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?
1) Type-safety: We can hold only a single type of objects in generics. It doesn’t allow to store other
objects.
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
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
firstName.hashCode() *
lastName.hashCode();
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
of null values. HashTable doesn’t allow null keys and null values.
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
31
CORE JAVA
3) Both implement Map interface.
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 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
Null Keys and Null values One null key, any null values Not permit null key, but any null values
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;
obj1.add("Alive");
obj1.add("is");
obj1.add("Awesome");
33
CORE JAVA
System.out.println(obj1);
}
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;
obj1.add("Alive");
obj1.add("is");
obj1.add("Awesome");
System.out.println(obj1);
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.
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?
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().
Iterator have remove() method to remove element from the collection whereas For loop only support to
iterate the collection.
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.
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 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:
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
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.
Iterator<Integer> it = myList.iterator();
while(it.hasNext()){
Integer i = it.next();
System.out.println("Iterator Value::"+i);
myList.forEach(new Consumer<Integer>() {
});
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.
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
@Override
System.out.println("My Runnable");
}};
//use lamda
Runnable r1 = () -> {
System.out.println("My Runnable");
};
i1.method1("abc");
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.
//sequential stream
//parallel stream
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.
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.
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.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.
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.
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.
40
CORE JAVA
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.
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.
Loads code
Verifies code
Executes code
42
CORE JAVA
LinkedList
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)
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 (Interface)
Set (Interface)
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
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);
}
}
44
CORE JAVA
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);
}
}
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
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.
System.out.printIn("subash"); What is System? what is out and its type? what is println ?
In modern Java, marker interfaces have no place. They can be completely replaced by Annotations.
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.
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();
49
CORE JAVA
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
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
order of arguments. But, they must have same order of arguments while overriding a
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.
public, protected Overloaded methods can have same visibility or you can increase the visibility. But you
Static Context Overloaded methods can be static or not static. It You can’t override a static method.
50
CORE JAVA
Binding between method call and method Binding between method call and
definition happens at compile time (Static method definition happens at run time
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 overloading, only one class is required – super class and sub class.
required. I.e. Method overloading happens That means method overriding happens
"** 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.
privateStringField.setAccessible(true);
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.
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.
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:
privateStringMethod.setAccessible(true);
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 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.
The String class and all the wrapper classes implements java.io.Serializable interface by default.
Advantage
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().
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
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
It is used to execute normal SQL It is used to execute parameterized or It is used to call the stored
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 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.
DDL statements like CREATE, ALTER, queries which are to be executed It is used to execute stored
The performance of this interface is The performance of this interface is The performance of this interface is
55
CORE JAVA
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";
}
}
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);
}
}
57
CORE JAVA
Is String final?
yes, String is final to make it immutable. One advantage of immutable objects is that
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.
// 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.
// The above object stored in heap and its value can be changed.
demo1=new StringBuffer("Bye");
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.
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
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 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.
synchronizedList(List list): Returns synchronized which is thread safe list and backed by specified
list.
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.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
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.
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.
You can extend any other class. You can’t extend any other 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.
Improves the reusability of the code. Doesn’t improve the reusability of the code.
62
CORE JAVA
Maintenance of the code will be easy. Maintenance of the code will be time consuming.
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)
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)
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.
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
Monitor/manage thread
How to monitor/manage threads?
64
CORE JAVA
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.
65
CORE JAVA
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():
+ 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()
- Thread.yield()
+ method is used to release CPU so that other thread can acquire it.
+ 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():
+ 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 process communication is slow as processes same process share the same memory address of the
Context switching between the process is more Context switching between threads of the same process
Processes don’t share the memory with other Threads share the memory with other threads of the
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
69
CORE JAVA
Synchronization assures that the object data is not accessed by multiple threads at the same time.
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.
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.
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() sleep()
The thread which calls wait() method releases the lock it The thread which calls sleep() method doesn’t release the
The thread regains the lock after other threads call either No question of regaining the lock as thread doesn’t
wait() method must be called within the synchronized sleep() method can be called within or outside the
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 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.
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.
Synchronization
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
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.
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
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
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
JBOSS AS7
Glassfish
75