java4all@1986 java. Powered by Blogger.

Methods of Map.entry Interface?

>> Monday, May 30, 2011

Map.Entry is an Interface ,it consists of  some methods.
   public  Object getKey(){};
  public Object getValue(){};

These methods can be used to get key and value fro a map;

Sample program:
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

public class Main {
  public static void main(String[] a) {
    Properties props = System.getProperties();
    Iterator iter = props.entrySet().iterator();

    while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry) iter.next();
      System.out.println(entry.getKey() + " -- " + entry.getValue());
    }

  }
}

OUTPUT::
sun.cpu.endian -- little
sun.desktop -- windows
sun.cpu.isalist --
 The output we got from system property files.

Read more...

How to create HashTable from HashMap?




import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;

public class Main {
  public static void main(String[] args) {

    HashMap hMap = new HashMap();

    hMap.put("1", "One");
    hMap.put("2", "Two");
    hMap.put("3", "Three");

    Hashtable ht = new Hashtable();
    ht.put("1", "REPLACED !!");
    ht.put("4", "Four");

    Enumeration e = ht.elements();
    while (e.hasMoreElements()){
      System.out.println(e.nextElement());
         }      

    ht.putAll(hMap);
    e = ht.elements();
System.out.println("in hashtable");
    while (e.hasMoreElements()){
    
     System.out.println(e.nextElement());
    }      
    
  }
}
 
OUTPUT:
Four
REPLACED !!
in hashtable
Four
Three
Two
One

Read more...

How do we will create Fake session in our application?

the following example describes how to create a fake session.
  
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

public class FakeHttpSession implements HttpSession
{
    /**
     * Setup the creation time
     */
    public FakeHttpSession()
    {
        creationTime = System.currentTimeMillis();
    }

    /**
     * Setup the creation time
     * @param id The new session id
     */
    public FakeHttpSession(String id)
    {
        this.id = id;
        creationTime = System.currentTimeMillis();
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#getCreationTime()
     */
    public long getCreationTime()
    {
        return creationTime;
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#getId()
     */
    public String getId()
    {
        if (id == null)
        {
            System.out.println("Inventing data in FakeHttpSession.getId() to remain plausible.");
            id = "fake";
        }

        return id;
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#getLastAccessedTime()
     */
    public long getLastAccessedTime()
    {
        return creationTime;
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#getServletContext()
     */
    public ServletContext getServletContext()
    {
        return null;
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#setMaxInactiveInterval(int)
     */
    public void setMaxInactiveInterval(int maxInactiveInterval)
    {
        this.maxInactiveInterval = maxInactiveInterval;
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#getMaxInactiveInterval()
     */
    public int getMaxInactiveInterval()
    {
        return maxInactiveInterval;
    }

    /**
     * @see javax.servlet.http.HttpSession#getSessionContext()
     * @deprecated
     */
    @SuppressWarnings({"UnnecessaryFullyQualifiedName"})
    @Deprecated
    public javax.servlet.http.HttpSessionContext getSessionContext()
    {
        return null;
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#getAttribute(java.lang.String)
     */
    public Object getAttribute(String name)
    {
        return attributes.get(name);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#getValue(java.lang.String)
     */
    @Deprecated
    public Object getValue(String name)
    {
        return attributes.get(name);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#getAttributeNames()
     */
    public Enumeration getAttributeNames()
    {
        return Collections.enumeration(attributes.keySet());
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#getValueNames()
     */
    @Deprecated
    public String[] getValueNames()
    {
        return attributes.keySet().toArray(new String[attributes.keySet().size()]);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#setAttribute(java.lang.String, java.lang.Object)
     */
    public void setAttribute(String name, Object value)
    {
        attributes.put(name, value);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#putValue(java.lang.String, java.lang.Object)
     */
    @Deprecated
    public void putValue(String name, Object value)
    {
        attributes.put(name, value);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#removeAttribute(java.lang.String)
     */
    public void removeAttribute(String name)
    {
        attributes.remove(name);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#removeValue(java.lang.String)
     */
    @Deprecated
    public void removeValue(String name)
    {
        attributes.remove(name);
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#invalidate()
     */
    public void invalidate()
    {
    }

    /* (non-Javadoc)
     * @see javax.servlet.http.HttpSession#isNew()
     */
    public boolean isNew()
    {
        return true;
    }

    /**
     * The session id
     */
    private String id = null;

    /**
     * The list of attributes
     */
    private Map attributes = new HashMap();

    /**
     * When were we created
     */
    private long creationTime;

    /**
     * How long before we timeout?
     */
    private int maxInactiveInterval = 30 * 60 * 1000;

}

   

Read more...

What are the Http Session Methods?

The below are the HttpSession methods ..
1.) getCreationTime()
    Returns the time at which this session representation
was created, in milliseconds since midnight, January 1, 1970
UTC.
2.) getId()
    Returns the identifier assigned to this session.
3.) getLastAccessedTime()
    Returns the last time the client sent a request carrying
the identifier assigned to the session.
4.) getMaxInactiveInterval()

    Returns the session-timeout in seconds.
5.) getSessionContext()
    Returns the context in which this session is bound.
Deprecated.
5.) getValue(String)
    Returns the object bound to the given name in the
session's application layer data.
6.) getValueNames()
    Returns an array of the names of all the application
layer data objects bound into the session.
7.) invalidate()
    Causes this representation of the session to be
invalidated and removed from its context.
8.) isNew()
    A session is considered to be "new" if it has been
created by the server, but the client has not yet
acknowledged joining the session.
9.) putValue(String, Object)
    Binds the specified object into the session's
application layer data with the given name.
10.) removeValue(String)

    Removes the object bound to the given name in the
session's application layer data.
11.) setMaxInactiveInterval(int)
    Sets the maximum interval between requests that this
session will be kept by the host server.

Read more...

How to create session Logger or how to get the session id?

To create session logger We need Logger from apache.
   look at the below example
 we will get log4j proreties from  http://javabysantosh.blogspot.com/search/label/Log4J
after that
     
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import javax.servlet.*;
import javax.servlet.http.*;

public class SessionLogger implements HttpSessionListener {

  private Logger log;

  public SessionLogger() {

    /*
     * The loggers are typically initialized by a special initialization
     * listener or servlet. If this is not the case, then initialize the
     * logger here:
     * 
     * java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle(
     * "com.java2s.global");
     * PropertyConfigurator.configure(bundle.getString(
     * "log-configure-path"));
     */

    log = Logger.getLogger(SessionLogger.class);

  }

  public void sessionCreated(HttpSessionEvent se) {

    //log request of the INFO level
    log.info("HttpSession created: " + se.getSession().getId());

  }

  public void sessionDestroyed(HttpSessionEvent se) {

    //log request about session's that are invalidated
    log.info("HttpSession invalidated: " + se.getSession().getId());

  }

}
 

The following are the HttpSession Methods
1.) getCreationTime()
Returns the time at which this session representation
was created, in milliseconds since midnight, January 1, 1970
UTC.
2.) getId()
Returns the identifier assigned to this session.
3.) getLastAccessedTime()
Returns the last time the client sent a request carrying
the identifier assigned to the session.
4.) getMaxInactiveInterval() 
to return session time-out  in seconds
5.)getSessionContext()
Returns the context in which this session is bound.
Deprecated.
5.) getValue(String)
Returns the object bound to the given name in the
session's application layer data.
6.) getValueNames()
Returns an array of the names of all the application
layer data objects bound into the session.
7.) invalidate()
Causes this representation of the session to be
invalidated and removed from its context.
8.) isNew()
A session is considered to be "new" if it has been
created by the server, but the client has not yet
acknowledged joining the session.
9.) putValue(String, Object)
Binds the specified object into the session's
application layer data with the given name.
10.) removeValue(String)
Removes the object bound to the given name in the
session's application layer data.
11.) setMaxInactiveInterval(int)
Sets the maximum interval between requests that this
session will be kept by the host server.

Read more...

In servlet how to increase session time-out programitacally?

Session:It is the time duration,which starts the starting point of client to server conversation and which terminates the end point of server to client conversation.


Example:
    
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SimpleSession extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
  Start body tag

    out.println("

Session Info

"); out.println("session Id: " + session.getId() + "

"); out.println("The SESSION TIMEOUT period is " + session.getMaxInactiveInterval() + " seconds.

"); out.println("Now changing it to 20 minutes.

"); session.setMaxInactiveInterval(20 * 60);//it can be used to set session programitically out.println("The SESSION TIMEOUT period is now " + session.getMaxInactiveInterval() + " seconds."); end body tag } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { doGet(request, response); } }

Read more...

Where we will maintain the Session timout in our application?

In our application we will maintain the session time-out in web.XML file under session-config tag,the below code explain ....
<web-app>
  <session-config>
    <session-timeout>120<session-timeout>
  <session-config>
<web-app>

Read more...

What is meant by String ConstantPoll?

ConstantPoll:When we created a String Object with Assignment operator i.e String s="bhaskar" ;
The String object is stored in Constant Poll not in heap area.If the object is available in Constant poll it Just take the Reference of the Object Not creating another .that means  If we are creating String s1="bhaskar" first JVM checks the object is available in ConstantPoll are not.If it is not available it creates a new object in Constant poll;.If available it just take it reference.
  Example:
String s="Veeru";
String s1="Bhaskar";
String s2="bhaskar";
Here totally two objects are created.

Read more...

What is the difference between yield and sleeping? What is the difference between the methods sleep() and wait()?

When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it
changes from running state to waiting/sleeping state.
The method wait(1000), causes the current thread to sleep up to one second. A thread could sleep less than 1
second if it receives the notify() or notifyAll() method call. The call to sleep(1000) causes the current thread to sleep for exactly 1 second.

Read more...

Levels of threads.?

Runnable — waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
 Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily  gives up its turn with this static method Thread.yield(). Because of context switching overhead, yield() should
not be used very frequently.
 Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
 Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method:
Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
 Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
 Blocked on synchronization: Will move to Runnable when a lock is acquired.
 Dead: The thread is finished working.

Read more...

Among runnable Interface (or) Thread class which one is preferable?

The Runnable interface is preferred, as it does not require your
object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above
example we had to extend the Base class so implementing Runnable interface is an obvious choice. Also note
how the threads are started in each of the different cases as shown in the code sample.
In an OO approach you should only extend a class when you want to make it different from it’s superclass, and change it’s behavior. By
implementing a Runnable interface instead of extending the Thread class, you are telling to the user that the class
Counter that an object of type Counter will run as a thread.

Read more...

Explain different ways of thread?

Threads can be used by either :
 Extending the Thread class
 Implementing the Runnable interface

Examples::
class Counter extends Thread {
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let’s see how to start the threads
public static void main(String[] args){
Thread t1 = new Counter();
Thread t2 = new Counter();
t1.start(); //start the first thread. This calls the run() method.
t2.start(); //this starts the 2nd thread. This calls the run() method.
}
}
class Counter extends Base implements Runnable {
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let us see how to start the threads
public static void main(String[] args){
Thread t1 = new Thread(new Counter());
Thread t2 = new Thread(new Counter());
t1.start(); //start the first thread. This calls the run() method.
t2.start(); //this starts the 2nd thread. This calls the run() method.
}
}

Read more...

What is difference between process and threads?

A process is an execution of a program but a thread is a single execution sequence within the process. A process
can contain multiple threads. A thread is sometimes called a lightweight process
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why
several threads may access the same object. Threads share the heap and have their own stack space. This is
how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the
heap is not thread-safe and must be synchronized for thread safety.

Read more...

What is user Defined Exception?

User defined exceptions may be implemented by defining a new exception class by extending the Exception class.
           look the example:
public class MyException extends Exception {
/* class definition of constructors goes here */
public MyException() {
super();
}
public MyException (String errorMessage) {
super (errorMessage);
}
}

Throw and/or throws statement is used to signal the occurrence of an exception. To throw an exception:
throw new MyException(“I threw my own exception.”)
To declare an exception: public myMethod() throws MyException {…}
.

Read more...

Why should you catch a checked exception late in a catch {} block?

You should not try to catch the exception before your program can handle it in an appropriate manner. The natural tendency when a compiler complains about a checked exception is to catch it so that the compiler stops reporting errors.
It is a bad practice to sweep the exceptions under the carpet by catching it and not doing anything with it.
The best practice is to catch the exception at the appropriate layer (e.g. an exception thrown at an integration layer can be caught at a presentation layer in a catch {} block), where your program can either meaningfully recover from the exception and continue to execute or log the exception only once in detail, so that user can identify the cause of the exception.

Read more...

What are the Java Modifiers?

static:
Class:A static inner class is just an inner
class associated with the class,
rather than with an instance of the
class.
Methods:A static method is called by class name.method
(e.g Math.random()), can only access static
variables.
Variables:Class variables are
called static variables.
There is only one
occurrence of a class
variable per JVM per
class loader.

abstract:
class:An abstract class cannot be
instantiated, must be a superclass
and a class must be declared
abstract whenever one or more
methods are abstract.
methods:Method is defined but contains no
implementation code (implementation code is
included in the subclass). If a method is
abstract then the entire class must be abstract.
variables:N/A

synchronized:N/A
methods:
Acquires a lock on the class for static
methods.
Acquires a lock on the instance for nonstatic
methods.
variables:N/A
transient:
class::N/A
methods::N/A
variables:variable should not be
serialized.

final:
class:It cannot inherited.
methods:Method cannot be overridden.
variables:variable should not be
serialized.

native:
class:N/A
methods:Platform dependent. No body, only signature.
variables:N/A

Read more...

Where and How you can use private Constructor?

Private constructor is used if you do not want other classes to instantiate the object and to prevent subclassing.
The instantiation is done by a public static method within the same class.
Used in the singleton design pattern. Used in the factory method design pattern e.g. java.util.Collections class .
Used in utility classes e.g. StringUtils etc.

Read more...

Difference between public,protected,private,default?

public(Modifier): It is used in  Outer classes, interfaces,
constructors, Inner classes, methods
and field variables.
Description:A class or interface may be accessed from outside the
package. Constructors, inner classes, methods and field
variables may be accessed wherever their class is
accessed.

protected:Constructors, inner classes, methods,
and field variables.
Description:Accessed by other classes in the same package or any
subclasses of the class in which they are referred (i.e. same
package or different package).

private:Constructors, inner classes,
methods and field variables,
Description:Accessed only within the class in which they are declared

<Default>:Outer classes, inner classes,
interfaces, constructors, methods, and
field variables
Description:Accessed only from within the package in which they are
declared.

Read more...

Give an example where you might use a static method?

 Static methods prove useful for creating utility classes, singleton classes and factory methods.
Utility classes are not meant to be instantiated. Improper coding of utility classes can lead to
procedural coding. java.lang.Math, java.util.Collections etc are examples of utility classes in Java.

Read more...

What is difference between String and String Builder/String Buffer?

String:  
              1.)String is immutable: you can’t modify a string
            object but can replace it by creating a new
            instance. Creating a new instance is rather
            expensive.
           2.)//Inefficient version using immutable String
String output = “Some text”
Int count = 100;
for(int i =0; i<count; i++) {
output += i;
}
return output;
3.)3.)The above code would build 99 new String
objects, of which 98 would be thrown away
immediately. Creating new objects is not
efficient.

 StringBuffer / StringBuilder (added in J2SE 5.0)
1.)StringBuffer is mutable: use StringBuffer or StringBuilder when you want
to modify the contents. StringBuilder was added in Java 5 and it is
identical in all respects to StringBuffer except that it is not synchronized,
which makes it slightly faster at the cost of not being thread-safe.
2.)//More efficient version using mutable StringBuffer
StringBuffer output = new StringBuffer(110);// set an initial size of 110
output.append(“Some text”);
for(int i =0; i<count; i++) {
output.append(i);
}
return output.toString();
3.)The above code creates only two new objects, the StringBuffer and the
final String that is returned. StringBuffer expands as needed, which is
costly however, so it would be better to initialize the StringBuffer with the
correct size from the start as shown.
       

Read more...

What are the methods in java.lang.object?

The non-final methods are equals(), hashCode(), toString(), clone(), and finalize(). The other methods like
wait(), notify(), notifyAll(), getClass() etc are final methods and therefore cannot be overridden.

equals():  This method checks if some other object passed to it as an argument is equal the object in which this method is
invoked.
public class Pet {
int id;
String name;
public boolean equals(Object obj){
if(this == obj) return true; // if both are referring to the same object
if ((obj == null) || (obj.getClass() != this.getClass())) {
return false;
}
Pet rhs = (Pet) obj;
return id == rhs.id && (name == rhs.name ||
(name != null && name.equals(rhs.name)) );
}
//hashCode() method must be implemented here.
…
}
hashCode(): This method returns a hashCode() value as an Integer and is supported for the benefit of hashing based
java.util.Collection classes like Hashtable, HashMap, HashSet etc. If a class overrides the equals() method, it
must implement the hashCode() method as well. The general contract of the hashCode() method is that:
1. Whenever hashCode() method is invoked on the same object more than once during an execution of a Java
program, this method must consistently return the same integer result. The integer result need not remain
consistent from one execution of the program to the next execution of the same program.
2. If two objects are equal as per the equals() method, then calling the hashCode() method in each of the two
objects must return the same integer result. So, If a field is not used in equals(), then it must not be used in
hashCode() method.
3. If two objects are unequal as per the equals() method, each of the two objects can return either two different
integer results or same integer results (i.e. if 2 objects have the same hashCode() result does not mean that they
are equal, but if two objects are equal then they must return the same hashCode() result).
Example:
public class Pet {
int id;
String name;
public boolean equals(Object obj){
//as shown above.
}
//both fields id & name are used in equals(), so both fields must be used in
//hashCode() as well.
public int hashCode() {
int hash = 9;
hash = (31 * hash) + id;
hash = (31 * hash) + (null == name ? 0 : name.hashCode());
return hash;
}
}

toString(): The toString() method provided by the java.lang.Object returns a string, which consists of the class name followed by an “@” sign and then unsigned hexadecimal representation of the hashcode, for example Pet@162b91. This hexadecimal representation is not what the users of your class want to see.
Example:
public class Pet {
int id;
String name;
public boolean equals(Object obj){
//as shown above.
}
public int hashCode() {
//as shown before
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(“id=”).append(id);
sb.append(“,name=”).append(name);
return sb.toString();
}
}

clone(): It can be used to create a bitwise of exact copy of original object.


The above four are non final methods.

Read more...

What is difference between == and equals methos in Strings?

==: It can be used to compare the reference variables not the content in the String.

Equals():It can be used to compare the string contents .
   Just look on the following example:
public class StringBasics {
public static void main(String[] args) {
String s1 = new String("A"); //not recommended, use String s1 = "A"
String s2 = new String("A"); //not recommended, use String s2 = "A"
//standard: follows the == and equals() rule like plain java objects.
if (s1 == s2) { //shallow comparison
System.out.println("references/identities are equal"); //never reaches here
}
if (s1.equals(s2)) { //deep comparison
System.out.println("values are equal"); // this line is printed
}
//variation: does not follow the == and equals rule
String s3 = "A"; //goes into a String pool.
String s4 = "A"; //refers to String already in the pool.
if (s3 == s4) { //shallow comparison
System.out.println("references/identities are equal"); //this line is printed
}
if (s3.equals(s4)) { //deep comparison
System.out.println("values are equal"); //this line is also printed
}
}
}
                                                            
Design Pattern: String class is designed with Flyweight design pattern. When you create a String constant as shown
above in the variation, (i.e. String s3 = “A”, s4= “A”), it will be checked to see if it is already in the String pool. If it is in the
pool, it will be picked up from the pool instead of creating a new one. Flyweights are shared objects and using them can
result in substantial performance gains.            

Read more...

What are the advantages of collection Framework?

Advantages: Collections framework provides flexibility, performance,
and robustness.

Polymorphic algorithms – sorting, shuffling, reversing, binary search etc.
1.) Set algebra - such as finding subsets, intersections, and unions between objects.
 2.)Performance - collections have much better performance compared to the older Vector and Hashtable classes with
the elimination of synchronization overheads.
 3.)Thread-safety - when synchronization is required, wrapper implementations are provided for temporarily
4.)synchronizing existing collection objects. For J2SE 5.0 use java.util.concurrent package.
 Immutability - when immutability is required wrapper implementations are provided for making a collection
immutable.
5.) Extensibility - interfaces and abstract classes provide an excellent starting point for adding functionality and
features to create specialized object collections

Read more...

Difference between Iterator,ListIterator and Enumeratio?

Iterator:It is an interface, which can be used to iterate objects in forward Direction.
     Following are the methods of Iterator,
     1.)public boolean hasNext(){};
      2.)public object next(){};
       3.)public void remove(){};

ListIterator:It is an interface ,which can be used to iterate objects in forward direction as well as in Backward direction.
          Following are the methods of ListIterator,
        1.)public boolean hasNext(){};
      2.)public object next(){};
       3.)public void remove(){};
       4.)public boolean hasPerivous(){};
       5.)public object perivous(){};

Enumeration: It is an interface which can be used to iterate objects in forward direction.But it doesn't havr a method to remove object.
        Following are the methods of Enumeration,
      1.)public boolean hasMoreElement(){};
       2.)public object nextElement(){};

Read more...

What is meant By JDBC?

JDBC: The process of interacting with Data Base from Java Application.
  
 But as per JDBC application we will write Data Base Logic in Java Application,When we sent the Data Base logic to Data Base ,the Data Base Engine Could Not understand the Java provided DataBase logic,Why because Data Base Engine could understand only Query Language.In order to convert  the Java Language to Query Language and Query Language to Java Language we need an Interface Between between Java Application and Data Base.The interface which we are using in between Java Application and Data Base is called as "Driver".This Driver can be used to convert 
Java Language to Query Language and Query Language to Java Language.

Read more...

Difference Between Comparable and Comparator Interface?

Comparable interface:
1.The “Comparable” allows itself to compare with another
similar object (i.e. A class that implements Comparable
becomes an object to be compared with). The method
compareTo() is specified in the interface.
2.Many of the standard classes in the Java library like String,
Integer, Date, File etc implement the Comparable interface
to give the class a "Natural Ordering". For example String
class uses the following methods:
3.public int compareTo(o)
public int compareToIgnoreCase(str)
4.
public class Pet implements Comparable {
int petId;
String petType;
public Pet(int argPetId, String argPetType) {
petId = argPetId;
this.petType = argPetType;
}
public int compareTo(Object o) {
Pet petAnother = (Pet)o;
//natural alphabetical ordering by type
//if equal returns 0, if greater returns +ve int,
//if less returns -ve int
return this.petType.compareTo(petAnother.petType);
}
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Pet(2, "Dog"));
list.add(new Pet(1, "Parrot"));
list.add(new Pet(2, "Cat"));
Collections.sort(list); // sorts using compareTo method
for (Iterator iter = list.iterator(); iter.hasNext();) {
Pet element = (Pet) iter.next();
System.out.println(element);
}
}
public String toString() {
return petType;
}
}
Output: Cat, Dog, Parrot
Comparator interface:
1.The Comparator is used to compare two different objects. The
following method is specified in the Comparator interface.
public int compare(Object o1, Object o2)
2.You can have more control by writing your Comparator class. Let us
write a Comparator for the Pet class shown on the left. For most cases
natural ordering is fine as shown on the left but say we require a
special scenario where we need to first sort by the “petId” and then by
the “petType”. We can achieve this by writing a “Comparator” class.
3.
public class PetComparator implements Comparator, Serializable{
public int compare(Object o1, Object o2) {
int result = 0;
Pet pet = (Pet)o1;
Pet petAnother = (Pet)o2;
//use Integer class's natural ordering
Integer pId = new Integer(pet.getPetId());
Integer pAnotherId = new Integer(petAnother.getPetId());
result = pId.compareTo(pAnotherId);
//if ids are same compare by petType
if(result == 0) {
result= pet.getPetType().compareTo
(petAnother.getPetType());
}
return result;
}
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Pet(2, "Dog"));
list.add(new Pet(1, "Parrot"));
list.add(new Pet(2, "Cat"));
Collections.sort(list, new PetComparator());
for (Iterator iter = list.iterator(); iter.hasNext();){
Pet element = (Pet) iter.next();
System.out.println(element);
}
}
}
Output: Parrot, Cat, Dog.

Read more...

Difference between Method Overloading and Method Overriding?

Method Overloading :
1.Overloading deals with multiple methods in the same class
with the same name but different method signatures.
2.
class MyClass {
public void getInvestAmount(int rate) {…}
public void getInvestAmount(int rate, long principal)
{ … }
}
3.Both the above methods have the same method names
but different method signatures, which mean the methods
are overloaded
4.Overloading lets you define the same operation in
different ways for different data.
Method Overriding:
1.Overriding deals with two methods, one in the parent class and
the other one in the child class and has the same name and
signatures.
2.class BaseClass{
public void getInvestAmount(int rate) {…}
}
class MyClass extends BaseClass {
public void getInvestAmount(int rate) { …}
}
3.Both the above methods have the same method names and
the signatures but the method in the subclass MyClass
overrides the method in the superclass BaseClass.
4.Overriding lets you define the same operation in different
ways for different object types.

Read more...

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP