Beruflich Dokumente
Kultur Dokumente
Ans: )
1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In
Vector class each method like add(), get(int i) is surrounded with a synchronized
block and thus making Vector class thread-safe.
2) Data growth - Internally, both the ArrayList and Vector hold onto their
contents using an Array. When an element is inserted into an ArrayList or a
Vector, the object will need to expand its internal array if it runs out of room. A
Vector defaults to doubling the size of its array, while the ArrayList increases its
array size by 50 percent.
Q2) How can Arraylist be synchronized without using Vector?
Ans) Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)
Q3) If an Employee class is present and its objects are added in an arrayList. Now I
want the list to be sorted on the basis of the employeeID of Employee class. What
are the steps?
Ans) 1) Implement Comparable interface for the Employee class and override the
compareTo(Object obj) method in which compare the employeeID
2) Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and
override the compare(Object obj, Object obj1) method .
2) Call Collections.sort() on the list and pass comparator as an argument.
Q4)What is difference between HashMap and HashTable?
Ans) Both collections implements Map. Both collections store value as key-value pairs.
The key differences between the two are
1. Hashmap is not synchronized in nature but hshtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the
enumerator for the Hashtable isn't.
Fail-safe - “if the Hashtable is structurally modified at any time after the
iterator is created, in any way except through the iterator's own remove method,
the iterator will throw a ConcurrentModificationException�
3. HashMap permits null values and only one null key, while Hashtable doesn't
allow key or value as null.
Q5) What are the classes implementing List interface?
Ans)
There are three classes that implement List interface:
1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be
increased dynamically also operations like add,remove and get can be formed once the
object is created. It also ensures that the data is retrieved in the manner it was stored. The
ArrayList is not thread-safe.
3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First
In First Out) operation for add operation. It is faster if than ArrayList if it performs
insertion and deletion of elements from the middle of a list.
Q6) Which all classes implement Set interface?
Ans) A Set is a collection that contains no duplicate elements. More formally, sets
contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null
element. HashSet,SortedSet and TreeSet are the commnly used class which implements
Set interface.
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows
the data to be iterated in the ascending order or sorted on the basis of Comparator or
Comparable interface. All elements inserted into the interface must implement
Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides
guaranteed log(n) time cost for the basic operations (add, remove and contains). The class
is not synchronized.
HashSet: This class implements the Set interface, backed by a hash table (actually a
HashMap instance). It makes no guarantees as to the iteration order of the set; in
particular, it does not guarantee that the order will remain constant over time. This class
permits the null element. This class offers constant time performance for the basic
operations (add, remove, contains and size), assuming the hash function disperses the
elements properly among the buckets
Q7) What is difference between List and a Set?
Ans)
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique
elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt
ensures the sequence in which data can be retrieved.(Except HashSet)
Q8) What is difference between Arrays and ArrayList ?
Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that once
array is declared as :
int [] intArray= new int[6];
intArray[7] // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with arrayList the size
is variable.
Once the array is created elements cannot be added or deleted from it. But with
ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray= new int[3][2][1]; // 3 dimensional array
To create an array the size should be known or initalized to some value. If not
initialized carefully there could me memory wastage. But arrayList is all about
dynamic creation and there is no wastage of memory.
Q9) When to use ArrayList or LinkedList ?
Ans) Adding new elements is pretty fast for either type of list. For the ArrayList, doing
random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's
no efficient way to index into the middle of a linked list. When removing elements, using
ArrayList is slow. This is because all remaining elements in the underlying array of
Object instances must be shifted down for each remove operation. But here LinkedList is
fast, because deletion can be done simply by changing a couple of links. So an ArrayList
works best for cases where you're doing random access on the list, and a LinkedList
works better if you're doing a lot of editing in the middle of the list.
Source :
Q10) Consider a scenario. If an ArrayList has to be iterate to read data only, what
are the possible ways and which is the fastest?
Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The first
option is faster than using iterator. Because value stored in arraylist is indexed access. So
while accessing the value is accessed directly as per the index.
Q11) Now another question with respect to above question is if accessing through
iterator is slow then why do we need it and when to use it.
Ans) For loop does not allow the updation in the array(add or remove operation) inside
the loop whereas Iterator does. Also Iterator can be used where there is no clue what type
of collections will be used because all collections have iterator.
Q12) Which design pattern Iterator follows?
Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The
Iterator pattern is one, which allows you to navigate through a collection of data using a
common interface without knowing about the underlying implementation. Iterator should
be implemented as an interface. This allows the user to implement it anyway its easier for
him/her to return data. The benefits of Iterator are about their strength to provide a
common interface for iterating through collections without bothering about underlying
implementation.
Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an
example of the Iterator pattern. It represents and abstract means of iterating over a
collection of elements in some sequential order without the client having to know the
representation of the collection being iterated over. It can be used to provide a uniform
interface for traversing collections of all kinds.
When you override methods, JVM determines the proper methods to call at the program’s
run time, not at the compile time. Overriding occurs when a class method has the same
name and signature as a method in parent class.
Overloading occurs when several methods have same names with
• Same method signature and same number of parameters but of different type
Example of Overloading
int add(int a,int b)
float add(float a,int b)
float add(int a ,float b)
void add(float a)
int add(int a)
void add(int a) //error conflict with the method int add(int a)
Example: Overloading
Class BookDetails{
String title;
String publisher;
float price;
setBook(String title){
}
setBook(String title, String publisher){
}
setBook(String title, String publisher,float price){
}
}
Example: Overriding
class BookDetails{
String title;
setBook(String title){ }
}
class ScienceBook extends BookDetails{
setBook(String title){} //overriding
setBook(String title, String publisher,float price){ } //overloading
}
Q2) What is inheritance?
Ans) Inheritance is the property which allows a Child class to inherit some properties
from its parent class. In Java this is achieved by using extends keyword. Only properties
with access modifier public and protected can be accessed in child class.
public class Parent{
public String parentName;
public int parentage;
public String familyName;
}
public class Child extends Parent{
public String childName;
public int childAge;
public void printMyName(){
System.out.println(“ My name is “+ chidName+” “ +familyName)
}
}
In above example the child has inherit its family name from the parent class just by
inheriting the class.
Q3) What is multiple inheritance and does java support?
Ans) If a child class inherits the property from multiple classes is known as multiple
inheritance.
Java does not allow to extend multiple classes but to overcome this problem it allows to
implement multiple Interfaces.
Q4) What is abstraction?
Ans) Abstraction is way of converting real world objects in terms of class. For example
creating a class Vehicle and injecting properties into it. E.g
public class Vehicle {
public String colour;
public String model;
}
Q5) What is encapsulation?
Ans) The encapsulation is achieved by combining the methods and attribute into a class.
The class acts like a container encapsulating the properties. The users are exposed mainly
public methods.The idea behind is to hide how thinigs work and just exposing the
requests a user can do.
Q6) What is Association?
Ans) Association is a relationship between two classes. In this relationship the object of
one instance perform an action on behalf of the other class. The typical behaviour can be
invoking the method of other class and using the member of the other class.
public class MyMainClass{
public void init(){
new OtherClass.init();
}
}
Q7) What is Aggregation?
Ans) Aggregation has a relationship between two classes. In this relationship the object
of one class is a member of the other class. Aggregation always insists for a direction.
public class MyMainClass{
OtherClass otherClassObj = new OtherClass();
}
Q8) What is Composition?
Ans) Composition is a special type of aggregation relationship with a difference that its
the compulsion for the OtherClass object (in previous example) to exist for the existence
of MyMainClass.
=====================================================================
• A thread of execution.
An instance of Thread is just…an object. Like any other object in Java, it has variables
and methods, and lives and dies on the heap. But a thread of execution is an individual
process (a "lightweight" process) that has its own call stack. In Java, there is one thread
per call stack—or, to think of it in reverse, one call stack per thread. Even if you don't
create any new threads in your program, threads are back there running.
The main() method, that starts the whole ball rolling, runs in one thread, called
(surprisingly) the main thread. If you looked at the main call stack (and you can, any time
you get a stack trace from something that happens after main begins, but not within
another thread), you'd see that main() is the first method on the stack— the method at the
bottom. But as soon as you create a new thread, a new stack materializes and methods
called from that thread run in a call stack that's separate from the main() call stack.
Q2) What is difference between thread and process?
Ans) Differences between threads and processes are:-
1. Threads share the address space of the process that created it; processes have their own
address.
2. Threads have direct access to the data segment of its process; processes have their own
copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use
interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent
process.
6. Threads can exercise considerable control over threads of the same process; processes
can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior
of the other threads of the process; changes to the parent process do not affect child
processes.
Q3) What are the advantages or usage of threads?
Ans)
Threads support concurrent operations. For example,
• Multiple requests by a client on a server can be handled as an individual client thread.
• Long computations or high-latency disk and network operations can be handled in the
background without disturbing foreground computations or screen updates.
• public static void yield() public final void join() throws Interrupted exception
• notify()
• join()
• sleep()
• yield()
Q16) List the methods which when called on the object the thread releases the locks
held on that object?
Ans) wait()
Q17) Does each thread has its own thread stack?
Ans) Yes each thread has its own call stack. For eg
Thread t1 = new Thread();
Thread t2 = new Thread();
Thread t3 = t1;
In the above example t1 and t3 will have the same stack and t2 will have its own
independent stack.
Q18) What is thread starvation?
Ans) In a multi-threaded environment thread starvation occurs if a low priority thread is
not able to run or get a lock on the resoruce because of presence of many high priority
threads. This is mainly possible by setting thread priorities inappropriately.
Q19) What is threadLocal variable?
Ans) ThreadLocal is a class. If a variable is declared as threadLocal then each thread will
have a its own copy of variable and would not interfere with the other's thread copy.
Typical scenario to use this would be giving JDBc connection to each thread so that there
is no conflict.
ThreadLocal class by JAVA API
public class ThreadLocal {
public Object get();
public void set(Object newValue);
public Object initialValue();
}
Implementation of ThreadLocal
public class ConnectionDispenser {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}
===============================================================
==========
Q1) Which part of the memory is involved in Garbage Collection? Stack or Heap?
Ans) Heap
Q2)What is responsiblity of Garbage Collector?
Ans) Garbage collector frees the memory occupied by the unreachable objects during the
java program by deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that
there will be sufficient memory for the program to run.
Q3) Is garbage collector a dameon thread?
Ans) Yes GC is a dameon thread. A dameon thread runs behind the application. It is
started by JVM. The thread stops when all non-dameon threads stop.
Q4)Garbage Collector is controlled by whom?
Ans) The JVM controls the Garbage Collector; it decides when to run the Garbage
Collector. JVM runs the Garbage Collector when it realizes that the memory is running
low, but this behavior of jvm can not be guaranteed.
One can request the Garbage Collection to happen from within the java program but there
is no guarantee that this request will be taken care of by jvm.
Q5) When does an object become eligible for garbage collection?
Ans) An object becomes eligible for Garbage Collection when no live thread can access
it.
Q6) What are the different ways to make an object eligible for Garbage Collection
when it is no longer needed?
Ans)
1. Set all available object references to null once the purpose of creating the object
is served :
str = null;
/*String object referenced by variable str becomes eligible for GC */
}
}
2. Make the reference variable to refer to another object : Decouple the reference
variable from the object and set it refer to another object, so the object which it was
referring to before reassigning is eligible for Garbage Collection.
str1 = str2;
/* Now the str1 variable referes to the String object "Another String" and
the object "Garbage collected after use" is not referred by any variable and
hence is eligible for GC */
}
3) Creating Islands of Isolation : If you have two instance reference variables which
are referring to the instances of the same class, and these two reference variables refer
to each other and the objects referred by these reference variables do not have any
other valid reference then these two objects are said to form an Island of Isolation and
are eligible for Garbage Collection.
public class GCTest3 {
GCTest3 g;
}
Q7) Can the Garbage Collection be forced by any means?
Ans) No. The Garbage Collection can not be forced, though there are few ways by which
it can be requested there is no guarantee that these requests will be taken care of by JVM.
Q8) How can the Garbage Collection be requested?
Ans) There are two ways in which we can request the jvm to execute the Garbage
Collection.
• 1) The methods to perform the garbage collections are present in the Runtime
class provided by java. The Runtime class is a Singleton for each java main
program.
The method getRuntime() returns a singleton instance of the Runtime class. The
method gc() can be invoked using this instance of Runtime to request the garbage
collection.
• 2) Call the System class System.gc() method which will request the jvm to
perform GC.
Q9) What is the purpose of overriding finalize() method?
Ans) The finalize() method should be overridden for an object to include the clean up
code or to dispose of the system resources that should to be done before the object is
garbage collected.
Q10) If an object becomes eligible for Garbage Collection and its finalize() method
has been called and inside this method the object becomes accessible by a live thread
of execution and is not garbage collected. Later at some point the same object
becomes eligible for Garbage collection, will the finalize() method be called again?
Ans) No
Q11) How many times does the garbage collector calls the finalize() method for an
object?
Ans) Only once.
Q12) What happens if an uncaught exception is thrown from during the execution
of the finalize() method of an object?
Ans) The exception will be ignored and the garbage collection (finalization) of that object
terminates.
Q13) What are different ways to call garbage collector?
Ans) Garbage collection can be invoked using System.gc() or
Runtime.getRuntime().gc().
Q14) How to enable/disable call of finalize() method of exit of the application
Ans) Runtime.getRuntime().runFinalizersOnExit(boolean value) . Passing the
boolean value will either disable or enable the finalize() call.
=====================================================
Q16) Once the control switches to the catch block does it return back to the try
block to execute the balance code?
Ans) No. Once the control jumps to the catch block it never returns to the try block but it
goes to finally block(if present).
Q17) Where is the clean up code like release of resources is put in try-catch-finally
block and why?
Ans) The code is put in a finally block because irrespective of try or catch block
execution the control will flow to finally block. Typically finally block contains release
of connections, closing of result set etc.
Q18) Is it valid to have a try block without catch or finally?
Ans) NO. This will result in a compilation error. The try block must be followed by a
catch or a finally block. It is legal to omit the either catch or the finally block but not
both.
e.g. The following code is illegal.
try{
int i =0;
}
int a = 2;
System.out.println(“a = “+a);
Q19) Is it valid to place some code in between try the catch/finally block that follows
it?
Ans) No. There should not be any line of code present between the try and the
catch/finally block. e.g. The following code is wrong.
try{}
String str = “ABC”;
System.out.println(“str = “+str);
catch(Exception e){}
Q20) What happens if the exception is never caught and throws down the method
stack?
Ans) If the exception is not caught by any of the method in the method’s stack till you get
to the main() method, the main method throws that exception and the JVM halts its
execution.
Q21) How do you get the descriptive information about the Exception occurred
during the program execution?
Ans) All the exceptions inherit a method printStackTrace() from the Throwable class.
This method prints the stack trace from where the exception occurred. It prints the most
recently entered method first and continues down, printing the name of each method as it
works its way down the call stack from the top.
Q22) Can you catch more than one exceptions in a single catch block?
Ans)Yes. If the exception class specified in the catch clause has subclasses, any
exception object that is a subclass of the specified Exception class will be caught by that
single catch block.
E.g..
try {
// Some code here that can throw an IOException
}
catch (IOException e) {
e.printStackTrace();
}
The catch block above will catch IOException and all its subclasses e.g.
FileNotFoundException etc.
Q23)Why is not considered as a good practice to write a single catchall handler to
catch all the exceptions?
Ans) You can write a single catch block to handle all the exceptions thrown during the
program execution as follows :
try {
// code that can throw exception of any possible type
}catch (Exception e) {
e.printStackTrace();
}
If you use the Superclass Exception in the catch block then you will not get the valuable
information about each of the exception thrown during the execution, though you can
find out the class of the exception occurred. Also it will reduce the readability of the code
as the programmer will not understand what is the exact reason for putting the try-catch
block.
Q24) What is exception matching?
Ans) Exception matching is the process by which the the jvm finds out the matching
catch block for the exception thrown from the list of catch blocks. When an exception is
thrown, Java will try to find by looking at the available catch clauses in the top down
manner. If it doesn't find one, it will search for a handler for a supertype of the exception.
If it does not find a catch clause that matches a supertype for the exception, then the
exception is propagated down the call stack. This process is called exception matching.
Q25) What happens if the handlers for the most specific exceptions is placed above
the more general exceptions handler?
Ans) Compilation fails. The catch block for handling the most specific exceptions must
always be placed above the catch block written to handle the more general exceptions.
e.g. The code below will not compile.
1 try {
// code that can throw IOException or its subtypes
} catch (IOException e) {
// handles IOExceptions and its subtypes
} catch (FileNotFoundException ex) {
// handle FileNotFoundException only
}
The code below will compile successfully :-
try {
// code that can throw IOException or its subtypes
} catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
} catch (IOException e){
// handle FileNotFoundException only
}
Q26) Does the order of the catch blocks matter if the Exceptions caught by them are
not subtype or supertype of each other?
Ans) No. If the exceptions are siblings in the Exception class’s hierarchy i.e. If one
Exception class is not a subtype or supertype of the other, then the order in which their
handlers(catch clauses) are placed does not matter.
Q27) What happens if a method does not throw an checked Exception directly but
calls a method that does? What does 'Ducking' the exception mean?
Ans) If a method does not throw an checked Exception directly but calls a method that
throws an exception then the calling method must handle the throw exception or declare
the exception in its throws clause. If the calling method does not handle and declares the
exception, the exceptions is passed to the next method in the method stack. This is called
as ducking the exception down the method stack.
e.g. The code below will not compile as the getCar() method has not declared the
CarNotFoundException which is thrown by the getColor () method.
void getCar() {
getColor();
}
void getColor () {
throw new CarNotFoundException();
}
Fix for the above code is
void getCar() throws CarNotFoundException {
getColor();
}
void getColor () {
throw new CarNotFoundException();
}
Q28) Is an empty catch block legal?
Ans) Yes you can leave the catch block without writing any actual code to handle the
exception caught.
e.g. The code below is legal but not appropriate, as in this case you will nt get any
information about the exception thrown.
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
//no code to handle the FileNotFound exception
}
Q29)Can a catch block throw the exception caught by itself?
Ans) Yes. This is called rethrowing of the exception by catch block.
e.g. the catch block below catches the FileNotFound exception and rethrows it again.
void checkEx() throws FileNotFoundException {
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
throw FileNotFound();
}
}
=============================
}
Consider a scenario where Cars can have any number of tyres and other features can also
be different. In this case interface will be created.
Class B{
add(){
// doesnt matter which interface it belong to
}
}
Q7) Can this keyword be assigned null value?
Ans) No
Q8) What are the different types of references in java?
Ans) Java has a more expressive system of reference than most other garbage-collected
programming languages, which allows for special behavior for garbage collection. A
normal reference in Java is known as a strong reference. The java.lang.ref package
defines three other types of references—soft, weak, and phantom references. Each type of
reference is designed for a specific use.
A SoftReference can be used to implement a cache. An object that is not reachable by a
strong reference (that is, not strongly reachable), but is referenced by a soft reference is
called softly reachable. A softly reachable object may be garbage collected at the
discretion of the garbage collector. This generally means that softly reachable objects will
only be garbage collected when free memory is low, but again, it is at the discretion of
the garbage collector. Semantically, a soft reference means "keep this object unless the
memory is needed."
A WeakReference is used to implement weak maps. An object that is not strongly or
softly reachable, but is referenced by a weak reference is called weakly reachable. A
weakly reachable object will be garbage collected during the next collection cycle. This
behavior is used in the class java.util.WeakHashMap. A weak map allows the
programmer to put key/value pairs in the map and not worry about the objects taking up
memory when the key is no longer reachable anywhere else. Another possible application
of weak references is the string intern pool. Semantically, a weak reference means "get
rid of this object when nothing else references it."
A PhantomReference is used to reference objects that have been marked for garbage
collection and have been finalized, but have not yet been reclaimed. An object that is not
strongly, softly or weakly reachable, but is referenced by a phantom reference is called
phantom reachable. This allows for more flexible cleanup than is possible with the
finalization mechanism alone. Semantically, a phantom reference means "this object is no
longer needed and has been finalized in preparation for being collected."
Q9) How to change the heap size of a JVM?
Ans) The old generation's default heap size can be overridden by using the -Xms and
-Xmx switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program
Q10) What is difference between instanceof and isInstance(Object obj)?
Ans) Differences are as follows:
1) instanceof is a reserved word of Java, but isInstance(Object obj) is a method of
java.lang.Class.
if (obj instanceof MyType) {
...
}else if (MyType.class.isInstance(obj)) {
...
}
2) instanceof is used of identify whether the object is type of a particular class or its
subclass but isInstance(obj) is used to identify object of a particular class.
Q11) Java supports pass by value or pass by reference?
Ans) Java supports only pass by value. The arguments passed as a parameter to a method
is mainly primitive data types or objects. For the data type the actual value is passed.
Java passes the references by value just like any other parameter. This means the
references passed to the method are actually copies of the original references.Java copies
and passes the reference by value, not the object. Thus, method manipulation will alter
the objects, since the references point to the original objects.Consider the example:
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
OutPut:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method successfully alters the value of pnt1, even though it is passed by value;
however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the
main() method, pnt1 and pnt2 are nothing more than object references. When you pass
pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any
other parameter. This means the references passed to the method are actually copies of
the original references.
Q12) What is memory leak?
Ans) A memory leak is where an unreferenced object that will never be used again still
hangs around in memory and doesnt get garbage collected.
Q13) What is the difference between equals() and ==?
Ans) == operator is used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object class. The default
implementation uses == operator to compare two objects.
But since the method can be overriden like for String class. equals() method can be used
to compare the values of two objects.
String str1 = "MyName";
String str2 = "MyName";
String str3 = str2;
if(str1 == str2){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str1.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
Output:
Objects are not equal
Objects are equal
if(str2 == str3){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
if(str3.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}
OutPut:
Objects are equal
Objects are equal
Q14) How to make sure that Childclass method actually overrides the method of the
superclass?
Ans) The @Override annotation can be added to the javadoc for the new method. If you
accidently miss an argument or capitalize the method name wrong, the compiler will
generate a compile-time error.
Q15) How to find the size of an object?
Ans)The heap size of an object can be found using -
Runtime.totalMemory()-Runtime.freeMemory() .
Q16) Can an abstract class have a static method?
Ans) Yes an abstract class have a static method and it can be accessed by any other
class(even not a concrete class).
Q17) Can an abstract class have a constructor?
Ans) Yes an abstract class have a default and parameterized constructors.
Q18) Why static methods cannot access non static variables or methods?
Ans) A static method cannot access non static variables or methods because static
methods doesnt need the object to be accessed. So if a static method has non static
variables or non static methods which has instantiated variables they will no be intialized
since the object is not created and this could result in an error.
Q19) What is difference between stringbuffer and stringbuilder?
Ans) The only difference between StringBuffer and StringBuilder is that StringBuilder is
unsynchronized whereas StringBuffer is synchronized. 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.
1)If your text can change and will only be accessed from a single thread, use a
StringBuilder 2)because StringBuilder is unsynchronized.
If your text can changes, and will be accessed from multiple threads, use a StringBuffer
because StringBuffer is synchronous.
Q20) Consider a scenario in which the admin want to sure that if some one has
written System.exit() at some part of application then before system shutdown all
the resources should be released. How is it possible?
Ans) This is possible using Runtime.getRuntime().addShutdownHook(Thread hook).
The Java virtual machine shuts down in response to two kinds of events:
1. The program exits normally, when the last non-daemon thread exits or when the
exit (equivalently, System.exit) method is invoked, or
2. The virtual machine is terminated in response to a user interrupt, such as typing ^C,
or a system-wide event, such as user logoff or system shutdown.
A shutdown hook is simply an initialized but unstarted thread. When the virtual machine
begins its shutdown sequence it will start all registered shutdown hooks in some
unspecified order and let them run concurrently. When all the hooks have finished it will
then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the
virtual machine will halt. Note that daemon threads will continue to run during the
shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking
the exit method.
Once the shutdown sequence has begun it can be stopped only by invoking the halt
method, which forcibly terminates the virtual machine.
Q21) What is the difference between final, finally and finalize() in Java?
Ans)
final - constant declaration. A final variable act as constant, a final class is immutable
and a final method cannot be ovrriden.
finally - handles exception. The finally block is optional and provides a mechanism to
clean up regardless of what happens within the try block (except System.exit(0) call). Use
the finally block to close files or to release other system resources like database
connections, statements etc.
finalize() - method helps in garbage collection. A method that is invoked before an object
is discarded by the garbage collector, allowing it to clean up its state. Should not be used
to release non-memory resources like file handles, sockets, database connections etc
because Java has only a finite number of these resources and you do not know when the
garbage collection is going to kick in to release these non-memory resources through the
finalize() method.
Q22) How does Java allocate stack and heap memory?
Ans) Each time an object is created in Java it goes into the area of memory known as
heap. The primitive variables like int and double are allocated in the stack, if they are
local method variables and in the heap if they are member variables (i.e. fields of a
class). In Java methods local variables are pushed into stack when a method is invoked
and stack pointer is decremented when a method call is completed.
In a multi-threaded application each thread will have its own stack but will share the
same heap. This is why care should be taken in your code to avoid any concurrent access
issues in the heap space. The stack is threadsafe (each thread will have its own stack) but
the heap is not threadsafe unless guarded with synchronisation through your code.
Q23) Explain re-entrant, recursive and idempotent methods/functions?
Ans) A method in stack is re-entrant allowing multiple concurrent invocations that do
not interfere with each other.
A function is recursive if it calls itself. Given enough stack space, recursive method calls
are perfectly valid in Java though it is tough to debug. Recursive functions are useful in
removing iterations from many sorts of algorithms. Allrecursive functions are re-entrant
but not all re-entrant functions are recursive. Idempotent methods are methods, which
are written in such a way that repeated calls to the same method with the same arguments
yield same results. For example clustered EJBs, which are written with idempotent
methods, can automatically recover from a server failure as long as it can reach another
server.
Q24)Can a private variable or method of a class can be accessed?
Ans) Yes its possible using reflection.
Q25)What is difference between static block and the init block?
Or
Difference between
Static {} and {}
Ans) The static block is loaded when the class is loaded by the JVM for the 1st time only
whereas init {} block is loaded every time class is loaded. Also first the static block is
loaded then the init block.
static{
System.out.println("Inside static");
}
{
System.out.println("Inside init");
}
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks();
}
}
Output:
Inside static
Inside init
Inside init
Inside init
Q26)Why inner class can access only final variable?
Ans) Local classes can most definitely reference instance variables. The reason they
cannot reference non final local variables is because the local class instance can remain in
memory after the method returns. When the method returns the local variables go out of
scope, so a copy of them is needed. If the variables weren't final then the copy of the
variable in the method could change, while the copy in the local class didn't, so they'd be
out of synch.
Anonymous inner classes require final variables because of the way they are
implemented in Java. An anonymous inner class (AIC) uses local variables by creating a
private instance field which holds a copy of the value of the local variable. The inner
class isn't actually using the local variable, but a copy. It should be fairly obvious at this
point that a "Bad Thing"â„¢ can happen if either the original value or the copied value
changes; there will be some unexpected data synchronization problems. In order to
prevent this kind of problem, Java requires you to mark local variables that will be used
by the AIC as final (i.e., unchangeable). This guarantees that the inner class' copies of
local variables will always match the actual values.
Q27)What is fully abstract class?
Ans) An abstract class which has all methods as abstract and all fields are public static
final.
Q28)What is dynamic binding and static binding?
Ans) Method invocation
The Java programming language provides two basic kinds of methods: instance methods
and class (or static) methods. The difference are:
1. Instance methods require an instance before they can be invoked, whereas class
methods do not.
2. Instance methods use dynamic (late) binding, whereas class methods use static
(early) binding.
When the Java virtual machine invokes a class method, it selects the method to invoke
based on the type of the object reference, which is always known at compile-time. On the
other hand, when the virtual machine invokes an instance method, it selects the method to
invoke based on the actual class of the object, which may only be known at run time.
Q29) What is Java Reflection?
Ans)Reflection is commonly used by programs which require the ability to examine or
modify the runtime behavior of applications running in the Java virtual machine.
Drawbacks of Reflection: Reflection is powerful, but should not be used
indiscriminately. If it is possible to perform an operation without using reflection, then it
is preferable to avoid using it. The following concerns should be kept in mind when
accessing code via reflection.
Performance Overhead: Because reflection involves types that are dynamically
resolved, certain Java virtual machine optimizations can not be performed. Consequently,
reflective operations have slower performance than their non-reflective counterparts, and
should be avoided in sections of code which are called frequently in performance-
sensitive applications.
Security Restrictions: Reflection requires a runtime permission which may not be
present when running under a security manager. This is in an important consideration for
code which has to run in a restricted security context, such as in an Applet.
Exposure of Internals: Since reflection allows code to perform operations that would be
illegal in non-reflective code, such as accessing private fields and methods, the use of
reflection can result in unexpected side-effects, which may render code dysfunctional and
may destroy portability. Reflective code breaks abstractions and therefore may change
behavior with upgrades of the platform.
Q30) When an obj is passed through a function , one can set the properties but
cannot set a new memory location?
Ans) It is because when u pass an object the address value is passed and stored in some
new address . like if address 1234 is passed , it is stored in 4567 location. So if u change
in the value of an object it will take the address from 4567 and do 1234.setXXX(). If u set
the object to null it will set 4567=null.