Professional Documents
Culture Documents
Garbage Collection
Multithreading
Object oriented
Path and Classpath are operating system level environment variables. Path is used define
where :.class files.
2. Which part of JVM will allocate the memory for a java program?
Class loader subsystem of JVM will allocate the necessary memory needed by the java program.
a) In procedural program, programming logic follows certain procedures and the instructions are
executed one after another. In OOP program, unit of program is object, which is nothing but
combination of data and code.
b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is
accessible within the object and which in turn assures the security of the code
Lakven Technologies
5. What is Object?
A Java object is a set of data combined with methods for manipulating that data. An object is
made from a class; a class is the blueprint for the object.
Each object made from a class will have its own values for the instance variables of that class.
Instance variables are things an object knows about itself.
Object Declaration
Object Instantiation
Object Initialization
Object Declaration
Object Instantiation
Instantiating an object allocated space in memory for the object. This is accomplished with the
new operator.
Object Initialization
Initializing an object fills the objects variables with an initial set of values. This is accomplished
using a constructor.
6. What is class?
A class is a group of variables and methods. In java class contains the logic to execute some task.
7. Explain the reason for each keyword of public static void main (String args[])?
public- main (..) is the first method called by java environment when a program is executed so it
has to accessible from java environment. Hence the access specifier has to be public.
Static: Java environment should be able to call this method without creating an instance of the
class, so this method must be declared as static.
Lakven Technologies
void: main does not return anything so the return type must be void
String args [] : The argument String indicates the argument type which is given at the command
line and arg is an array for string given during command line.
8. What if the static modifier is removed from the signature of the main method?
What if I do not provide the String array as the argument to the method?
The program compiles properly but at runtime it will give "Main method not public." message.
12. What are the oops concepts in java, explain with real-time examples?
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphisam
In Remote there is number format, power buttons and other buttons. We can see the
buttons and we cannot see the button circuits, i.e buttons circuits and wirings all are
hidden.
Encapsulation:
Lakven Technologies
Writing Operations and methods stored in a single Unit is called Encapsulation. This
keeps the data safe from outside interface and misuse
Capsule is the best real time example for it. In it we will have two types of drugs
combined as single capsule.
Polymorphism:
Example: Person
13. What is the access specifies in java and explain those accessibility?
Public- public classes, methods, and fields can be accessed from everywhere.
Protected- protected methods and fields can only be accessed within the same class to
which the methods and fields belong, within its subclasses, and within classes of the same
package.
Default(no specifier)- If you do not set access to specific level, then such a class, method, or
field will be accessible from inside the same package to which the class, method, or field
belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class to which the
methods and fields belong. Private methods and fields are not visible within subclasses and
are not inherited by subclasses.
Accessible to class
yes yes yes no
from same package?
Lakven Technologies
from different package?
14. What is constructor?
A constructor is a special method whose task is to initialize the object of its class. It is special
because its name is the same as the class name. They do not have return types, not even void
and therefore they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor. Constructor
is invoked whenever an object of its associated class is created.
If a class defined by the code does not have any constructor, compiler will automatically provide
one no-parameter-constructor (default-constructor) for the class in the byte code. The access
modifier (public/private/etc.) of the default constructor is the same as the class itself.
Writing more than one method in a class with the same name is called overloading.
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)
In the overloading the return type can be same, but the parameters should be changed.
Writing the method in subclass which is already existing in super class is called overriding.
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 the nothing but static polymorphism. Overriding is nothing but dynamic
polymorphism.
Lakven Technologies
Whenever we are overriding the method which throws exception in super class, in subclass we
need to throw the same exception or we can throw the subclass of the super class exception.
But we cannot throw the super class of the super class method’s exception.
20. What the access specifier’s hierarchy when you override method?
Whenever we are overriding the method the subclass method’s access specifier should be same
as super class’s method or it can be it can be higher level access specified.
That means in overriding we can increase the visibility of method but we cannot decrease the
visibility.
21. When is static variable loaded? Is it at compile time or runtime? When exactly a static block is
loaded in Java?
Static variable are loaded when class loader brings the class to the JVM. It is not necessary that
an object has to be created. Static variables will be allocated memory space when they have
been loaded. The code in a static block is loaded/executed only once i.e. when the class is first
initialized. A class can have any number of static blocks. Static block is not member of a class,
they do not have a return statement and they cannot be called directly. Cannot contain this or
super. They are primarily used to initialize static fields.
Static variables are class level variables where all objects of the class refer to the same variable.
If one object changes the value then the change gets reflected in all the objects.
Static variables: the variable which defined with static keyword is called static variable.
If we create n number of objects to the class, only one copy of the memory will be allocated.
Static methods: the method which defined with static keyword is called static method. Static
methods will be loaded by jvm at the class loading time.
Static blocks will be executed by JVM before executing the main method. static lock looks like as
below
static {
// some statements
Lakven Technologies
}
Static classes: Top level classes cannot be static classes and inner classes can be static classes.
We cannot call or access the not static members in the static methods.
If we have static variables or methods, by using this and super we cannot access these variables
or methods. The reason is that static variable and methods are for class and loaded at class
loading time, but the this and super is for the object.
The instance block will be executed after creating the object for the class.
25. What are the differences between Class / static Methods and Instance Methods?
Class methods can only operate on class members Instance methods of the class can also not be called
and not on instance members as class methods are from within a class method unless they are being
unaware of instance members. called on an instance of that class.
Lakven Technologies
super is a keyword which is used to access the method or member variables from the
superclass. If a method hides one of the member variables in its superclass, the method can
refer to the hidden variable through the use of the super keyword. In the same way, if a method
overrides one of the methods in its superclass, the method can invoke the overridden method
through the use of the super keyword.
Note:
Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine
plays the central role in this concept.
The JVM is the environment in which Java programs execute. It is a software that is
implemented on top of real hardware and operating system.
When the source code (.java files) is compiled, it is translated into byte codes and then placed
into (.class) files. The JVM executes these byte codes. So Java byte codes can be thought of as
the machine language of the JVM.
A JVM can either interpret the byte code one instruction at a time or the byte code can be
compiled further for the real microprocessor using what is called a just-in-time compiler. The
JVM must be implemented on a particular platform before compiled programs can run on that
platform.
30. What is call by value and call by reference, whether the java uses call by value or call by
reference?
Pass by reference means, passing the address itself rather than passing the value. Pass by value
means passing a copy of the value. Java uses the pass by value instead of reference.
finalize () method is used to clean up the unused references of the objects, then JVM executes
Garbage collection to clean up the memory.
Lakven Technologies
Finalize () method is the method of Object class. The syntax is as follows
protected void finalize () throws Throwable
{
}
32. What is the garbage collection?
The process of reclaiming the memory from the un used objects is called Garbage collection.
Garbage collection is the automatic process which Is called by JVM.
We cannot force the JVM to call Garbage collection, but we can suggest the JVM to call GC by
using the System.gc () or Runtime.gc(). But JVM does not give guarantee.
33. Can we force JVM for garbage collection?
We cannot force the JVM to call Garbage collection, but we can suggest the JVM to call GC by
using the System.gc() or Runtime.gc(). But JVM does not give guarantee.
34. Which algorithm is used by garbage collector to remove the unused variables or objects from
memory?
Garbage collector uses many algorithems but the most commonly used algorithm is
mark andsweep
35. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any
cleanup processing before the object is garbage collected
X =20; // gives error saying that final value can not be changed
}
}
Final methods:
Once we have defined the final method, we cannot override that method in subclass.
Ex:
Lakven Technologies
final int X =10;
final int m1() {
return X;
}
int m1() // gives the error, saying that we can not override fina method
{
return 100;
}
}
We can’t create the object for the abstract class. But we can create the reference variable to it.
1. We have to extend the abstract class form any other class. (if no class is extending then
there is no use of defining abstract class)
2. If any class is extending the abstract class, then we have to provide the body for the abstract
methods in the sub class. Incase if we are not proving the body, then the subclass will also
becomes abstart class.
Advantage of the abstract class is that subclass can implement the method body as per his
requirement.
Ex: Let us assume a father (Base Class), he has some Land (Member Function), and he has not
done anything with it.
(Implementation) in it... As his Child (Derived Class), he Takes the Land(Member Function) from
the Father(Base) and does Agriculture(implementing the M.F. of Parent Class) in the Child...
Lakven Technologies
Abstract method ends with semicolon.
Ex: void m1();
39. Can we apply final keyword abstract class?
No we cannot apply final keyword for abstract class. A final class means we cannot extend that
class.
But if you declare abstract class, you have to extend that class by another class; otherwise there
is no use with abstract class.
So we can not apply final class for abstract class.
1. We have to implement the interface form any other class. (if no class is implementing then
there is no use of defining interface)
2. If any class is implementing the interface, then we have to provide the body for the abstract
methods in the implementing class. Incase if we are not proving the body, then the subclass
will becomes abstract class.
41. What is similarities/difference between an Abstract class and Interface?
Differences are as follows:
• Interfaces provide a form of multiple inheritance. A class can extend only one other
class.
• Interfaces are limited to public methods and constants with no implementation.
Abstract classes can have a partial implementation, protected parts, static methods,etc.
• A Class may implement several interfaces. But in case of abstract class, a class may
extend only one abstract class.
• Interfaces are slow as it requires extra indirection to to find corresponding method in
the actual class. Abstract classes are fast.
Similarities:
• Neither Abstract classes or Interface can be instantiated.
42. When should I use abstract classes and when should I use interfaces?
Lakven Technologies
If various implementations only share method signatures then it is better to use
Interfaces.
you need some classes to use some methods which you don't want to be included in the
class, then you go for the interface, which makes it easy to just implement and make use
of the methods defined in the interface.
If various implementations are of the same kind and use common behavior or status
then abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the
implementation task with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They're
also a good choice for nonleaf classes in class hierarchies
Java Doesnot support multiple inheritance because of Diamond problem, consider a class A
has foo() method and then B and C derived from A and has there own foo() implementation
and now class D derive from B and C using multiple inheritance and if we refer just foo()
compiler will not be able to decide which foo() it should invoke. This is also called Diamond
problem because structure on this inheritance scenario is similar to 4 edge diamond, see
below
A foo()
/ \
/ \
foo() B C foo()
\ /
\ /
D
foo()
Implicit casting is the process of simply assigning one entity to another without any
transformation guidance to the compiler. This type of casting is not permitted in all kinds of
transformations and may not work for all scenarios.
int i = 1000;
Lakven Technologies
Explicit casting in the process in which the complier are specifically informed to about
transforming the object.
long i = 700.20;
A constructor is a member function of a class that is used to create objects of that class, invoked
using the new operator. It has the same name as the class and has no return type. They are only
called once, whereas member functions can be called many times. A method is an ordinary
member function of a class. It has its own name, a return type (which may be void), and is
invoked using the dot operator. Constructor will be automatically invoked when an object is
created whereas method has to be called explicitly.
super.method() is used to call a super class method from a sub class. To call a constructor of the
super class, we use the super(); statement as the first line of the subclass’s constructor.
Lakven Technologies
* Runtime.freeMemory() --> Returns JVM Free Memory
* Runtime.maxMemory() --> Returns the maximum amount of memory that the JVM will
attempt to use. It also helps to run the garbage collector
* Runtime.gc
51. What is an inner class?
Inner class is a class defined inside other class and act like a member of the enclosing class
52. How to access the inner class from code within the outer class?
The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
Inner in = new Inner();
System.out.println(“No Of Inner classes is : “+ in.getNoOfClassesFromOuter());
}
class Inner{
Here the method getNoOfInnerClasses() is called on the outer class’s instance through this outer
class instance the inner class instance in is created.
53. How to create an inner class instance from outside the outer class instance code?
To create an instance of the inner class you must have the instance of its enclosing class.
class EnclosingOuter {
class Inner{ }
}
To create the instance of inner class from class other than the enclosing class.
1) class OtherThanOuter{
EnclosingOuter out = new EnclosingOuter();
EnclosingOuter.Inner in = out.new Inner();
}
2) class OtherThanOuter{
EnclosingOuter.Inner out = new EnclosingOuter.Inner ();
54. Can Abstract Class have constructors? Can interfaces have constructors?
Lakven Technologies
Abstract class's can have a constructor, but you cannot access it through the object, since you
cannot instantiate abstract class. To access the constructor create a sub class and extend the
abstract class which is having the constructor.
Example
public abstract class AbstractExample {
public AbstractExample(){
System.out.println("In AbstractExample()");
}
}
Return statement is used inside a method to come out of it. System.exit( 0) is used in any
method to come of the program.
SHALLOW Cloning just allows cloning the object but not sub objects.
For ex, object of address contains street and city. To clone it, set references to the street
and city objects.
DEEP Cloning clones the objects as well as sub objects.
For example, a car has four wheels. To clone a car, four wheels must be cloned.
That distinction is better understood in terms of databases.
You need deep Cloning, if the entity requires "cascade deleting". You need shallow Cloning if
"cascade deleting" is not needed.
Lakven Technologies
Inside the method, your first action must be super.clone().
Classes that want to allow CLONING must implement the marker interface Cloneable.
Singleton is a design pattern meant to provide one and only one instance of an object. Other
objects can get a reference to this instance through a static method (class constructor is
kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to
create a single instance of a given class. This has advantages in memory management, and
for Java, in garbage collection. Moreover, restricting the number of instances may be
necessary or desirable for technological or business reasons--for example, we may only
want a single instance of a pool of database connections.
63. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
Lakven Technologies
A string is s character array.
A String is a final class. String class is the part of java.lang package.
String is immutable. Once it is defined we cannot change the value of string without assigning to
another object.
String s = "Hello";
s.concat("world");
System.out.println(s);-> will print Hello only.
StringBuffer s = "Hello";
s.append(" world");
System.out.println(s);-> prints Hello World.
String objects are immutable whereas StringBuffer objects are not. StringBuffer support
growable and modifiable strings but String does not support.
String is immutable whereas StringBuffer and StringBuilder can change their values.
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 is not going to change use a string Class because a String object is
immutable.
2. If your text can change and will only be accessed from a single thread, use a
StringBuilder because StringBuilder is unsynchronized.
3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer
because StringBuffer is synchronous
68. In how many ways we can create String Objects and what are they and explain?
Lakven Technologies
2. Using new operator
String s = “lakven”;
String s1 = “lakven”
In the constant pooling mechanism, once the String is created JVM creates the one reference id
for the string.
When the second String is creating, jvm first checks whether the string is available in memory (in
constant pool) and if it is available JVM refers the same reference id and it will not create new
one. As it is referring the same reference, the memory will be saved.
In the above example both the string s and s1 refers the same memory location.
If you create the Strings by using new operator, for each and every string JVM creates
one new memory location even though the String contents are same.
Note: Creating strings as literals instead of creating String objects using 'new' key word
whenever possible
69. Give some method names in String and explain with example?
The following program explains the usage of the some of the basic String methods like;
1. compareTo(String anotherString)
Compares two strings lexicographically.
2. charAt(int index)
Returns the character at the specified index.
4. length()
Returns the length of this string.
5. equals(Object anObject)
Compares this string to the specified object.
Lakven Technologies
6. equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
7. toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default
locale.
7. toLowerCase()
Converts all of the characters in this String to upper case using the rules of the default
locale.
9. concat(String str)
Concatenates the specified string to the end of this string.
Returns the index within this string of the first occurrence of the specified character.
Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.
Returns the index within this string of the first occurrence of the specified substring.
Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.
Returns the index within this string of the last occurrence of the specified character.
Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.
Returns the index within this string of the rightmost occurrence of the specified
substring.
Lakven Technologies
Returns the index within this string of the last occurrence of the specified substring,
searching backward starting at the specified index.
Returns a new string resulting from replacing all occurrences of oldChar in this string
with newChar.
21. trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
70. Which method of String is used to find whether the part of string is exists in the string or not?
We can use the indexOf() method to check whether the string is available or not.
If the specified character or the string is found in the String, then the position will be returned.
If it is not found it returns the -1.
71. What is the difference between and == and equals method.
The == operator compares two objects to determine if they are the same object in memory i.e.
present in the same memory location. It is possible for two String objects to have the same
value, but located in different areas of memory.
== Compares references while .equals compares contents. For two String objects, value
equality means that they contain the same character sequence. For the Wrapper classes,
value equality means that the primitive values are equal.
String s1 = "lakven";
String s2 = s1;
String s5 = " lakven ";
String s3 = new String("lakven ");
String s4 = new String("lakven ");
System.out.println("== comparison : " + (s1 == s5));
System.out.println("== comparison : " + (s1 == s2));
System.out.println("Using equals method : " + s1.equals(s2));
Lakven Technologies
System.out.println("== comparison : " + s3 == s4);
System.out.println("Using equals method : " + s3.equals(s4));
}
}
lastIndexOf(String s) returns the last index position of the first occurance of the String
Exception Handling
75. What is an exception?
An exception is an abnormal condition that arises in a code sequence at run time
Lakven Technologies
77. What is an error?
Errors are irrecoverable exceptions, usually a program terminates when an error is encountered.
78. Difference between Exception and Error?
Errors are irrecoverable exceptions. Exceptions we can handle using the try catch block.
A checked exception is some subclass of Exception (or Exception itself), excluding class
RuntimeException and its subclasses. Making an exception checked forces client programmers
to deal with the exception may be thrown. Checked exceptions must be caught at compile time.
Example: IOException.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its
subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't
force client programmers either to catch the exception or declare it in a throws clause. In fact,
client programmers may not even know that the exception could be thrown.
Lakven Technologies
82. Can we write finally without catch and vice versa?
Yes, we can write finally without catch as well as catch without finally for try block.
But try should have either catch or finally.
Yes we can write as many try blocks inside try block as long as it is following catch or finally.
Try {
// some code
}
Catch(ExceptionClass y) {
// some code
}
Finally{
//this code will be executed whether or not an exception
//is thrown or caught
}
User defined Exceptions are custom Exception classes defined by the user for specific purpose. A
user defined exception can be created by simply sub-classing an Exception class or a subclass of
an Exception class. This allows custom exceptions to be generated (using throw clause) and
Lakven Technologies
caught in the same way as normal exceptions.
Example:
When an object is not initialized, the default value is null. When the following things happen,
the NullPointerException is thrown:
NullPointerException is a runtime exception. The best practice is to catch such exception even if
it is not required by language design.
IO Streams
89. What is Serialization and deserialization?
Serializable is a marker interface. When an object has to be transferred over a network
( typically through rmi or EJB) or persist the state of an object to a file, the object Class needs
to implement Serializable interface. Implementing this interface will allow the object converted
into bytestream and transfer over a network.
The process of reconstructing the Object from the Bytestream is called deserialization.
91. How to make a class or a bean serializable? How do I serialize an object to a file?
An object must implement the Serializable or Externalizable interface before it can be written to
a stream as an object. The class whose instances are to be serialized should implement an
Lakven Technologies
interface Serializable. Then you pass the instance to the ObjectOutputStream which is
connected to a fileoutputstream. This will save the object to a file.
93. What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream classhierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/
OutputStream class hierarchy is byte-oriented.
When you use Serializable interface, your class is serialized automatically by default. But you can
override writeObject() and readObject() two methods to control more complex object
serailization process. When you use Externalizable interface, you have a complete control over
your class's serialization process.
Multithreading
95. What is thread?
Thread is a small program which does some task.
96. What is the difference between process and thread?
Lakven Technologies
1) Extend the Thread class and override the run() method in your class. Create an instance of the
subclass and invoke the start() method on it, which will create a new thread of execution. e.g.
public class NewThread extends Thread{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
c.start();
}}
2)Implements the Runnable interface.The class will have to implement the run() method in the
Runnable interface. Create an instance of this class. Pass the reference of this instance to the
Thread constructor a new thread of execution will be created. e.g. class
public class NewThread implements Runnable{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}
Lakven Technologies
1) New – When a thread is instantiated it is in New state until the start() method is called on the
thread instance. In this state the thread is not considered to be alive.
2) Runnable – The thread enters into this state after the start method is called in the thread
instance. The thread may enter into the Runnable state from Running state. In this state the
thread is considered to be alive.
3) Running – When the thread scheduler picks up the thread from the Runnable thread’s pool,
the thread starts running and the thread is said to be in Running state.
4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable.
The thread switches to this state because of reasons like wait method called or sleep method
has been called on the running thread or thread might be waiting for some i/o resource so
blocked.
5) Dead – When the thread finishes its execution i.e. the run() method execution completes, it
is said to be in dead state. A dead state can not be started again. If a start() method is invoked
on a dead thread a runtime exception will occur.
2. What is the purpose of the wait (), notify (), and notifyAll() methods?
Wait(): whenever the wait() is called on the particular thread, that thread will be in waiting state
and cannot come to running state till the notify() is called.
notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first.
3. What is deadlock?
When two threads are waiting for each other and can’t proceed until the first thread obtains a
lock on the other thread or vice versa, the program is said to be in a deadlock.
4. What’s the difference between the methods sleep () and wait ()?
When the sleep () method calls the thread will sleep for specified time period.
Ex: sleep (1000), puts the thread aside for exactly one second.
When the sleep () method calls the thread will sleep for specified time period. But it can come to
running state before the specified time when the notify () method is called. The method wait ()
is defined in the Object and the method sleep() is defined in the class Thread.
Every thread has a priority, the higher priority thread gets preference over the lower priority
thread by the thread scheduler
Lakven Technologies
Synchronized keyword provides a lock on the object.
We can apply Synchronized keyword for methods, blocks and static methods.
When we apply the synchronized keyword for the static method, then the class will be locked.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
7. What is daemon thread and which method is used to create the daemon thread?
Daemon threads are threads with low priority and runs in the back ground doing the garbage
collection operation for the java runtime system.
The setDaemon() method is used to create a daemon thread. These threads run without the
intervention of the user. To determine if a thread is a daemon thread, use the accessor method
isDaemon().
Synchronized blocks place locks for shorter periods than synchronized methods.
Answer: when we add a synchronized keyword to the block or the method, the object will be
locked.
When object is locked at a time only one thread can access the method or block.
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. When we
add the synchronized keyword for the static method, the class will be locked.
A static method can be synchronized. If you do so, the JVM will obtain a lock on the
java.lang.Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) { }
Lakven Technologies
Collections Framework
12. What is collection API?
The Collections API is a set of classes and interfaces that support operations on collections of
objects.
A collection represents a group of objects, known as its elements. This framework is provided in
the java.util package. Objects can be stored, retrieved, and manipulated as elements of
collections.
Collection API Reduces programming efforts, Increases program speed and quality
Collections
Arrays
1. Arrays r fixed in size and hence once we created 1. Collections are growable in nature and hence
an array we are not allowed to increase or decrease based on our requirement we can increase or
the size based on our requirement. decrease the size.
2. Memory point of view arrays are not 2. Memory point of view collections are
recommended to use recommended to use.
3. Performance point of view arrays are 3. Performance point of view collections are not
recommended to use recommended to use.
4. Arrays can hold only homogeneous elements 4. Collections can hold both homogeneous and
heterogeneous elements.
5. Arrays can hold both primitives as well as objects 5. Collections can hold only objects.
6. For any requirement, there is no ready method 6. For every requirement ready made method
support compulsory programmer has to code support is available. Being a programmer we have to
explicitly. know how to use those methods and we are not
responsible to implement those.
Lakven Technologies
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a
remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it
has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate
the objects also like adding and removing the objects.
16. Difference between Vector and ArrayList? What is the Vector class?
ArrayList Vector
The ArrayList increases its array size by 50 percent if it A Vector defaults to doubling the size of its array if it runs
runs out of room. out of room
ArrayList has no default size. While vector has a default size of 10.
17. What is the difference b/w Iterator and ListIterator?
18. Where will you use Vector and where will you use ArrayList?
The basic difference between a Vector and an ArrayList is that, vector is synchronized while
ArrayList is not.
Whenever there is a possibility of multiple threads accessing the same instance, one should use
Vector.
While if not multiple threads are going to access the same instance then use Array List. Non
synchronized data structure will give better performance than the synchronized one.
List interface is a child interface of Collection interface. This can be used to represent group of
individual objects in as a single entity where
Lakven Technologies
Duplicates are allowed
Insertion order is preserved
Set is a child interface of Collection interface. it can be used to represent a group of individual
objects as a single entity where
Remember it is not a child Interface of Collection Interface and hence Map and Collection
Interfaces doesn’t have any relationship.
Collection is an interface which can be used for representing a group of individual objects as
single entity and it acts as root interface of collection frame work.
A collection is utility class to define several utility methods for Collection implemented class
objects.
Lakven Technologies
24. Difference between HashMap and HashTable? Can we make hashmap synchronized?
1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and
permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow
nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
Map m = Collections.synchronizeMap(hashMap);
25. What is the difference between ArrayList and LinkedList? (ArrayList vs LinkedList.)
1. ArrayList uses primitive object array for storing objects whereas LinkedList is made up of a
chain of nodes. Each node stores an element and the pointer to the next node. A singly
linked list only has pointers to next. A doubly linked list has a pointer to the next and the
previous element. This makes walking the list backward easier.
2. ArrayList implements the RandomAccess interface, and LinkedList does not. ArrayList is
much faster than a Linked List for random access, that is, when accessing arbitrary list
elements using the get method.
3. Adding and deleting at the start and middle of the ArrayList is slow, because all the later
elements have to be copied forward or backward. (Using System.arrayCopy()) Whereas
Linked lists are faster for inserts and deletes anywhere in the list, since all you do is update a
few next and previous pointers of a node.
4. Each element of a linked list (especially a doubly linked list) uses a bit more memory than its
equivalent in array list, due to the need for next and previous pointers.
26. If we are trying to insert duplicate values in Set what will happen?
If we are trying to insert duplicate objects to the HashSet , we wont get any compile time or run
time errors just the add(Object o) returns false and it doesn’t add that object.
Set stores elements in an unordered way but does not contain duplicate elements, whereas List
stores elements in an ordered way but may contain duplicate elements.
When we required uniqueness then we can use set and setdoes not allow any duplications but
list may contain duplications set and list both extends collection interface.
Lakven Technologies
28. Why is it preferred to declare: List<String> list = new ArrayList<String>(), instead of
ArrayList<String> = new ArrayList<String>();
It is preferred because:
1. If later on code needs to be changed from Array List to Vector then only at the declaration
place we can do that.
2. The most important one – If a function is declared such that it takes list.
void show Details (List list);
When the parameter is declared as List to the function it can be called by passing any
subclass of List like ArrayList, Vector, LinkedList making the function more flexible
29. How do you sort an ArrayList (or any list) of user-defined objects ?
By default, the ArrayList’s elements are display according to the sequence it is put inside. Often
times, you may need to sort the ArrayList to make it alphabetically order. In this example, it
shows the use of Collections.sort(‘List’) to sort an ArrayList.
Incase of User defined objects like Employee, we have to create a new class which implements
the Comparator interface that knows how to order your objects and pass it to
java.util.Collections.sort(List, new EmployeeComparator).
The Comparable interface is used to sort collections and arrays of objects using the
Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class
implementing the Comparable interface can be ordered.
interface Comparable<T>
All classes implementing the Comparable interface must implement the compareTo() method
that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
Lakven Technologies
31. What are the differences between the Comparable and Comparator interfaces ?
Comparable Comparator
It is necessary to modify the class whose instance is A separate class can be created in order to sort the
going to be sorted. instances.
Only one sort sequence can be created. Many sort sequences can be created.
It is frequently used by the API classes. It used by third-party classes to sort instances.
If two objects are equal then they must have the same hashcode, however the reverse is
not true.
If two objects have the same hashcode does not mean that they are equal.
Note
If you override equals method in the class, you must override the hashcode also.
This divides the elements in a Set into number of sub sets and the newly inserting element will
be compared to the elements within the one of the sub sets. So the number of comparisons
required to identify whether the newly inserting element is equivalent to any of existing element
will be very less.
Eg: If a set contains 1000 elements and hashing algorithm divides them into 10 number of subsets
( buckets) and each and every bucket will contains 100 elements. Now the newly inserting elements
will be compared elements in one of the buckets so the number of comparisons will be maximum
100.
Lakven Technologies
Where as in case List if we want to maintain the unique elements the newly inserting element
should be compared all existing 1000 elements.
Hashing algorithm uses hash code of the objects to create the number of buckets. All the elements
having same/equal hashcode will be stored in single bucket.
When we insert new element hashing algorithm will take the hashcode of the new element and try
to identify the bucket whose hashcode same as the new element.
a) If the bucket is identified with same hash code of new element then the new element will be
compared with all the elements in that bucket. New element will not be added to the Set if it is
equivalent any of the elements in that bucket otherwise it will added in that bucket.
b) If NO bucket is identified with the hashcode of new element then new bucket will be created for
this element and add this to that bucket.
Note: HashSet and LinkedHashSet uses hashing algorithm to maintain the unique elements.
Lakven Technologies