Java Passes Everything by Value, and Not by Reference. and When We Say Everything, We
Java Passes Everything by Value, and Not by Reference. and When We Say Everything, We
Java passes everything by value, and not by reference. And when we say everything, we
mean everything – objects, arrays (which are objects in Java), primitive types (like ints and
floats), etc. – these are all passed by value in Java.
http://www.programmerinterview.com/index.php/java-questions/does-java-pass-by-
reference-or-by-value/
The interface does not have any method to be implemented is called marker interface. It is
used to indicate something to compiler or JVM. It is used to store state of an object.
Marker interface has no method. Java has built-in marker interface like Serializable,
Clonable etc that are understood by JVM.
We can create our own marker interface but it has nothing to do with JVM, we can add
some checks with instanceOf.
interface Marker{ }
class Main{
public static void main(String[] args){
A ob = new A();
if (ob instanceOf Marker){
System.out.println(ob.add(2, 5));
}
else{
System.out.println("hi");
}
}
}
How Annotations are better than Marker Interfaces? - They let you achieve the same
purpose of conveying metadata about the class to its consumers without creating a separate type
for it. Annotations are more powerful, too, letting programmers pass more sophisticated
information to classes that "consume" it.
4. instanceof in java?
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
Persistent java object means, the state of the object can be stored to the persistent storage
(eg. hard drive) for later use. State of java object means at particular instance what
information its members are consisting. For object persistence to be possible, the class must
implement the Serializable interface. This interface does not have any method to be
implemented that is why called marker interface.
Sometimes you may want some of your members not required to be saved as part of object
state. You make those member variables transient so that while serialization takes place, all
the members get serialized except transient variables. Static members are not part of
object, they are for class, so no serialization for them also.
IS-A Relationship :
HAS-A Relationship :
Has-A means an instance of one class “has a” reference to an instance of another class
or another instance of same class. It is also known as “composition” or “aggregation”.
8. Understanding-Association-Aggregation-and-Composition
http://www.codeproject.com/Articles/330447/Understanding-Association-Aggregation-and-
Composit
Life time Have their own lifetime Have their own lifetime Owner's life time
Child Child objects all are Child objects belong to a Child objects belong to a
object independent single parent single parent
Below is a visual representation of how the relationships have emerged from the
requirements.
1. Manager is an employee of XYZ limited corporation. -- Inheritance
2. Manager uses a swipe card to enter XYZ premises. -- Association
3. Manager has workers who work under him. -- Aggregation
4. Manager has the responsibility of ensuring that the project is successful.
--Composition
5. Manager's salary will be judged based on project success. -- Composition
9. Polymorphism
o Polymorphism is the ability of an object to take on many forms.
o There are two types of polymorphism in java- Runtime polymorphism(Dynamic
polymorphism) and Compile time polymorphism (static polymorphism).
o Compile time polymorphism is nothing but the method overloading in java. In simple
terms we can say that a class can have more than one methods with same name but
with different number of arguments or different types of arguments or both
o Method overriding is a perfect example of runtime polymorphism. In this kind of
polymorphism, reference of class X can hold object of class X or an object of any sub
classes of class X. For e.g. if class Y extends class X then both of the following statements
are valid:
Y obj = new Y();
//Parent class reference can be assigned to child object
X obj = new Y();
o Since in method overriding both the classes (base class and child class) has same
method, compile doesn’t figure out which method to call at compile-time. In this case
JVM (java virtual machine) decides which method to call at runtime that’s why it is
known as runtime or dynamic polymorphism.
o Static binding happens at compile-time while dynamic binding happens at runtime.
o Binding of private, static and final methods always happen at compile time since these
methods cannot be overridden. Binding of overridden methods happen at runtime.
o Java uses static binding for overloaded methods and dynamic binding for overridden
methods.
o Important Points
Final methods cannot be overrided but can be accessed in subclass
Private methods can be overrided and cannot be accessed in subclass or any
other class
Static methods can be overrided and can be accessed in subclass
If class A is a parent class and class B is a sub class
A has static void add()
A has void sub()
Scenario 1 (Both methods are overrided in subclass)
o A a=new B();
o a.add(); --Super class method will be called as it is static
o a.sub(); --Sub class will be called
Scenario 2 (Both methods are not overrided in subclass)
o A a=new B();
o a.add(); -- Super class method will be called
o a.sub(); -- Super class method will be called
Scenario 3(Both methods are not available in class A and available
only in class B)
o A a=new B();
o a.add(); -- Compile time error since the method is undefined for
class A
o a.sub(); -- Compile time error since the method is undefined for
class A
10. What is the difference between up-casting and down-casting?
Up-casting: The upcasting is casting from the child class to base class. The upcasting in java
is implicit which means that you don't have to put the braces (type) as an indication for
casting.
}
}
Down-casting: The downcasting is the casting from base class to child class. Downcasting is
explicit note the usage of braces(type)
((Dog)a).callme2();
Or
Dog d = (Dog)a;
d.callme2();
The reason why is because animal's runtime type is Animal, and so when you tell the
runtime to perform the cast it sees that animal isn't really a Dog and so throws a
ClassCastException.
http://beginnersbook.com/2013/05/abstract-class-vs-interface-in-java/
Data abstraction simply means generalizing something to hide the complex logic
that goes underneath. We achieve data abstraction in Java primarily by using
Interfaces and abstract classes.
In Java, the equals method can be considered to perform a deep comparison of the
value of an object, whereas the == operator performs a shallow comparison. The equals
method compares the content of two objects rather than two objects' references. The
== operator with reference types (i.e., Objects) evaluates as true if the references are
identical - point to the same object. With value types (i.e., primitives) it evaluates as true
if the value is identical. The equals method is to return true if two objects have identical
content - however, the equals method in the java.lang.Object class - the default equals
method if a class does not override it - returns true only if both references point to the
same object.
Default implementation of equals checks for only the references and not the content.
Only if we override equals() method, content will be compared. Since the String literal
overrides equals() method by default, it checks the content.
http://www.journaldev.com/797/what-is-java-string-pool
String allocation, like all object allocation, proves costly in both time and memory. The
JVM performs some trickery while instantiating string literals to increase performance
and decrease memory overhead. To cut down the number of String objects created in
the JVM, the String class keeps a pool of strings. Each time your code creates a string
literal, the JVM checks the string literal pool first. If the string already exists in the pool,
a reference to the pooled instance returns. If the string does not exist in the pool, a new
String object instantiates then is placed in the pool. Java can make this optimization
since strings are immutable and can be shared without fear of data corruption. For
example
true
A String object is created out of the String literal pool, even if an equal string already
exists in the pool. Considering all that, avoid new String unless you specifically know that
you need it! For example
false true
A JVM has a string pool where it keeps at most one object of any String. String literals
always refer to an object in the string pool. String objects created with the new operator
do not refer to objects in the string pool but can be made to using String's intern()
method. The java.lang.String.intern() returns an interned String, that is, one that has an
entry in the global String pool. If the String is not already in the global String pool, then it
will be added. For example
s1 == s2? false
s1 == s3? true
There is a table always maintaining a single reference to each unique String object in the
global string literal pool ever created by an instance of the runtime in order to optimize
space. That means that they always have a reference to String objects in string literal
pool, therefore, the string objects in the string literal pool not eligible for garbage
collection.
String StringBuffer
String class is immutable StringBuffer class is mutable
String is slow and consumes more memory
StringBuffer is fast and consumes less
when you concat too many strings because
memory when you cancat strings.
every time it creates new instance.
String class overrides the equals() method of
StringBuffer class doesn't override the
Object class. So you can compare the
equals() method of Object class.
contents of two strings by equals() method.
String literals can be declared in the following StringBuffer s = “india”; is not possible. It
way. can be created only through “new”
String s = “india”; keyword.
String s= new String("india"); StringBuffer s = new StringBuffer(“india”);
20. Difference between StringBuilder and StringBuffer
StringBuffer StringBuilder
StringBuilder is non-synchronized i.e. not
StringBuffer is synchronized i.e. thread safe. It
thread safe. It means two threads can call
means two threads can't call the methods of
the methods of StringBuilder
StringBuffer simultaneously.
simultaneously.
StringBuffer is less efficient than StringBuilder is more efficient than
StringBuilder. StringBuffer.
Whenever an error occurs within a Java code on runtime, an Object is created called
Exception Object, it contains all information about exception including type or class of
exception and the location where the exception is occurred in the program.
Java run time environment searches for an appropriate handler for this exception object, it
starts searching from the current method to calling methods in reverse and at last the main
method. If an appropriate handler code is found then the exception is handled normally,
otherwise program terminates.
Event handling is a mechanism that provides handler code snippets to the program, so that
the exceptions can be caught and programming flow can be maintained.
The exceptions that are not checked at compile time are called unchecked
exceptions. It means if your program is throwing an unchecked exception and even if
you didn’t handle/declare that exception, the program won’t give a compilation error.
Most of the times these exception occurs due to the bad data provided by user during
the user-program interaction. It is up to the programmer to judge the conditions in
advance, that can cause such exceptions and handle them appropriately. classes that
extends RuntimeException comes under unchecked exceptions. Examples of some
unchecked exceptions are listed below.
ArithmeticException
package com.beingjavaguys.core;
public class ExceptionTest {
public static void main(String[] args) {
int i = 10/0;
}
}
Console :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:6)
ArrayIndexOutOfBoundsException
Console :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
4 at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:7)
NullPointerException
Console:
Exception in thread "main" java.lang.NullPointerException
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:9)
2) Checked Exception
If some code within a method throws a checked exception, then the method must
either handle the exception or it must specify the exception using throws keyword.
For example, consider the following Java program that opens file at location
“C:\test\a.txt” and prints first three lines of it. The program doesn’t compile, because the
function main() uses FileReader() and FileReader() throws a checked
exception FileNotFoundException. It also uses readLine() and close() methods, and
these methods also throw checked exception IOException
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
fileInput.close();
}
}
Output:
To fix the above program, we either need to specify list of exceptions using throws, or we
need to use try-catch block. We have used throws in the below program.
Since FileNotFoundException is a subclass of IOException, we can just
specify IOException in the throws list and make the above program compiler-error-free.
class Main {
public static void main(String[] args)throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
fileInput.close();
}
}
A. throw: Sometimes we explicitly want to create exception object and then throw it to
halt the normal processing of the program. throw keyword is used to throw exception
to the runtime to handle it.
B. throws: When we are throwing any checked exception in a method and not handling
it, then we need to use throws keyword in method signature to let caller program
know the exceptions that might be thrown by the method. The caller method might
handle these exceptions or propagate it to its caller method using throws keyword.
We can provide multiple exceptions in the throws clause and it can be used
with main() method also.
C. try-catch: We use try-catch block for exception handling in our code. try is the start of
the block and catch is at the end of try block to handle the exceptions. We can have
multiple catch blocks with a try and try-catch block can be nested also. catch block
requires a parameter that should be of type Exception.
D. finally: finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that
will not get closed, so we can use finally block. finally block gets executed always,
whether exception occurrs or not.
MyException.java
public class MyException extends Exception
{
public MyException(String message)
{
super(message);
}
}
"MyException" is our exception class name. You can give any name of your
choice. Important thing to be noted is our class extends "Exception" class. This is
all we need to do make a custom defined exception
"Now we define a constructor of my class. This constructer takes a "String"
argument. We call super class' constructor (super class here is "Exception class")
and pass this string to it. Now Java creates a new Exception with the message
passed in the input String
ExceptionDemo.java
public class ExceptionDemo
{
public static void main(String args[]) throws Exception
{
ExceptionDemo exceptionDemo = new ExceptionDemo();
exceptionDemo.displayNumbers();
}
StackOverflowError is related to stack. All your local variables and methods calls related
data will be on stack. For every method call one stack frame will be created and local as well as
method call related data will be placed inside the stack frame. Once method execution is
completed, stack frame will be removed. ONE WAY to reproduce this is, have infinite loop for
method call, you will see stackoverflow error, because stack frame will be populated with
method data for every call but it won't be freed (removed).
How to avoid Make sure method calls are ending (not in infinite loop)
StackOverflowError happens when you execute too many methods one inside another (for
example with an infinite recursion), which is limited by the size of the stack.
OutOfMemoryError happens when the JVM runs out of space to allocate new objects, which are
allocated on the heap.
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 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();
}
}
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.
After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second
time, it will throw exception.
Each thread starts in a separate call stack. Invoking the run() method from main thread, the
run() method goes onto the current call stack rather than at the beginning of a new call
stack.
We can prevent a thread from execution by using any of the 3 methods of Thread class:
1. yield() method pauses the currently executing thread temporarily for giving a chance to
the remaining waiting threads of the same priority to execute. If there is no waiting
thread or all the waiting threads have a lower priority then the same thread will continue
its execution. The yielded thread when it will get the chance for execution is decided by
the thread scheduler whose behavior is vendor dependent.
2. join() If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter
into waiting state until t2 completes its execution.
3. sleep() Based on our requirement we can make a thread to be in sleeping state for a
specified period of time. It holds the lock.
wait(): It is a method on Object class. It makes the current thread into the "Not Runnable"
state. Wait is called on a object, not a thread. Before calling wait() method, the object
should be synchronized, means the object should be inside synchronized block. The call to
wait() releases the acquired lock
notify() This method is inherited from Object class. It wakes up the first thread that
called wait() on the same object. It should be noted that calling notify() does not actually
give up a lock on a resource. It tells a waiting thread that that thread can wake up. However,
the lock is not actually given up until the notifier’s synchronized block has completed. So, if a
notifier calls notify() on a resource but the notifier still needs to perform 10 seconds of
actions on the resource within its synchronized block, the thread that had been waiting will
need to wait at least another additional 10 seconds for the notifier to release the lock on the
object, even though notify() had been called.
notifyAll() : This method is inherited from Object class. It wakes up all the threads that
called wait() on the same object. The highest priority thread will run first in most of the
situation, though not guaranteed. Other things are same as notify() method above.
wait(): This method is inherited from Object class. This method makes current
thread to wait until another thread invokes the notify() or the notifyAll() for this
object.
final: final is a keyword. The variable decleared 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
Synchronization control the access the multiple threads to a shared resources. Without
synchronization of threads, one thread can modify a shared variable while another thread
can update the same shared variable, which leads to significant errors.
35. What are the differences between synchronized method and synchronized block (statement)?
The practical differences are in controlling scope and the monitor. With a synchronized
method, the lock is obtained for the duration of the entire method. With synchronized
blocks you can specify exactly when the lock is needed.
Basically, synchronized blocks are more general, and synchronized methods can be
rewritten to use synchronized blocks:
class Program {
public synchronized void f() {
.........
}
}
is equivalent to
class Program {
public void f() {
synchronized(this){
...
}
}
}
For example, You have a method with some parts that need synchronized and others don't. The
synchronized block lets you synchronize only the partial line codes that really need it.
36. What is the difference between static synchronized and synchronized methods?
Static synchronized methods synchronize on the class object. If one thread is executing a
static synchronized method, all other threads trying to execute any static synchronized
methods will be blocked.
Non-static synchronized methods synchronize on this ie the instance of the class. If one
thread is executing a synchronized method, all other threads trying to execute any
synchronized methods will be blocked.
equals() - Indicates whether some other object is "equal to" this one.
finalize() - Called by the garbage collector on an object when garbage collection determines
that there are no more references to the object.
notifyAll() - Wakes up all threads that are waiting on this object's monitor.
wait() - Causes current thread to wait until another thread invokes the notify() method or
the notifyAll() method for this object.
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. Let's take a simple example:
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.
Collection framework represents a unified architecture for storing and manipulating group
of objects. It has:
An array is a container object that holds elements of similar data type. The length of an
array is established when the array is created.
Limitations:
These are fixed in size i.e. once we created an array object there is no
chance of increasing or decreasing size based on our requirement. Hence If
we don’t know size in advance , arrays are not recommended to use.
Arrays can hold only homogeneous elements.
To delete one element in the array, we need to traverse throughout the
array.
int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);
// print directly will print reference value
System.out.println(intArray);
// [I@7150bd4d
System.out.println(intArrayString);
// [1, 2, 3, 4, 5]
Reverse an array
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]
Wrapper classes are used to convert any primitive data type into an object and object into
data type
int k = 100;
Integer it1 = new Integer(k); or Integer it1=Integer.valueOf(k);
The int data type k is converted into an object, it1 using Integer class. The it1 object can be
used in Java programming wherever k is required an object.
The following code can be used to unwrap (getting back int from Integer object) the object
it1.
int m = it1.intValue();
System.out.println(m*m); // prints 10000
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object
into primitive automatically. The automatic conversion of primitive into object is known and
autoboxing and vice-versa unboxing.
int a=20;
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
Duplicity: List allows duplicate elements. Any number of duplicate elements can be inserted
into the list without affecting the same existing values and their indexes.
Set doesn’t allow duplicates. Set and all of the classes which implements Set interface
should have unique elements.
Map stored the elements as key & value pair. Map doesn’t allow duplicate keys while it
allows duplicate values.
Map can have single null key at most and any number of null values.
Order: List and all of its implementation classes maintains the insertion order.
Set doesn’t maintain any order; still few of its classes sort the elements in an order such as
LinkedHashSet maintains the elements in insertion order.
Similar to Set, Map also doesn’t stores the elements in an order, however few of its classes
does the same. For e.g. TreeMap sorts the map in the ascending order of keys and
LinkedHashMap sorts the elements in the insertion order, the order in which the elements
got added to the LinkedHashMap.
synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
System.out.println(i.next());
}
}
ArrayList Vector
ArrayList is not synchronized and gives Vector is synchronized and gives poor
better performance(fast). performance(slow)
ArrayList grow by half of its size if Vector doubles the array size if total
number of element exceeds from its number of element exceeds than its
capacity capacity
ArrayList is not a legacy class, it is Vector is a legacy class
introduced in JDK 1.2
The iterator and listIterator returned by The Enumeration returned by Vector is
ArrayList are fail-fast not fail-fast
A fail-fast system is nothing but immediately report any failure that is likely to lead to
failure. When a problem occurs, a fail-fast system fails immediately. In Java, we can find this
behavior with iterators. In case, you have called iterator on a collection object, and another
thread tries to modify the collection object, then concurrent modification exception will be
thrown. This is called fail-fast.
Contrary to fail-fast Iterator, fail-safe iterator doesn't throw any Exception if Collection is
modified structurally while one thread is Iterating over it because they work on clone of
Collection instead of original collection and that’s why they are called as fail-safe iterator.
Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator
Iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw
ConcurrentModificationException in Java.
HashTable, HashMap and HashSet are the Collection classes in java.util package that make
use of hashing algorithm to store objects. In all these Collection classes except HashSet,
objects are stored as key-value pairs. For the storage and the retrieval of any user-defined
objects it is a good practice to override the following methods which is mentioned below,
hashCode()
equals()
These methods are available in the Object class and hence available to all java classes. Using
these two methods, an object can be stored or retrieved from a Hashtable, HashMap or
HashSet.
hashCode() method
This method returns a hashcode value as an int for the object. Default implementation for
hashcode() should be overridden in order to make searching of data faster. The
implementation of hashCode() method for an user-defined object should be calculated
based on the properties of the class which we wish to consider.
equals() method
This method returns a boolean which specifies whether two objects are equal or not. The
default implementation of equals() method given by the Object Class uses the ‘==’ operator
to compare two object references, and returns true only if they refer to the same object.
But, we can meaningfully re-define this equals() method to have en equality check based on
our own criteria.
Consider the following code, which defines two user defined classes Employee and
EmployeeId which are supposed to be stored in a Map.
Employee.java
HashCodeTest.java
Let us look at how the same code works when we provide our desired implementation for
hashcode() and equals() methods. We basically override hashcode() here just to make the
object to be searched fast.
Employee.java
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != getClass()) {
return false;
}
Employee emp = (Employee) obj;
if (this.name == emp.name) {
return true;
}
return false;
}
@Override
public int hashCode() {
return name.hashCode();
}
}
EmployeeId.java
@Override
public int hashCode() {
return id.hashCode();
}
}
Now, we get the desired output ‘Jeny’, because as per our implementation for the equals()
method, the new EmployeeId("222") in the put statement and new EmployeeId("222") in
the get statement are considered one and the same.
54. Difference between HashMap and HashTable
HashMap HashTable
HashMap is not synchronized and gives HashTable is synchronized and gives
better performance(fast) poor performance(slow)
HashMap allows one null key and Hashtable doesn't allow any null key or
multiple null values value.
HashMap is a new class introduced in Hashtable is a legacy class
JDK 1.2
HashMap is traversed by Iterator and is Hashtable is traversed by Enumerator
fail-fast and Iterator and is not fail-fast
We can make the HashMap as Hashtable is internally synchronized and
synchronized by calling this code can't be unsynchronized.
Map m =
Collections.synchronizedMap(hashMap);
HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.
Similarities:
ArrayList LinkedList
ArrayList internally uses dynamic array to LinkedList internally uses doubly linked
store the elements. Search operation is list to store the elements.
pretty fast
ArrayList search operation is pretty fast. LinkedList requires the traversal through
get(int index) in ArrayList gives the all the elements for searching an element
performance of O(1) and its performance is O(n)
ArrayList gives variable LinkedList insert and remove operation
performance: O(n) in worst case (while gives O(1) performance
removing first element) and O(1) in best
case (While removing last element).
ArrayList maintains indexes and element LinkedList maintains element data and
data and so less memory overhead two pointers for neighbor nodes hence
the memory consumption is high in
LinkedList
In real world applications , you will more frequently use ArrayList than LinkedList. But in a
very specific situations LinkedList can be preferred.
1. ArrayList is preferred when there are more get(int) or search operations need to be
performed as every search operation runtime is O(1).
2. If application requires more insert(int) , delete(int) operations then the get(int) operations
then LinkedList is preferred as they do not need to maintain back and forth like arraylist to
preserve continues indices.
Similarities:
http://javahungry.blogspot.com/2013/08/difference-between-comparable-and.html
Sorting logic Sorting logic must be in same Sorting logic is in separate class.
class whose objects are being Hence we can write different
sorted. Hence this is called sorting based on different
natural ordering of objects attributes of objects to be
sorted. E.g. Sorting using
id,name etc.
Implementatio Class whose objects to be Class whose objects to be sorted
sorted must implement this do not need to implement this
n interface. e.g Country class interface. Some other class can
needs to implement implement this interface. E.g.-
comparable to collection of CountrySortByIdComparator
country object by id class can implement Comparator
interface to sort collection of
country object by id
Sorting method int compareTo(Object o1) int compare(Object o1,Object
o2)
This method compares this
object with o1 object and This method compares o1 and
returns a integer. Its value has o2 objects. and returns a
following meaning integer.Its value has following
1. positive – this object is meaning.
greater than o1 1. positive – o1 is greater than
2. zero – this object equals to o2
o1 2. zero – o1 equals to o2
3. negative – this object is less 3. negative – o1 is less than o1
than o1
Calling method Collections.sort(List) Collections.sort(List,
Here objects will be sorted on Comparator)
the basis of CompareTo Here objects will be sorted on
method the basis of Compare method in
Comparator
Package Java.lang.Comparable Java.util.Comparator
Sort sequence : In comparable ,Only one sort sequence can be created while in comparator
many sort sequences can be created .
Methods Used : Comparator interface in Java has method public int compare (Object o1,
Object o2) which returns a negative integer, zero, or a positive integer as the first argument
is less than, equal to, or greater than the second. While Comparable interface has method
public int compareTo(Object o) which returns a negative integer, zero, or a positive integer
as this object is less than, equal to, or greater than the specified object.
Objects needed for Comparision : If you see then logical difference between these two is
Comparator in Java compare two objects provided to it , while Comparable interface
compares "this" reference with the object specified. So only one object is provided which is
then compared to "this" reference.
Modify Classes : One has to modify the class whose instances you want to sort while in
comparator one build a class separate from the class whose instances one want to sort .
Employee.java
//this is required to print the user friendly information about the Employee
public String toString(){
return "Employee{" + "id=" + empId + ", name=" + name + ", age="
+ age + '}';
EmployeeMain.java
import java.util.*;
NameComparator.java
import java.util.Comparator;
AgeComparator.java
import java.util.Comparator;
Employee.java
import java.lang.Comparable;
EmployeeMain.java
import java.util.*;
Collections.sort(list);
http://www.ekiras.com/2014/09/how-does-hashmap-works-internally-in-java.html
http://www.javamadesoeasy.com/2015/02/hashmap-custom-implementation.html
Map.Entry interface - This interface gives a map entry (key-value pair). HashMap in Java
stores both key and value object, in bucket, as an object of Entry class which implements
this nested interface Map.Entry.
hashCode() - HashMap provides put(key, value) for storing and get(key) method for
retrieving Values from HashMap. When put() method is used to store (Key, Value) pair,
HashMap implementation calls hashcode on Key object to calculate a hash that is used to
find a bucket where Entry object will be stored. When get() method is used to retrieve
value, again key object is used to calculate a hash which is used then to find a bucket where
that particular key is stored.
equals() - equals() method is used to compare objects for equality. In case of HashMap key
object is used for comparison, also using equals() method Map knows how to handle
hashing collision (hashing collision means more than one key having the same hash value,
thus assigned to the same bucket. In that case objects are stored in a linked list Where
hashCode method helps in finding the bucket where that key is stored, equals method helps
in finding the right key as there may be more than one key-value pair stored in a single
bucket.
Bucket term used here is actually an index of array, that array is called
table in HashMap implementation. Thus table[0] is referred as bucket0,
table[1] as bucket1 and so on
Using hashCode() method, hash value will be calculated. Using that hash it will be
ascertained, in which bucket particular entry will be stored.
equals() method is used to find if such a key already exists in that bucket, if no then
a new node is created with the map entry and stored within the same bucket. A
linked-list is used to store those nodes.
If equals() method returns true, which means that the key already exists in the
bucket. In that case, the new value will overwrite the old value for the matched key.
As we know that HashMap also allows null, though there can only be one null key in
HashMap. While storing the Entry object HashMap implementation checks if the key is
null, in case key is null, it always map to bucket 0 as hash is not calculated for null keys.
62. What is the time complexity of Hashmap get() and put() method ?
The hashmap implementation provides constant time performance for (get and put) basic
operations i.e the complexity of get() and put() is O(1) , assuming the hash function
disperses the elements properly among the buckets.
HashMap ConcurrentHashMap
HashMap is not thread-safe ConcurrentHashMap is thread-safe that
is the code can be accessed by single
thread at a time
HashMap can be synchronized by using ConcurrentHashMap synchronizes or
synchronizedMap(HashMap) method. By locks on the certain portion of the Map .
using this method we get a HashMap To optimize the performance of
object which is equivalent to the ConcurrentHashMap , Map is divided
HashTable object. So every modification into different partitions depending
is performed on Map is locked on Map upon the Concurrency level . So that we
object. do not need to synchronize the whole
Map Object.
In HashMap there can only be one null ConcurrentHashMap does not allow
key . NULL values . So the key cannot be null
In multiple threaded environment In ConcurrentHashMap, as only single
HashMap is usually faster since any thread can access the certain portion of
number of threads can access the code at the Map, it reduces the performance .
the same time
64. HashMap example
Student.java
Address.java
StudentMain.java
import java.util.*;
output will b
a,b,c
66. Many immutable objects are available. But why only String has String constant pool not other
data types?
http://stackoverflow.com/questions/20394116/java-why-is-constant-pool-maintained-
only-for-string-values
Note: Eventhough, we are trying to modify a final String variable, error will not be
thrown because we are just trying to append and not assign.
String s = “abc”;
s = s + “def”; or s = s.concat(“def”);
System.out.println(s);
output: abcdef Since we are assigning a new value, it creates a new entry in String
pool and points the reference to “abcdef”.
class Singleton{
String s = "abc";
public static void main(String args[]){
String s ="";
s = s.concat("xyz");
System.out.println(s);
}
}
Output:xyz since static methods will be loaded at the compile time.
Char a =65 gives the output as “A” because the equivalent ASCII code for 65 is A
System.out.println(temp);
int arr[] = { 14, 46, 47, 92, 96, 52, 48, 99, 66, 85 };
int largest = arr[0];
int secondLargest = arr[0];
}
}
}
}
for(Character c: chArr) {
if(map.containsKey(c)) {
map.put(c, map.get(c)+1);
} else {
map.put(c, 1);
}
}
if(reverse.equalsIgnoreCase(s))
System.out.println(s+" is a Palindrome String");
else
System.out.println(s+" is not a Palindrome String");
}
}
79. Is the following way of instantiating the class using interface reference is valid?
interface a {
int i =0;
public void animal();
}
http://www.ekiras.com/2014/09/internal-implementation-of-hashset-and-how-hashset-
works-internally-in-java.html
public HashSet() {
map = new HashMap<>();
}
Set achieves the uniqueness in its elements through HashMap . In HashMap ,
each key is unique. So, when an object of HashSet is created, it will create an object
of HashMap . When an element is passed to Set , it is added as a key in the HashMap in
the add(Element e) method. Now, a value needs to be associated to the key. Java
uses a Dummy value ( new Object ) which is called PRESENT in HashSet .
In HashMap , the put(Key k,Value V) method returns:
1. null, if the key is unique. The key will be added to the map.
2. old value of the key, if the key is duplicated.
81. How Set or TreeSet or HashSet is not allowing duplicate elements? How is it restricting?
Internally TreeSet store element using HASHTABLE. HASHTABLE is a structure of Key value
pairs. Here what the values passed by the SET is treated as Keys of HASHTABLE Internally.
keys are unique cannot be duplicated. That is the reason if you pass any duplicate value it
return false and does not added to the SET ...
If the adding element return true it will added into SET. Else it return False, that why it won't
give any compilation or runtime error and it won’t be added to SET
Similarly HashSet uses HashMap for checking duplicate elements. As we know that in
HashMap , key should be unique. When element is added to HashSet, it is added to internal
HashMap as Key. This HashMap required some value so a dummy Object(eg : PRESENT) is
used as value in this HashMap.
so , actually when you are adding a line in HashSet like hashset.add(3) , what java does
internally is that it will put that 3 as a key in the HashMap(created during HashSet object
creation) and some dummy value that is Object's object is passed as a value to the key .
0
null
1
6
on execution because HashSet uses HashMap and one null key is allowed in
HashMap and output can be in any order
82. Which of the below statements are correct in inserting value into Hashtable?
Hashtable<String, String> h = new Hashtable<String, String>();
h.put(" ", "bbb"); //correct
h.put("", "ccccc"); //correct
h.put(null, "aaaa"); //throws null pointer exception since
hashtable does not allow null key
for(Map.Entry m : h.entrySet()){
System.out.println(m.getKey() + " " + m.getValue());
}
for(String t : list) {
if(!unique.add(t)) {
duplicates.add(t);
}
}
System.out.println(duplicates);
Output : [b,c,a]
Output : d: 1
b: 2
c: 2
a: 4
The Exceptions wich are checked by compiler for smooth execution of the program at
runtime is called checked exception.
Whether the Exception is checked or unchecked it always occured at runtime only . there
is no chance of occuring at compile time.
But in the program if there is any chance of raising checked exception ex:IOException,
InterruptedException( generally raised when we are using Files concept and Thread.sleep()
etc) compiler wont accept that code, we must handle that code by using either "try, catch"
or "throws" keyword.
Any exception either run time or compile exception can be declared using throws keyword.
class sample{
public static void bar(int i) throws ArithmeticException {
int result = 0;
try{
result = i/0;
}catch(Exception e){
System.out.println(e);
}
}
public static void main(String args[]){
sample s = new sample();
s.bar(10);
}
}
Output: java.lang.ArithmeticException: / by zero
Yes, both checked and unchecked exception can be thrown using custom exception.
The checked/unchecked refers to the requirement of handling the exception by the code
that uses your method throwing exception.
Say You throw an unchecked exception in your method (RuntimeException or its subclass).
You do not have to signal that your method throws it and anyone that uses your code does
not need to explicitly handle it.
However if You throw checked exception (Exception that isn't subclass of RuntimeException)
then your method must explicitly say that it throws exception and anyone that uses your
code must handle that exception - either by also declaring their method as method that
throws an exception (rethrow) or by using a try-catch block, around invocation of your
method that throws checked exception.
UserDefinedException(String s) {
super(s);
}
UserDefinedException(String s) {
super(s);
}
http://java67.blogspot.com/2012/12/difference-between-runtimeexception-and-checked-
exception.html#ixzz4BYsLbfBY
An immutable class is one whose state cannot be changed once created. Immutable objects
are good for caching purpose because you don’t need to worry about the value changes.
Other benefit of immutable class is that it is inherently thread-safe, so you don’t need to
worry about thread safety in case of multi-threaded environment.
There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float,
Double etc. In short, all the wrapper classes and String class is immutable.
HashMap handles collision by using linked list to store map entries (entry set) ended up in
same array location or bucket location
equals() checks if two objects are the same or not and returns a boolean.
compareTo() (from interface Comparable) returns an integer. It checks which of the two
objects is "less than", "equal to" or "greater than" the other.
The StringBuffer class has been part of the Java Library since the beginning
whereas the StringBuilder class was added in Java 5. The difference between the
two lies in thread safety. StringBuffer is thread-safe and StringBuilder is not
thread-safe. Most of the time, you do not need thread safety and using
StringBuffer in those cases has a performance penalty. This is the reason that
StringBuilder was added later.
Typesafe Enums
Covariant Return Type
Metadata (Annotations) :Built-In Java Annotations used in java code
@Override
@SuppressWarnings
@Deprecated
Varags
Static Import
http://stackoverflow.com/questions/22675604/multiple-interfaces-in-a-java-class-which-
gets-used-for-method-calls
Java 8:
https://www.softwaretestinghelp.com/java-8-interview-questions/
https://www.interviewbit.com/java-8-interview-questions/
Print random numbers using java 8 (if needed in sorted order add .sorted() after limit in the
below program)
import java.util.Random;
}}
import java.util.ArrayList;
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
System.out.println(sum(list));
}
Write a Java 8 program to square the list of numbers and then filter out the numbers
greater than 100 and then find the average of the remaining numbers?
import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
public class Java8 {
public static void main(String[] args) {
Integer[] arr = new Integer[] { 100, 100, 9, 8, 200 };
List<Integer> list = Arrays.asList(arr);
// Stored the array as list
OptionalDouble avg = list.stream().mapToInt(n -> n * n).filter(n -> n
> 100).average();
/* Converted it into Stream and filtered out the numbers
which are greater than 100. Finally calculated the average
*/
if (avg.isPresent())
System.out.println(avg.getAsDouble());
}
}
Q #28) Write a Java 8 program to find the lowest and highest number of a Stream?
import java.util.Comparator;
import java.util.stream.*;
public class Java8{
public static void main(String args[]) {
Integer highest = Stream.of(1, 2, 3, 77, 6, 5)
.max(Comparator.comparing(Integer::valueOf))
.get();
/* We have used max() method with Comparator.comparing() method
to compare and find the highest number
*/
Integer lowest = Stream.of(1, 2, 3, 77, 6, 5)
.min(Comparator.comparing(Integer::valueOf))
.get();
/* We have used max() method with Comparator.comparing() method
to compare and find the highest number
*/
System.out.println("The highest number is: " + highest);
System.out.println("The lowest number is: " + lowest);
}
}
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
for(Integer i : list1) {
System.out.println(i);
}
}
}
Given a list of integers, find out all the even numbers exist in the
list using Stream functions?
Given a list of integers, find out all the numbers starting with 1 using
Stream functions?
Given the list of integers, find the first element of the list using Stream
functions?
Given a list of integers, find the total number of elements present in the
list using Stream functions?
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
long count = myList.stream()
.count();
System.out.println(count);
Given a list of integers, sort all the values present in it using Stream
functions?
myList.stream()
.sorted()
.forEach(System.out::println);
https://www.java67.com/2018/10/java-8-stream-and-functional-programming-interview-questions-
answers.html
Program to count the duplicate characters
public class StringCountDuplicateCharJava8Streams {
printCountOfDuplicateCharJava8Stream("bbbcccccddddddaaaa");
printCountOfDuplicateCharJava8Stream("##^$!%^$!^%@!$^@!
kds");
// Step 1
IntStream intStream = input.chars();
// Step 2
Stream<Character> charsStream = intStream.mapToObj(ch ->
(char) ch);
// Step 3
Map<Character, Long> output =
charsStream.collect(Collectors.groupingBy(ch -> ch,
Collectors.counting()));
System.out.println(output);