Why String is
immutable in Java? (Security, String pool implementation)
1) Imagine StringPool facility without making string
immutable , its not possible at all because in case of string pool one string
object/literal e.g. "Test" has referenced by many reference variables
, so if any one of them change the value others will be automatically gets
affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which
change the same object into "TEST" , so A will also be
"TEST" which is not desirable.
2)String has been widely used as parameter for many Java
classes e.g. for opening network connection, you can pass hostname and port
number as string , you can pass database URL as string for opening database
connection, you can open any file in Java by passing name of file as argument
to File I/O classes.
In case, if String is not immutable, this would lead serious
security threat, I mean some one can access to any file for which he has
authorization, and then can change the file name either deliberately or
accidentally and gain access of those file. Because of immutability, you don't
need to worry about those kind of threats. This reason also gel with, Why
String is final in Java, by making java.lang.String final, Java designer
ensured that no one overrides any behavior of String class.
3)Since String is immutable it can safely shared between
many threads ,which is very important for multithreaded programming and to
avoid any synchronization issues in Java, Immutability also makes String
instance thread-safe in Java, means you don't need to synchronize String
operation externally. Another important point to note about String is memory
leak caused by SubString, which is not a thread related issues but something to
be aware of.
4) Another reason of Why String is immutable in Java is to
allow String to cache its hashcode , being immutable String in Java caches its
hashcode, and do not calculate every time we call hashcode method of String,
which makes it very fast as hashmap key to be used in hashmap in Java. In short
because String is immutable, no one can change its contents once created which
guarantees hashCode of String to be same on multiple invocations.
Can abstract class
have constructor in Java?
Yes, abstract class can have constructor in Java. You can
either explicitly provide constructor to abstract class or if you don't,
compiler will add default constructor of no argument in abstract class. This is
true for all classes and it’s also applies on abstract class. For those who
want to recall what is an abstract class in Java, it’s a class which cannot be
instantiated with new() operator or any other ways. In order to use abstract
class in Java, You need to extend it and provide a concrete class. Abstract
class is commonly used to define base class for a type hierarchy with default
implementation, which is applicable to all child classes.
Since abstract class
cannot be instantiated, why abstract class need constructor?
Now if we say we cannot create instance of abstract class
then why do Java adds constructor in abstract class. One of the reason which
make sense is, when any class extend abstract class, constructor of sub class
will invoke constructor of super class either implicitly or explicitly. This
chaining of constructors is one of the reason abstract class can have
constructors in Java.
What is difference
between interface and abstract class in Java?
1) First and major difference between abstract class and
interface is that, abstract class is a class while interface is a interface,
means by extending abstract class you cannot extend another class because Java
does not support multiple inheritance but you can implement multiple interfaces
in Java.
2) Second difference between interface and abstract class in
Java is that you cannot create non abstract method in interface, every method
in interface is by default abstract, but you can create non abstract method in
abstract class. Even a class which doesn't contain any abstract method can be
abstract by using abstract keyword.
3) Third difference between abstract class and interface in
Java is that abstract class are slightly faster than interface because
interface involves a search before calling any overridden method in Java. This
is not a significant difference in most of cases but if you are writing a time
critical application than you may not want to leave any stone unturned.
4) Fourth difference between abstract class vs interface in
Java is that, interface are better suited for Type declaration and
abstract class is more suited for code reuse and evolution perspective.
5) Another notable difference between interface and abstract
class is that when you add a new method in existing interface it breaks all its
implementation and you need to provide an implementation in all clients which
is not good. By using abstract class you can provide default implementation in
super class.
When to use interface
in Java?
Interface is best choice for Type declaration or defining
contract between multiple parties. If multiple programmers are working in
different module of project they still use each other’s API by defining
interface and not waiting for actual implementation to be ready. This brings us
lot of flexibility and speed in terms of coding and development. Use of
Interface also ensures best practices like "programming for interfaces
than implementation" and results in more flexible and maintainable code.
Which two methods are
overridden by an Object, intended to be used as key in HashMap?
A: equals and hashCode
Difference between
wait and sleep in Java?
A: Wait release lock, sleep keeps it
How do you make a
class Immutable in Java?
A: Make it final, final fields without setter, state is only
set in constructor, no leak of internal reference, copy data for mutable
members.
public final class Contacts {
private final String name;
private final String mobile;
public Contacts(String name, String mobile) {
this.name = name;
this.mobile = mobile;
}
public String getName(){
return name;
}
public String getMobile(){
return mobile;
}
}
Which data type you should used to represent currency in Java?
Long or BigDecimal, if you say double, you need to convince
them about rounding and how do you avoid floating point issues.
When to use abstract
class and interface in Java?
Use interface for type declaration, use abstract class if
evolution is concern, for few more points.
Difference between
Overloading and Overriding in Java?
Former take place at compile time, later happens at runtime,
only virtual method can be overridden, static, final and private method can't
be overridden in Java.
What kind of
reference types are exists in Java? Differences?
Strong reference, Weak references, Soft reference and
Phantom reference. Except strong, all other reference allows object to be
garbage collected. For example, if an object hash only weak reference, than
it's eligible for GC, if program needs space
Does Java array is
instance of Object?
Yes, and this is stark difference from array in C/C++,
though it doesn't have any method, it has an attribute called length, which
denotes size of array
Does
List<Number> can hold Integers?
(Yes)
Can we pass ArrayList<Number> to a method which
accepts List<Number> in Java? (Yes)
Can we pass ArrayList<Integer> to a method which
accepts List<Number>? (No) How to fix that? (use wildcards e.g. List<?
extends Number>
What is volatile
variable in Java?
Guarantees happens before relationship, variable's value is
read by main memory
Difference between
CountDownLatch and CyclicBarrier in Java?
Former cannot be reused once count reaches zero, while later
can be reused even after barrier is broken
Does BlockingQueue is
thread-safe?
Yes, take() and put() method of this class guarantees
thread-safety, no need to externally synchronize this class for adding and
retrieving objects
Why wait and notify
method should be called in loop?
To prevent doing task, if condition is not true and thread
is awake due to false alarms, checking conditions in loop ensures that
processing is only done when business logic allows
What is difference
between "abc".equals(unknown string) and
unknown.equals("abc")?
Former is safe from NullPointerException
What is marker or tag
interface in Java?
An interface, which presence means an instruction for JVM or
compiler e.g. Serializable, from Java 5 onwards Annotation is better suited for
this job.
Difference between
Serializable and Externalizable interface in Java?
Later provides more control over serialization process, and
allow you to define custom binary format for your object, later is also suited
for performance sensitive application
Can Enum types implement interface in Java? (Yes)
Can Enum extend class
in Java?
No, because Java allows a class to only extend one class and
enum by default extends java.lang.Enum,
How to prevent your
class from being subclassed?
Make it final or make constructor private
Can we override
Static method in Java? Compilation error?
No, it can only be hidden, no compilation error
Which design pattern
have you used recently?
Give any example except Singleton and MVC e.g. Decorator,
Strategy or Factory pattern)
Difference between
StringBuffer and StringBuilder in Java?
Former is synchronized, and slow, while later is not
synchronized and fast.
How to check if a
thread holds lock on a particular object in Java?
Thread.holdslock() is the best way to figure out whether
thread holds a lock on a particular object or not
Why ArrayList is
declared with List interface List<String> myList = new
ArrayList<String>();
Because if you decide to change it later it's easier:
List<String> myList = new ArrayList<String>();
List<String> myList = new LinkedList<String>();
It's more important in method signatures, when changing what
you return can force everyone using your function to change their code.
Why should we use
BigDecimal in monetary calculation?
public class BigDecimalExample {
public static void
main(String args[]) throws IOException {
//floating point
calculation
double amount1 =
2.15;
double amount2 =
1.10;
System.out.println("difference between 2.15 and 1.0 using double
is: " + (amount1 - amount2));
//Use BigDecimal
for financial calculation
BigDecimal
amount3 = new BigDecimal("2.15");
BigDecimal
amount4 = new BigDecimal("1.10") ;
System.out.println("difference between 2.15 and 1.0 using
BigDecimal is: " + (amount3.subtract(amount4)));
}
}
Output:
difference between 2.15 and 1.0 using double is:
1.0499999999999998
difference between 2.15 and 1.0 using BigDecmial is: 1.05
Don’t use float and double on monetary calculation.
Use BigDecimal, long or int for monetary calculation.
Use BigDecimal with String constructor and avoid double one.
Don’t use floating point result for comparing loop
conditions.
Which two method you
need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must
implements equals and hashcode methods in Java.
How HashMap works in
Java
HashMap works on the principle of Hashing. To understand Hashing, we should understand
the three terms first i.e Hash Function , Hash Value and Bucket.
What is Hash Function,
Hash Value and Bucket ?
hashCode() function
which returns an integer value is the Hash function. The important point
to note that, this method is present in Object class
This is the code for the hash function(also known as hashCode
method) in Object Class:
public native int
hashCode();
The most important point to note from the above line: hashCode method return int value.
So the Hash value is the int value returned by the hash
function.
What is bucket?
A bucket is used to store key value pairs. A bucket can have
multiple key-value pairs. In hash map, bucket used simple LinkedList to store objects.
After understanding the terms we are ready to move next step,
How hash map works in java or How get() works internally in java.
Code inside Java API (HashMap class internal implementation)
for HashMap get(Obejct key) method
1. Public V get(Object key)
{
2. if (key ==null)
3. //Some code
4. int hash =
hash(key.hashCode());
5. // if key found
in hash table then return value
6. // else return null
}
Hash map works on the principle of hashing
HashMap get(Key k) method calls hashCode method on the key
object and applies returned hashValue to its own static hash function to find a
bucket location(backing array) where keys and values are stored in form of a
nested class called Entry (Map.Entry) . So you have concluded that from the
previous line that Both key and value is stored in the bucket as a form of Entry object . So thinking that Only value is
stored in the bucket is not correct and
will not give a good impression on the interviewer .
* Whenever we call get( Key k ) method on the HashMap object . First it
checks that whether key is null or not .
Note that there can only be one null key in HashMap .
If key is null , then Null keys always map to hash 0, thus
index 0.
If key is not null then , it will call hashfunction on the
key object , see line 4 in above method i.e. key.hashCode() ,so after key.hashCode() returns hashValue ,
line 4 looks like
4. int hash = hash(hashValue)
, and now ,it applies
returned hashValue into its own hashing function .
We might wonder why we are calculating the hashvalue again
using hash(hashValue). Answer is ,It defends against poor quality hash
functions.
Now step 4 final
hashvalue is used to find the bucket location at which the Entry object
is stored . Entry object stores in the bucket like this
(hash,key,value,bucketindex) .
Interviewer: What if
when two different keys have the same hashcode ?
Solution, equals() method comes to rescue.
What is Object Class?
Mother of all classes, in other words every other class in
java is the subclass of Object class.
Object class is in the default package i.e. java.lang
package. The Object class defines the basic state and behavior that all objects
must have, such as the ability to compare oneself to another object, to convert
to a string, to wait on a condition variable, to notify other objects that a
condition variable has changed, and to return the object's class. There are 11
methods in Object class .
Access ReturnType Methods
Modifier
-----------------------------------------------------------------------------------
Public boolean * equals(Object obj)
Checks whether the obj object is equal to the object on
which the equals method is called.
Public int * hashCode()
hashCode() is used
for the HashTable. It returns the hash value of the object.
Protected void * finalize()
Public Class<?> * getClass()
It returns the runtime class object.
Protected Object * clone()
It creates and
returns the copy of the object .
Public void * notify()
It will wake up the thread waiting for the objects monitor.
Public void * notifyAll()
It will wakes up all the thread that are waiting for the
objects monitor .
Public String * toString()
It will return the string representation of the object .
Public void * wait()
This method causes the current thread to place itself in the
wait set for this object and then to relinquish any and all synchronization
claims on this object. It releases the lock.
Public void * wait(long timeout)
Public void * wait (long timeout , int nano )
What is immutable
object? Can you write immutable object?
Immutable classes are Java classes whose objects can not be
modified once created. Any modification in Immutable object result in new
object. For example is String is immutable in Java. Mostly Immutable are also
final in Java, in order to prevent sub class from overriding methods in Java
which can compromise Immutability. You can achieve same functionality by making
member as non final but private and not modifying them except in constructor.
What is the
difference between creating String as new() and literal?
When we create string with new() Operator, it’s created in
heap and not added into string pool while String created using literal are
created in String pool itself which exists in PermGen area of heap.
String s = new String("Test");
does not put the
object in String pool , we need to call String.intern() method which is used to
put them into String pool explicitly. its
only when you create String object as String literal e.g. String s =
"Test" Java automatically put that into String pool.
How do you handle
error condition while writing stored
procedure or accessing stored procedure from java?
Stored procedure should return error code if some operation
fails but if stored procedure itself fail than catching SQLException is only
choice.
What is difference
between Executor.submit() and Executer.execute() method
There is a difference when looking at exception handling. If
your tasks throws an exception and if it was submitted with execute this
exception will go to the uncaught exception handler (when you don't have
provided one explicitly, the default one will just print the stack trace to
System.err). If you submitted the task with submit any thrown exception,
checked exception or not, is then part of the task's return status. For a task
that was submitted with submit and that terminates with an exception, the
Future.get will re-throw this exception, wrapped in an ExecutionException.
When do you override
hashcode and equals() ?
Whenever necessary especially if you want to do equality
check or want to use your object as key in HashMap.
What will be the
problem if you don't override hashcode() method ?
You will not be able to recover your object from hash Map if
that is used as key in HashMap.
Is it better to
synchronize critical section of getInstance() method or whole getInstance()
method ?
Answer is critical section because if we lock whole method
than every time some one call this method will have to wait even though we are
not creating any object
Does not overriding
hashcode() method has any performance implication ?
This is a good question and open to all , as per my
knowledge a poor hashcode function will result in frequent collision in HashMap
which eventually increase time for adding an object into Hash Map.
What’s wrong using
HashMap in multithreaded environment? When get() method go to infinite loop ?
Concurrent access and re-sizing
What will happen if
you call return statement or System.exit on try or catch block ? will finally
block execute?
Finally block will execute even if you put return statement
in try block or catch block but finally block won't run if you call System.exit
form try or catch.
What will happen if
we put a key object in a HashMap which is already ther?
If you put the same key again than it will replace the old
mapping because HashMap doesn't allow duplicate keys.
If a method throws
NullPointerException in super class, can we override it with a method which
throws RuntimeException?
You can very well throw super class of RuntimeException in
overridden method but you cannot do same if it is checked Exception.
How do you ensure
that N thread can access N resources without deadlock?
Key point here is order, if you acquire resources in a
particular order and release resources in reverse order you can prevent
deadlock.
What is difference
between CyclicBarrier and CountDownLatch in Java?
Main difference between both of them is that you can reuse
CyclicBarrier even if Barrier is broken but you cannot reuse CountDownLatch in
Java
Happy to found this blog. Good Post!. It was so good to read and useful to improve my knowledge as updated one, keep blogging. Hibernate Training in Electronic City
ReplyDeleteJava Training in Electronic City