Search
Friday, June 13, 2014
Sunday, May 25, 2014
In Java , If two interfaces have same method signature and a class implements both , would it give problem ?
Example : Two interface as below :
Interface 1 :
public interface InterKap {
void show();
void abc();
int show(int k);
}
Interface :2
public interface InterKap2 {
void show();
void xyz();
int show(String k);
}
Implementing Class :
public class TestInerface implements InterKap , InterKap2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public void show() {
// TODO Auto-generated method stub
}
@Override
public void xyz() {
// TODO Auto-generated method stub
}
@Override
public void abc() {
// TODO Auto-generated method stub
}
@Override
public int show(String k) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int show(int k) {
// TODO Auto-generated method stub
return 0;
}
}
Cheers
Kapil
How many ways we can achieve ordering while adding records in MAP ?
java.util.HashMap is unordered; you can't and shouldn't assume anything beyond that.
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
java.util.LinkedHashMap uses insertion-order.
This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
java.util.TreeMap, a SortedMap, uses either natural or custom ordering of the keys.
The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
Cheers
Kapil
Thursday, July 14, 2011
What all available XMl Parser API and explain the featurs and benefits of those
Table 5-1 XML Parser API Feature Summary
| Feature | StAX | SAX | DOM | TrAX |
|---|---|---|---|---|
| API Type | Pull, streaming | Push, streaming | In memory tree | XSLT Rule |
| Ease of Use | High | Medium | High | Medium |
| XPath Capability | No | No | Yes | Yes |
| CPU and Memory Efficiency | Good | Good | Varies | Varies |
| Forward Only | Yes | Yes | No | No |
| Read XML | Yes | Yes | Yes | Yes |
| Write XML | Yes | No | Yes | Yes |
| Create, Read, Update, Delete Cheers Kapil |
No | No | Yes | No |
Wednesday, June 1, 2011
Rule to remember : Overrriding in Java
package SCJP;
/* A way to inherit behavior(function) of base class by sub class is called overriding
* 1.visibility can not reduce in overriding
* public -> private (Wrong)
* private -> protected , public (Right)
*
* 2. Exceptions can be allow in specialized manner or none(super -> subclass)
* RuntimeExcept -> Excpetion , RuntimeException (right)
*
*/
class override1 {
int show(int k) throws RuntimeException, Exception { return 0;}
public int show(String l){return 1;}
}
class override2 extends override1 {
//private int show(int j) throws RuntimeException{return 9;}
protected int show(int k) throws Exception {return 3;}
}
public class overrideDemo {
public static void main(String args[]) {
override1 ov1 = new override2();
try {
try {
System.out.println(ov1.show(6));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Monday, May 30, 2011
Understanding JVM - Java
Understanding JVM
JVM (Java Virtual Machine) is all about,an abstract specification; which is a conceptEvery java application will be running in a separate JVM instance even if they are in the same machine. The JVM starts the execution of a Java application from an initial class’ main method. The “java” program from Sun’s JDK is an implementation of a java virtual machine.
a concrete implementation; which runs on many platforms (can be a combination of hardware and software)
a runtime instance; which can host a single java application (each runs on different JVM)
“java
JVM Architecture
Major subsystemsClass loader subsystem:Other components
Responsible for loading classes and interfaces
Execution engine:
Responsible for the execution of the instructions specified in the classes
Runtime data areas
Native interface; interacts with the native libraries
More about runtime data areas
Mechanism to hold all kinds of data items such as instructions, object data, local variable data, return values & intermediate results.
Organization of runtime data areas
How runtime data are stored in the runtime data areas depends on the implementation of the JVM. Some implementation may enjoy the availability of memory and some others may not. The abstract nature of runtime data area specification allows the implementation of JVM in different machines easier.
Some runtime data areas are shared among all the threads in the application, while some others are too specific to an active thread.
Runtime data areas shared among all threads:
Method area: holds the details of each class loaded by the class loader subsystem.Thread specific runtime data areas:
Heap: holds every object being created by the threads during execution
Program counter register:Note:
points to the next instruction to be executed.
Java stack:
hold the state of each method (java method, not a native method) invocations for the thread such as the local variables, method arguments, return values, intermediate results. Each entry in the Java stack is called “stack frames“. Whenever a method is invoked a new stack frame is added to the stack and corresponding frame is removed when its execution is completed.
Native method stack:
holds the state of each native method call in an implementation dependent way.
In JVM there is no registers to store the intermediate values. They are stored in the java stack itself.
Disclaimer : The above contents are taken from the following post :
http://javabeanz.wordpress.com/2007/07/09/understanding-jvm/
Monday, May 9, 2011
What is the difference between Authentication and Authorization ??
What is Authentication?
Authentication is the process of verifying who someone is. It answers the fundamental question: "Are you who you claim to be?"
When you log into a website or an application, authentication mechanisms work to confirm your identity. Common methods include:
Passwords: The most traditional form of authentication, where you enter a secret code known only to you.
Biometric Verification: Such as fingerprint scans, facial recognition, or voice recognition.
Multi-Factor Authentication (MFA): Combines two or more verification methods, such as a password and a one-time code sent to your phone.
What is Authorization?
Authorization comes after authentication and determines what resources or actions you are permitted to access. It answers the question: "What are you allowed to do?"
For example, after logging into an online banking portal, you may be authorized to view your account balance, transfer money, or pay bills. However, you wouldn't be authorized to access the accounts of other users.
Key points about authorization include:
Role-Based Access Control (RBAC): Access permissions are granted based on user roles (e.g., admin, editor, viewer).
Permission Levels: Users may have specific permissions that dictate what actions they can perform within a system.
Granularity: Authorization can be fine-tuned to allow or restrict access to specific data, features, or tools.
Cheers !!
Wednesday, April 13, 2011
What is the Differenece between arrayList and Vector
ArrayList and Vector are very similar to each other. Difference between ArrayList and Vector is as given below
1) ArrayList is not synchronized, while Vector is synchronized.
Vector is synchronized, so its thread safe, ArrayList is not thread safe. Synchronization causes the performance penalty. So if thread safe collection is not needed then ArrayList should be used instead of the Vector.
2) ArrayList and Vector both are resizable array, and internally uses the array to hold elements of the list. Capacity of the ArrayList or Vector grows automatically as we add elements to it. By default Vector doubles the capacity when needed, while ArrayList increases the capacity by half.
Friday, April 1, 2011
Rules to Remember - Boxing Java 5
package SCJP;
/** Rules to Remember :
*
* Auto boxing and unboxing allow to implicit cast
* in between wrapper classes and those primitive types
* 1. Primitive to Object - Auto Boxing
* 2. Object to Primitive - Un Boxing
* 3. Null Pointer in case if null object assign to primitive - care full
*/
import static java.lang.System.out;
public class boxingDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 10;
Integer WrapperInt = i; // 1. Autoboxing primitive assign to object
out.println(WrapperInt);
Float Wrapf = new Float("34.78");
float primf = 56.78f; //2. f suffix required for float
primf = Wrapf; // Unboxing
out.println(primf);
Integer j = null;
int k = j; //3. NullPointer exception while assigning null object to primitive
}
}
Wednesday, March 23, 2011
Rules to remember : Abstract class - Java
package abstractclass;
/**
* Rule to remember :
* 1. Abstract call can never be instantiate either it has defination
* or not have defination(ERROR4 and ERROR5).
* 2. Compiler treat abstract keyword specially not to instantiate and not to defined(ERROR1 and ERROR4).
* 3. Only and Only Method can be declare abstract into abstract class - ERROR 2
* 4. An Abstract class is possible without any abstract method in java but there is not sense then .
* 5. Abstract methods only possible to have public and protected modifier - ERROR 3 Private is not possible
6. Abstract class can have static members since static loads with class loading (no need to create instance) we can directly call static members with class name ..)
*
* @author Kapil
*
*/
abstract class abs1 {
//protected abstract void show(){} // ERROR 1 - abstract method can not specify body
protected String show(String name) { //CASE 1 - a class can be declare abstarct without abstract member(method)
return name;
}
//public abstract int num; // ERROR 2- not possible , only mehotd can declare abstract
//protected abstract void show(); // CORRECT
//private abstract void show(); // ERROR 3- Not possible because no sense to keep abstract method private.it should be public or protected
}
public class abstractDemo1 {
public static void main (String args[]) {
//abs1 a = new abs1(); // ERROR 4 - can not be instantiates - compiler error
//abs1.class(); // ERROR 5 - not possible - compiler error
}
}
Tuesday, March 8, 2011
What is connection pooiling , how to implement it ?
Following example shows the implementation of database connection pooling :
package pool;
import java.sql.*;
import java.util.*;
import java.io.*;
class ConnectionReaper extends Thread {
private JDCConnectionPool pool;
private final long delay=300000;
ConnectionReaper(JDCConnectionPool pool) {
this.pool=pool;
}
public void run() {
while(true) {
try {
sleep(delay);
} catch( InterruptedException e) { }
pool.reapConnections();
}
}
}
public class JDCConnectionPool {
private Vector connections;
private String url, user, password;
final private long timeout=60000;
private ConnectionReaper reaper;
final private int poolsize=10;
public JDCConnectionPool(String url, String user, String password) {
this.url = url;
this.user = user;
this.password = password;
connections = new Vector(poolsize);
reaper = new ConnectionReaper(this);
reaper.start();
}
public synchronized void reapConnections() {
long stale = System.currentTimeMillis() - timeout;
Enumeration connlist = connections.elements();
while((connlist != null) && (connlist.hasMoreElements())) {
JDCConnection conn = (JDCConnection)connlist.nextElement();
if((conn.inUse()) && (stale >conn.getLastUse()) &&
(!conn.validate())) {
removeConnection(conn);
}
}
}
public synchronized void closeConnections() {
Enumeration connlist = connections.elements();
while((connlist != null) && (connlist.hasMoreElements())) {
JDCConnection conn = (JDCConnection)connlist.nextElement();
removeConnection(conn);
}
}
private synchronized void removeConnection(JDCConnection conn) {
connections.removeElement(conn);
}
public synchronized Connection getConnection() throws SQLException {
JDCConnection c;
for(int i = 0; i < connections.size(); i++) {
c = (JDCConnection)connections.elementAt(i);
if (c.lease()) {
return c;
}
}
Connection conn = DriverManager.getConnection(url, user, password);
c = new JDCConnection(conn, this);
c.lease();
connections.addElement(c);
return c;
}
public synchronized void returnConnection(JDCConnection conn) {
conn.expireLease();
}
}Monday, March 7, 2011
Java Collections Questions
Map is Interface and Hashmap is class that implements this interface.
What is the significance of ListIterator?
Or
What is the difference b/w Iterator and ListIterator?
Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements
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.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Note on Some Important Terms
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);
What is the difference between set and list?
A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.
Difference between Vector and ArrayList? What is the Vector class?
Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. ArrayList has no default size while vector has a default size of 10. when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.
What is an Iterator interface? Is Iterator a Class or Interface? What is its use?
The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.
What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
What is the List interface?
The List interface provides support for ordered collections of objects.
How can we access elements of a collection?
We can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.
What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
What’s the difference between a queue and a stack?
Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-first-out (FIFO) rule.
What is the Map interface?
The Map interface is used associate keys with values.
What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
a. Vector
b. ArrayList
c. LinkedList
d. None of the above
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.
How can we use hashset in collection interface?
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.
What are differences between Enumeration, ArrayList, Hashtable and Collections and Collection?
Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You can not remove elements from Enumeration.
ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements, including null. It is not thread -safe.
Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in collection.
Collections: It implements Polymorphic algorithms which operate on collections.
Collection: It is the root interface in the collection hierarchy.
What is difference between array & arraylist?
An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.
Array: can store primitive ArrayList: Stores object only
Array: fix size ArrayList: resizable
Array: can have multi dimensional
Array: lang ArrayList: Collection framework
Can you limit the initial capacity of vector in java?
Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity
public vector(int initialcapacity)
What method should the key class of Hashmap override?
The methods to override are equals() and hashCode().
What is the difference between Enumeration and Iterator?
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.
So Enumeration is used when ever we want to make Collection objects as Read-only.
Saturday, December 25, 2010
What is the mean of i18n and l10n ??
2. l10n is abbreviation of Localization because 10 letters come in between 'L' and 'n'.
Cheers
Sunday, October 10, 2010
What is serialization ?? How can we achieve it using Java and Why it is required ??
Serialization is the process of saving an object's state to a sequence of bytes; deserialization is the process of rebuilding those bytes into a live object.
How can we achieve it using Java ??
The Java Serialization API provides a standard mechanism for developers to handle object serialization
A Typical Serialization Algorithm does following:
- It writes out the metadata of the class associated with an instance.
- It recursively writes out the description of the superclass until it finds
java.lang.object. - Once it finishes writing the metadata information, it then starts with the actual data associated with the instance. But this time, it starts from the topmost superclass.
- It recursively writes the data associated with the instance, starting from the least superclass to the most-derived class.
Saturday, April 24, 2010
What is the difference between SAX and DOM parser
SAX:
1. Parses node by node (Event based).
2. Doesnt store the XML in memory.
3. We can't insert or delete a node.
4. Top to bottom traversing.
DOM
1. Stores the entire XML document into memory before processing
2. Occupies more memory.
3. We can insert or delete nodes.
4. Traverse in any direction.
For large documents SAX is better choice rather than DOM as it does not consume memory of JVM.
Friday, April 23, 2010
What is the difference between an instance variable and a static variable?
Instance variable : Is called object variable and there is only one copy per object .
Static variable act as Global variable and shared across the all instances of the class.
Saturday, April 17, 2010
What is JUnit ? What is coding convention of Unit test case class?
2. Following are coding convention to wirte test class :
Coding Convention :
1. Name of the test class must end with "Test".
2. Name of the method must begin with "test".
3. Return type of a test method must be void.
4. Test method must not throw any exception.
5. Test method must not have any parameter.
i.e :
Normal Version :
class Employee { public String name (String name) {return name;}}
Junit test case version :
class EmployeeTest extends TestCase {
Employee e = new Employee();
public void testName() {
assertEquals("kapil " , e.name("kapil"));
}
}
What is log4j ? How can we implement it? Explain log4j property ?
2. There are few steps to implement it into the project .
Step1 : download log4j.jar from apache web site and set into class path .
Step 2 : Create one log4j.properties and set into class path.
log4j prop file should have following value with naming convention as shown below :
log4j.rootLogger=ERROR, stdout, logfile // stdout to pring on console , logfile to print log into file
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=logs/sample.log
log4j.appender.logfile.MaxFileSize=5MB
log4j.appender.logfile.MaxBackupIndex=3
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.logger.com.sample=DEBUG
That's it .. Here I have used two type of appender , console and file but there lot more also available to configure. Appenders are which helps to print log.
Converiosn patterns Layout decide the pattern of printing . d - date , p - type , c - class name , m - message , n - name
And last line is used for filtering and type according to your packages to make the decision of log printing.
Here under com.sample package all classes debug log message will print if log4j Logger has set into class as following :
private static Logger _log= Logger.getLogger("com.sample.tutorials.main.SpringMain");
_log.debug("test debug");
Note : XML (log4j.xml) is also another way to configure the log4j logger.
Friday, April 16, 2010
is locking possible on primitive type or on static variable
i.e Synchronized works with the object and methods only.